Add Downloaded files to ListView | Click Listener on Downloaded files to open Particular App
Add Downloaded files to ListView | Click Listener on Downloaded files to open Particular App
In this post, We will add Downloaded Files to SQLite Database and then retrieve data from Sqlite and show it on a ListView. Also, we add a Click Listener on ListView item and open that Downloaded item with particular app.
To create a full WebView follow our previous posts.
For that, We create a DatabaseHelper.java class file and add a new Downloads Table and its values.
DatabaseHelper.java
package studio.harpreet.mybrowser;
import android.app.ActionBar;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.strictmode.SqliteObjectLeakedViolation;
import android.provider.ContactsContract;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.HashMap;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String Database_name = "Downloads.db";
public static final String Table_Download = "Downloads";
public static final String down_id = "Id_download";
public static final String down_title = "Title";
public static final String down_time = "Time";
public static final String down_path = "Path";
public DatabaseHelper(@Nullable Context context) {
super(context, Database_name, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_Download +" (Id_download INTEGER PRIMARY KEY AUTOINCREMENT, Title TEXT , Time TEXT, Path TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+Table_Download);
onCreate(sqLiteDatabase);
}
public boolean insertDataDownload(String Title,String Time, String Path)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(down_title,Title);
cv.put(down_time,Time);
cv.put(down_path,Path);
Long result = db.insert(Table_Download,null,cv);
if(result == -1 )
{
return false;
}
else
{
return true;
}
}
public ArrayList<HashMap<String,String>> ShowdataDownload()
{
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<HashMap<String,String>> downlist = new ArrayList<>();
Cursor cursor = db.rawQuery("select * from "+Table_Download,null);
while(cursor.moveToNext())
{
HashMap<String,String> user = new HashMap<>();
user.put("Id_download",cursor.getString(cursor.getColumnIndex(down_id)));
user.put("Title",cursor.getString(cursor.getColumnIndex(down_title)));
user.put("Time",cursor.getString(cursor.getColumnIndex(down_time)));
user.put("Path",cursor.getString(cursor.getColumnIndex(down_path)));
downlist.add(user);
}
return downlist;
}
}
Then We Add a Download Listener and Then create an add-data method for adding data to Database.
Use Download Listener and Add Download methods in MainActivity.java
Create a context menu or use Download Listener with WebView.
MainActivity.java
Create a new activity called Downloads.java to show List view with Downloaded file.
activity_downloads.xml
A custom List for ListView with 4 TextViews.
download_custom_list.xml
Use Download Listener and Add Download methods in MainActivity.java
Create a context menu or use Download Listener with WebView.
MainActivity.java
public void DowloadDialog(final String url, final String UserAgent, String contentdisposition, String mimetype)
{
final String filename = URLUtil.guessFileName(url,contentdisposition,mimetype);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Downloading...")
.setMessage("Do you want to Download "+ ' '+" "+filename+" "+' ')
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
String cookie = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("Cookie",cookie);
request.addRequestHeader("User-Agent",UserAgent);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager manager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filename);
manager.enqueue(request);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-YYYY , hh:mm a", Locale.getDefault());
File path = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + filename);
addDownload(filename,sdf.format(new Date()),String.valueOf(path));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
})
.show();
}
public void addDownload(String Title,String Time,String Path)
{
String title = Title;
String time = Time;
String path = Path;
boolean isInserted = mydb.insertDataDownload(title,time,path);
if(isInserted)
{
Toast.makeText(this, "Download Added", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Error adding Downloads", Toast.LENGTH_SHORT).show();
}
}
Create a new activity called Downloads.java to show List view with Downloaded file.
activity_downloads.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:layout_scrollFlags="scroll|enterAlways|snap"
app:title="Downloads"
app:titleTextColor="@color/white">
</androidx.appcompat.widget.Toolbar>
<ListView
android:layout_height="wrap_content"
android:id="@+id/downloadlistview"
android:layout_width="match_parent">
</ListView>
<LinearLayout
android:id="@+id/emptyList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_vertical"
android:text="WHOOPS"
android:textColor="#212121"
android:textSize="26sp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="20sp"
android:text="There are no Downloads at the moment"
android:textColor="#212121" />
</LinearLayout>
</LinearLayout>
A custom List for ListView with 4 TextViews.
download_custom_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="@+id/customiddownload"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#343434"
android:textSize="14sp" />
<TextView
android:id="@+id/customtitledownlaod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:ellipsize="end"
android:textColor="#343434"
android:textSize="14sp" />
<TextView
android:id="@+id/customtimedownload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:layout_marginTop="35dp"
android:textSize="14sp" />
<TextView
android:id="@+id/custompathdownload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:layout_marginTop="60dp"
android:textSize="14sp" />
</RelativeLayout>
Downloads.java
package studio.harpreet.mybrowser;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Downloads extends AppCompatActivity {
DatabaseHelper mydb;
ListView lview;
ListAdapter lviewAdapter;
ArrayAdapter adapter;
ArrayList<HashMap<String,String>> downlist;
LinearLayout emptylist;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_downloads);
mydb = new DatabaseHelper(this);
lview = findViewById(R.id.downloadlistview);
emptylist = findViewById(R.id.emptyList);
emptylist.setVisibility(View.GONE);
getdata();
lview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object o = lview.getAdapter().getItem(i);
if(o instanceof Map)
{
Map map = (Map) o;
try {
String filename = String.valueOf(map.get("Title"));
String extension = filename.substring(filename.lastIndexOf(".")+1);
String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
File file = new File(Environment.getExternalStorageDirectory() + "/" +
Environment.DIRECTORY_DOWNLOADS + "/" + filename);
Uri filepath = Uri.parse(String.valueOf(file));
Intent in = new Intent(Intent.ACTION_VIEW);
in.setDataAndType(filepath,type);
in.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
in.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(in,"Open With: "));
}
catch (Exception e)
{
Toast.makeText(Downloads.this, e.getMessage()+"", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void getdata()
{
downlist = mydb.ShowdataDownload();
if(downlist.isEmpty())
{
emptylist.setVisibility(View.VISIBLE);
return;
}
lviewAdapter = new SimpleAdapter(Downloads.this,downlist,R.layout.download_custom_list,
new String[]{"Id_download","Title","Time","Path"},
new int[]{R.id.customiddownload,R.id.customtitledownlaod,
R.id.customtimedownload,R.id.custompathdownload});
lview.setAdapter(lviewAdapter);
}
}
Also, we add a click listener on ListView item to open a particular app for a file.
Subscribe to Harpreet studio on Youtube
Like Harpreet Studio on Facebook
Follow me on Instagram
it will be huge help, if you also tell that how i can delete an item from download page listview. And One Thing show some indication when download is not completed.
ReplyDeleteThanks In Advance.....
Downloaded file not showing in my app
ReplyDeleteAlso app crashes when I press yes button
ReplyDeleteTula's International School is known to be one of the residential school and best boarding school in India The school is affiliated with Central Board of Secondary Education (CBSE) and has been awarded with numerous accolades in the field of education. Visit Class 8 Assignment Answer!
ReplyDeleteBangladesh education board share the assignment topic. So, all the student should get the assignment solution. Visit Class 7 Assignment Answer!
ReplyDeleteBangladesh secondary education board student need to complete their assignment. Here we mention all class assignment solution answer link. Visit Class 6 Assignment Answer!
ReplyDeleteMost education system manage assignment. To complete study process. You need to get subject assignment solution. Here we mention all class assignment solution.Visit Class 9 Assignment Answer!
ReplyDelete