ListView button at position not clicked proper click in android - android

I displayed the list item using a custom Baseadapter class. My problem is, when I click on the listview button at the position 1, the button at position other is also clicked.but i downloaded video in back progress completelty.but listview display not properly . How do I overcome this problem?
Here is my code:
public class TestHopeListNew extends Activity {
ListView lv;
ArrayList<Url_Dto> list = new ArrayList<Url_Dto>();
MyListAdapter adtf;
public static String prf_date_view = "";
String str_start;
Button all_detail;
Button accepted_all, mainDownloadBtn;
public static SQLiteDatabase db;
String name;
File download;
int i = 0;
private ArrayList<ProgressBarSeek> progreeSeekList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_hope_list_new);
progreeSeekList = new ArrayList<ProgressBarSeek>();
list = DBAdapter.getUrl_Detail();
Log.v("log_tag", "list :: " + list.size());
lv = (ListView) findViewById(R.id.main_list_meet);
mainDownloadBtn = (Button) findViewById(R.id.not_shown);
adtf = new MyListAdapter(this);
lv.setAdapter(adtf);
adtf.notifyDataSetChanged();
SqliteAdpter dba = SqliteAdpter
.getAdapterInstance(getApplicationContext());
dba.createdatabase();
db = dba.openDataBase();
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adtf.setAllDownload();
}
});
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
ProgressBar pr;
ProgressBar[] prArray = new ProgressBar[list.size()];
Button cl, dl;
ImageView im;
DownloadFileFromURL downloadFileFromURL;
ViewHolder holder = null;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setAllDownload() {
if (prArray.length > 0) {
for (int i = 0; i < prArray.length; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.v("log_tag", "list.get(i).url_video "
+ list.get(i).url_video);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, list.get(i).url_video, i);
}
}
}
private class ViewHolder {
public Button cl;
public Button dl;
public ProgressBar pr;
public ImageView im;
};
public View getView(final int position, View convertView,
ViewGroup parent) {
/*convertView = mInflater.inflate(R.layout.custome_list_view, null);
cl = (Button) convertView.findViewById(R.id.cancle_sedual);
dl = (Button) convertView.findViewById(R.id.download_sedual);
pr = (ProgressBar) convertView.findViewById(R.id.listprogressbar);
prArray[position] = pr;
im = (ImageView) convertView.findViewById(R.id.list_image);
im.setImageResource(list.get(position).images[position]);*/
//final ViewHolder holder = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.custome_list_view,
null);
holder = new ViewHolder();
prArray[position] = pr;
holder.cl = (Button) convertView
.findViewById(R.id.cancle_sedual);
holder.dl = (Button) convertView
.findViewById(R.id.download_sedual);
holder.pr = (ProgressBar) convertView
.findViewById(R.id.listprogressbar);
holder.im = (ImageView) convertView
.findViewById(R.id.list_image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.im.setImageResource(list.get(position).images[position]);
// pr.setProgress(getItem(position));
holder.cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Cancle Button Click");
holder.dl.setVisibility(View.VISIBLE);
holder.cl.setVisibility(View.GONE);
//downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
holder.pr.setProgress(0);
notifyDataSetChanged();
}
});
holder.dl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.dl.setFocusable(false);
str_start = list.get(position).url_video;
holder.dl.setVisibility(View.GONE);
holder.cl.setVisibility(View.VISIBLE);
Log.v("log_tag", "Start Button Click ");
// new DownloadFileFromURL().execute(str_start);
downloadFileFromURL = new DownloadFileFromURL(holder.dl, holder.cl);
downloadFileFromURL.execute(holder.pr, str_start, position);
notifyDataSetChanged();
}
});
getProgress(holder.pr, position, holder.dl, holder.cl);
// convertView.setTag(holder);
return convertView;
}
}
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
int position;
Button start, cancel;
boolean download1 = false;
public DownloadFileFromURL(Button start, Button cancel) {
this.start = start;
this.cancel = cancel;
}
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
download1 = true;
}
public void downloadFile() {
this.download1 = false;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
int count;
progressBar = (ProgressBar) params[0];
position = (Integer) params[2];
try {
URL url = new URL((String) params[1]);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
// Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(2000);
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (this.download1) {
if(isCancelled()){
break;
}
total += count;
// writing data to file
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
setProgress(progressBar, position, start, cancel, this);
} else {
File delete = new File(strDownloaDuRL);
delete.delete();
}
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Log.v("log_tag", "progress :: " + values);
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}
private void setProgress(final ProgressBar pr, final int position,
final Button Start, final Button cancel,
final DownloadFileFromURL downloadFileFromURL) {
ProgressBarSeek pbarSeek = new ProgressBarSeek();
pbarSeek.setPosition(position);
pbarSeek.setProgressValue(pr.getProgress());
// Log.v("log_tag", position + " progress " + pr.getProgress());
progreeSeekList.add(pbarSeek);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Cancle Button Click Set progress");
Start.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
pr.setProgress(0);
}
});
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Start Button Click set Progress");
str_start = list.get(position).url_video;
Start.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
Log.v("log_tag", "str_start " + str_start);
//
// new DownloadFileFromURL().execute(str_start);
DownloadFileFromURL downloadFileFromU = new DownloadFileFromURL(
Start, cancel);
downloadFileFromU.execute(pr, str_start, position);
}
});
}
private void getProgress(ProgressBar pr, int position, Button dl, Button cl) {
if (progreeSeekList.size() > 0) {
for (int j = 0; j < progreeSeekList.size(); j++) {
if (position == progreeSeekList.get(j).getPosition()) {
pr.setProgress(progreeSeekList.get(j).getProgressValue());
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
}
}
}
}
}
i click second button but display other button clickeble but second button background downloading in sd card but display not properly .how to solve it and what is wrong in my code,please helpme!!!

Related

Item deleting from listview affecting asynctask

I am making a multi-video downloader. I have created a listview and for each item in the listview an asynctask is called which downloads the file in the background. Everything works perfect. But, if i want to delete an item from the listview for example from position 2, the item at position 3 (both are currently running) comes on position 2 and the asynctask attached previously to position 2 continues running and it shows the progress of asynctask that was previously attached to the position 2. How can I move the asynctask of position 3 to position 2.
Here is my Adapter Class from where I am calling the asynctask class:
public class DownloadInfoArrayAdapter extends ArrayAdapter<DownloadInfo> {
public static TextView progpercent;
// Simple class to make it so that we don't have to call findViewById frequently
// private static final String TAG = FileDownloadTask.class.getSimpleName();
public static Integer result;
LayoutInflater inflater5;
ImageView delete;
Activity activity1;
int mvalue;
ContextWrapper cw1;
int flag=0;
int status=0;
GlobalDownload downloadList;
ArrayList downloadState;
FileDownloadTask task;
private static class ViewHolder {
TextView textView;
ProgressBar progressBar;
ImageView delete;
DownloadInfo info;
TextView size;
TextView prog;
public TextView progpercent;
}
private static final String TAG = DownloadInfoArrayAdapter.class.getSimpleName();
public DownloadInfoArrayAdapter(Context context, int textViewResourceId,
List<DownloadInfo> objects, ContextWrapper cw, Activity DownloadScreen) {
super(context, textViewResourceId, objects);
cw1=cw;
activity1=DownloadScreen;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
final DownloadInfo info = getItem(position);
ViewHolder holder = null;
if(null == row) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.file_download_row, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.downloadFileName);
holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
holder.size=(TextView) row.findViewById(R.id.downloadFileSize);
holder.progpercent=(TextView) row.findViewById(R.id.downloadFileProgress);
holder.delete=(ImageView) row.findViewById(R.id.deletebutton);
// holder.button = (Button)row.findViewById(R.id.downloadButton);
// holder.info = info;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.textView.setText(info.getFilename());
holder.progpercent.setText(info.getDownloadState().toString());
if(info.getStatus()== null)
{
Log.e("DATABASE1", "null ");
status=3;
info.setLastState(2);
}
else if(info.getStatus()== DownloadInfo.State.DONE)
{
if(info.getLastState()==1)
{
Log.e("DATABASE", "LS " + 1);
info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
status=1;
}
else if(info.getLastState()==0)
{
Log.e("DATABASE", "LS " + 2);
info.setDownloadState(DownloadInfo.DownloadState.FAILED);
status=1;
}
else
{
status=2;
}
}
Log.e("DATABASE", "DOWNLOAD STATE " + info.getDownloadState().toString());
if(info.getDownloadState()== DownloadInfo.DownloadState.NOT_STARTED)
{
if(status==3) {
holder.progressBar.setProgress(info.getProgress());
holder.progressBar.setMax(100);
holder.progpercent.setText("DOWNLOADING");
}
}
holder.size.setText(info.getFileSize());
info.setProgressBar(holder.progressBar);
if(info.getDownloadState()==DownloadInfo.DownloadState.NOT_STARTED){ info.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
if (MainScreen.settingsvalue==0) {
Log.e("DATABASE", " " + 0);
mvalue = 0;
task = new FileDownloadTask(info, cw1, activity1, mvalue);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
if(info.getDownloadState()== DownloadInfo.DownloadState.COMPLETE) {
Log.e("DATABASE", "UPDATE COMPLETE " + info.getDownloadState());
info.setStatus(DownloadInfo.State.DONE);
info.setLastState(1);
holder.progressBar.setProgress(R.drawable.download_bar);
holder.progpercent.setText(info.getDownloadState().toString());
cancelstatus=0;
}
if(info.getDownloadState()== DownloadInfo.DownloadState.FAILED) {
info.setStatus(DownloadInfo.State.DONE);
MainScreen.newDB.execSQL("update " + DatabaseHelper.TABLE_NAME + " set " + DatabaseHelper.COL_6 + " = '" + info.getStatus() + "', " + DatabaseHelper.COL_7 + " =0 where " + DatabaseHelper.COL_1 + " = " + info.getFileid());
Log.e("DATABASE", "UPDATED ");
info.setLastState(0);
holder.progpercent.setText(info.getDownloadState().toString());
cancelstatus=0;
}
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
Log.e("POSITION", "TAG " + index);
Log.e("POSITION", "POSITION " + position);
downloadList = ((GlobalDownload) activity1.getApplicationContext());
downloadState = (ArrayList) downloadList.getDownloadInfo();
CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
CustomDialogClass2.customfilename2= info.getFilename() + "." + info.getFileType();
Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
CustomDialogClass2 cdd = new CustomDialogClass2(MainScreen.activity1);
cdd.show();
CustomDialogClass2.mPosition=position;
CustomDialogClass2.id=info.getFileid();
// downloadState.remove(position);
Log.e("STATUS", "Status before stopping " + info.getDownloadState());
if((info.getDownloadState()== DownloadInfo.DownloadState.DOWNLOADING)) {
info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
cancelstatus=1;
task.cancel(true);
}
}
});
return row;
}
}
Here is the Asynctask class
public class FileDownloadTask extends AsyncTask<String, Integer, Integer> {
private static final String TAG = FileDownloadTask.class.getSimpleName();
final DownloadInfo mInfo;
TextView display;
public int progress;
public String encodedurl;
PopupWindow popupWindow;
Activity activity;
// ListView listview1;
// Context context;
LayoutInflater layoutInflater;
static int i=0;
int Mvalue;
ContextWrapper cw;
File file;
String nameoffile;
PowerManager mgr;
PowerManager.WakeLock wakeLock;
public static int cancelstatus =0;
int a=0;
// DownloadInfoArrayAdapter mAdapter;
public FileDownloadTask(DownloadInfo info, ContextWrapper cw1, Activity activity1, int mvalue) {
mInfo = info;
cw=cw1;
activity=activity1;
this.Mvalue=mvalue;
// listView1 = (ListView) listview.findViewById(R.id.downloadListView);
// mAdapter = new DownloadInfoArrayAdapter(, R.id.downloadListView,mInfo);
}
// #Override
protected void onProgressUpdate(Integer... values) {
mInfo.setProgress(values[0]);
mInfo.setFilePercent(values[0]);
// Log.e("FILE PERCENT", String.valueOf(mInfo.getFilePercent()));
// mAdapter.notifyDataSetChanged();
// mAdapter.setNotifyOnChange(true);
// display = (TextView) row.findViewById(R.id.downloadFileProgress);
ProgressBar bar = mInfo.getProgressBar();
// Integer percent=mInfo.getFilePercent();
if (bar != null) {
bar.setProgress(mInfo.getProgress());
// percent(mInfo.getFilePercent());
// display.setText(mInfo.getProgress());
// bar.invalidate();
}
// DownloadScreen.adapter.notifyDataSetChanged();
// DownloadScreen.listView.setAdapter(DownloadScreen.adapter);
}
#Override
protected void onCancelled() {
super.onCancelled();
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");
File file = new File(rootdirectory, CustomDialogClass2.customfilename2);
Log.e("FILE", " name" + file.toString());
file.delete();
DownloadScreen.adapter.notifyDataSetChanged();
}
#Override
protected Integer doInBackground(String... params) {
int count;
try {
String state = Environment.getExternalStorageState();
String root = Environment.getExternalStorageDirectory().toString();
URL url = new URL(mInfo.getFileUrl().toString());
Log.e("URL", "" + url);
HttpURLConnection conection = (HttpURLConnection) url.openConnection();
conection.connect();
Log.e("connection", " " + 0);
int lenghtOfFile = conection.getContentLength();
Log.e("length", "" + lenghtOfFile);
String nameoffile = mInfo.getFilename() + "." + mInfo.getFileType();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");
if (!rootdirectory.exists()) {
rootdirectory.mkdirs();
}
File file = new File(rootdirectory, nameoffile);
file.createNewFile();
Log.e("name of file", "" + nameoffile);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
mInfo.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
long total = 0;
while ((count = input.read(data)) != -1) {
if(!isCancelled()) {
total += count;
progress = (int) ((total * 100) / lenghtOfFile);
publishProgress(progress);
// Log.e("PROGRESS", "" + mInfo.getFileType() + progress);
mInfo.setFilePercent(progress);
output.write(data, 0, count);
i = 1;
}
}
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
mInfo.setStatus(DownloadInfo.State.COMPLETE);
output.flush();
output.close();
input.close();
Log.e("Download Complete", "" + 0);
Log.e("DEVICE SDCARD", " " + Mvalue);
}
return progress;
}
protected void onPostExecute(Integer progress) {
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
DownloadScreen.adapter.notifyDataSetChanged();
DownloadScreen.listView.setAdapter(DownloadScreen.adapter);
Uri contentUri = Uri.fromFile(file);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
activity.sendBroadcast(mediaScanIntent);
CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
CustomDialogClass.customfilename=mInfo.getFilename() + "." + mInfo.getFileType();
Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
CustomDialogClass cdd = new CustomDialogClass(MainScreen.activity1);
cdd.show();
}
#Override
protected void onPreExecute() {
}
}
you should override the remove method of your adapter in order to cancel properly the asyncTask associated to your item.

How to Download Video File From server and Save Sd Card?

i develop downloading app and when I click the save button then download process in back ground but button click not show right position .I have listView in which I inflate a row contain Imageview and button and progressbar now I want to handle click event of button which coded in adapter and I am able to get the position of button too. But here when I click on button I am changing a image of button its works fine problem is when I scroll the view it again change the image of button as it was before because of getview() Method its recycle view every time.and how to all Download video and save sd card. my code below::
public class TestHopeListNew extends Activity {
ListView lv;
ArrayList<Url_Dto> list = new ArrayList<Url_Dto>();
MyListAdapter adtf;
public static String prf_date_view = "";
String str_start;
Button mainDownloadBtn;
public static SQLiteDatabase db;
ProgressBar freePr;
String name;
File download;
int i = 0;
private ArrayList<ProgressBarSeek> progreeSeekList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_hope_list_new);
progreeSeekList = new ArrayList<ProgressBarSeek>();
list = DBAdapter.getUrl_Detail();
Log.v("log_tag", "list :: " + list.size());
lv = (ListView) findViewById(R.id.main_list_meet);
mainDownloadBtn = (Button) findViewById(R.id.not_shown);
freePr = (ProgressBar) findViewById(R.id.progressBar1);
adtf = new MyListAdapter(this);
lv.setAdapter(adtf);
//adtf.notifyDataSetChanged();
SqliteAdpter dba = SqliteAdpter
.getAdapterInstance(getApplicationContext());
dba.createdatabase();
db = dba.openDataBase();
BusyExtMemory();
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adtf.setAllDownload();
}
});
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
ProgressBar pr;
ProgressBar[] prArray = new ProgressBar[list.size()];
Button cl, dl;
ImageView im;
DownloadFileFromURL downloadFileFromURL;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public void setAllDownload() {
if (prArray.length > 0) {
for (int i = 0; i < prArray.length; i++) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.v("log_tag", "list.get(i).url_video "
+ list.get(i).url_video);
downloadFileFromURL.execute(pr, list.get(i).url_video, i);
}
}
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custome_list_view, null);
cl = (Button) convertView.findViewById(R.id.cancle_sedual);
dl = (Button) convertView.findViewById(R.id.download_sedual);
pr = (ProgressBar) convertView.findViewById(R.id.listprogressbar);
prArray[position] = pr;
im = (ImageView) convertView.findViewById(R.id.list_image);
im.setImageResource(list.get(position).images[position]);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Cancle Button Click");
dl.setVisibility(View.VISIBLE);
cl.setVisibility(View.GONE);
downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
pr.setProgress(0);
}
});
dl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
str_start = list.get(position).url_video;
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
Log.v("log_tag", "Start Button Click ");
//downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, str_start, position);
}
});
getProgress(pr, position, dl, cl);
return convertView;
}
}
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
int position;
Button start, cancel;
boolean download1 = false;
public DownloadFileFromURL(Button start, Button cancel) {
this.start = start;
this.cancel = cancel;
}
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
download1 = true;
}
public void downloadFile() {
this.download1 = false;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
int count;
progressBar = (ProgressBar) params[0];
position = (Integer) params[2];
/*
* try { Thread.sleep(500); } catch (InterruptedException e) {
* e.printStackTrace(); }
*/
try {
URL url = new URL((String) params[1]);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
// Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (this.download1) {
if (isCancelled()) {
break;
}
total += count;
// writing data to file
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
setProgress(progressBar, position, start, cancel, this);
} else {
File delete = new File(strDownloaDuRL);
delete.delete();
}
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
BusyExtMemory();
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}
private void setProgress(final ProgressBar pr, final int position,
final Button Start, final Button cancel,
final DownloadFileFromURL downloadFileFromURL) {
ProgressBarSeek pbarSeek = new ProgressBarSeek();
pbarSeek.setPosition(position);
pbarSeek.setProgressValue(pr.getProgress());
// Log.v("log_tag", position + " progress " + pr.getProgress());
progreeSeekList.add(pbarSeek);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Cancle Button Click Set progress");
Start.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
downloadFileFromURL.cancel(true);
// downloadFileFromURL.downloadFile();
downloadFileFromURL.cancel(true);
pr.setProgress(0);
}
});
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag", "Start Button Click set Progress");
str_start = list.get(position).url_video;
Start.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
Log.v("log_tag", "str_start " + str_start);
//
// new DownloadFileFromURL().execute(str_start);
DownloadFileFromURL downloadFileFromU = new DownloadFileFromURL(
Start, cancel);
downloadFileFromU.execute(pr, str_start, position);
}
});
}
private void getProgress(ProgressBar pr, int position, Button dl, Button cl) {
if (progreeSeekList.size() > 0) {
for (int j = 0; j < progreeSeekList.size(); j++) {
if (position == progreeSeekList.get(j).getPosition()) {
pr.setProgress(progreeSeekList.get(j).getProgressValue());
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
}
}
}
}
public String TotalExtMemory() {
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory()
.getAbsolutePath());
int Total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;
Log.v("log_tag", "TotalExtMemory " + Total);
String strI = Integer.toString(Total);
return strI;
}
public String FreeExtMemory() {
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory()
.getAbsolutePath());
int Free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
String strI = Integer.toString(Free);
Log.v("log_tag", "FreeExtMemory " + strI);
return strI;
}
public String BusyExtMemory() {
StatFs statFs = new StatFs(Environment.getExternalStorageDirectory()
.getAbsolutePath());
int Total = (statFs.getBlockCount() * statFs.getBlockSize()) / 1048576;
int Free = (statFs.getAvailableBlocks() * statFs.getBlockSize()) / 1048576;
int Busy = Total - Free;
String strI = Integer.toString(Busy);
freePr.setProgress(Integer.parseInt(strI));
Log.v("log_tag", "BusyExtMemory " + strI);
return strI;
}
}
My Screen Shot Demo Display::
try changing this
cl.setVisibility(View.GONE);
to
v.setVisibility(View.GONE);
in your button onClick
On all your button onClicks where you want to deal with the actual button that you just clicked use the View v

how to all file download in android and save all file in sd card?

In my case i click download button when download all file but in show all file sdcard and some file display . and i used thread .what me wrong in my code : and Cancel(cl) button working but in i used delted download file is not working and {cl and dl button} setVisibitly not changed. My Code Below: Please Helpme>
mainDownloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
adtf.setAllDownload();
}
});
}
public class MyListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
ProgressBar pr;
ProgressBar[] prArray = new ProgressBar[list.size()];
Button cl, dl;
ImageView im;
DownloadFileFromURL downloadFileFromURL;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setAllDownload() {
if (prArray.length > 0) {
for (int i = 0; i < prArray.length; i++) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, list.get(i).url_video, i);
}
}
}
public View getView(final int position, View convertView,
ViewGroup parent) {
convertView = mInflater.inflate(R.layout.custome_list_view, null);
cl = (Button) convertView.findViewById(R.id.cancle_sedual);
dl = (Button) convertView.findViewById(R.id.download_sedual);
pr = (ProgressBar) convertView.findViewById(R.id.listprogressbar);
prArray[position] = pr;
im = (ImageView) convertView.findViewById(R.id.list_image);
im.setImageResource(list.get(position).images[position]);
getProgress(pr, position, cl, dl);
// pr.setProgress(getItem(position));
cl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click");
// dl.setVisibility(View.VISIBLE);
dl.setVisibility(View.VISIBLE);
cl.setVisibility(View.GONE);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
//downloadFileFromURL.cancel(true);
downloadFileFromURL.downloadFile();
pr.setProgress(0);
}
});
dl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
str_start = list.get(position).url_video;
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
Log.v("log_tag","Start Button Click ");
//
// new DownloadFileFromURL().execute(str_start);
downloadFileFromURL = new DownloadFileFromURL(dl, cl);
downloadFileFromURL.execute(pr, str_start, position);
}
});
return convertView;
}
}
class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {
int count = 0;
ProgressDialog dialog;
ProgressBar progressBar;
int myProgress;
int position;
Button start, cancel;
boolean download1 = false;
public DownloadFileFromURL(Button start, Button cancel) {
this.start = start;
this.cancel = cancel;
}
/**
* Before starting background thread Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
ProgressBar progressBar;
download1 = true;
}
public void downloadFile() {
this.download1 = false;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
/**
* Downloading file in background thread
* */
#Override
protected Integer doInBackground(Object... params) {
//Log.v("log_tag", "params :::; " + params);
int count;
progressBar = (ProgressBar) params[0];
position = (Integer) params[2];
try {
// URL url = new URL(f_url[0]);
URL url = new URL((String) params[1]);
//Log.v("log_tag", "name ::: " + url);
name = ((String) params[1]).substring(((String) params[1])
.lastIndexOf("/") + 1);
//Log.v("log_tag", "name Substring ::: " + name);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
download = new File(Environment.getExternalStorageDirectory()
+ "/download/");
if (!download.exists()) {
download.mkdir();
}
String strDownloaDuRL = download + "/" + name;
Log.v("log_tag", " down url " + strDownloaDuRL);
FileOutputStream output = new FileOutputStream(strDownloaDuRL);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
if (this.download1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
// publishProgress("" + (int) ((total * 100) /
// lenghtOfFile));
// writing data to file
progressBar
.setProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
setProgress(progressBar, position, start, cancel, this);
}
}
// flushing output
output.flush();
if(!this.download1){
File delete = new File(strDownloaDuRL);
delete.delete();
}
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return 0;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
// Log.v("log_tag", "progress :: " + values);
// setting progress percentage
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
Log.v("log", "login ::: 4::: " + download);
String videoPath = download + "/" + name;
String chpName = name;
Log.v("log_tag", "chpName ::::" + chpName + " videoPath "
+ videoPath);
db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
+ chpName + "\",\"" + videoPath + "\" )");
}
}
private void setProgress(final ProgressBar pr, final int position,
final Button Start, final Button cancel,
final DownloadFileFromURL downloadFileFromURL) {
ProgressBarSeek pbarSeek = new ProgressBarSeek();
pbarSeek.setPosition(position);
pbarSeek.setProgressValue(pr.getProgress());
//Log.v("log_tag", position + " progress " + pr.getProgress());
progreeSeekList.add(pbarSeek);
/* cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Cancle Button Click Set progress");
Start.setVisibility(View.VISIBLE);
cancel.setVisibility(View.GONE);
downloadFileFromURL.cancel(true);
pr.setProgress(0);
}
});
Start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("log_tag","Start Button Click set Progress");
str_start = list.get(position).url_video;
Start.setVisibility(View.GONE);
cancel.setVisibility(View.VISIBLE);
Log.v("log_tag", "str_start " + str_start);
//
// new DownloadFileFromURL().execute(str_start);
DownloadFileFromURL downloadFileFromU = new DownloadFileFromURL(
Start, cancel);
downloadFileFromU.execute(pr, str_start, position);
}
});*/
}
private void getProgress(ProgressBar pr, int position, Button cl, Button dl) {
if (progreeSeekList.size() > 0) {
for (int j = 0; j < progreeSeekList.size(); j++) {
if (position == progreeSeekList.get(j).getPosition()) {
pr.setProgress(progreeSeekList.get(j).getProgressValue());
dl.setVisibility(View.GONE);
cl.setVisibility(View.VISIBLE);
}
}
}
}
}
You can try using the below code to download the files from the url and save into the sdcard:
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/xmls");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
long startTime = System.currentTimeMillis();
Log.d("DownloadManager", "download url:" + url);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
} catch (IOException e) {
Log.d("DownloadManager", "Error: " + e);
}
}
Also keep in mind that you specify the below permissions in your manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
I hope it will help you.
Thanks

Custom List item change background in Android

Hi I am using custom listview and my list item contains checkbox. When updating the listview with the existing values the background is changed, so it is working fine.But when i clicks the check button, at that time the background will not changing after loading some where again then the background is changed . My question is at the time of check the item the background need to change immediately.
This is my adapter class.
public class GuestListAdapter extends BaseAdapter implements OnClickListener {
private String strExe;
AlertDialog.Builder builder;
Context context;
private ArrayList<String> arrayListFirstName;
private ArrayList<String> arrayListLastName;
private ArrayList<String> arrayListGuests;
private ArrayList<String> arrayCustomOne;
private ArrayList<String> arTempId;
private ArrayList<Boolean> chickinlist;
public static ArrayList<Integer> arrCheckedItems;
public static ArrayList<Integer> arrUnCheckedItems;
Button btnInfo;
private SQLiteAdapter mySqliteAdapter;
private GuestListScreen myGuestList;
private RelativeLayout views;
// private AlertDialog alertDialog = null;
private ArrayList<Boolean> checks = new ArrayList<Boolean>();
public GuestListAdapter(Context mcontext, ArrayList<String> arrListFN,
ArrayList<String> arrListLN, ArrayList<String> arrListGuest,
ArrayList<String> arrTiketID, ArrayList<String> arrCustOne,
ArrayList<Boolean> chicklist) {
clearAdapter();
arrayListFirstName = new ArrayList<String>();
arrayListLastName = new ArrayList<String>();
arrayListGuests = new ArrayList<String>();
arrayCustomOne = new ArrayList<String>();
arTempId = new ArrayList<String>();
chickinlist = new ArrayList<Boolean>();
arrCheckedItems = new ArrayList<Integer>();
arrUnCheckedItems = new ArrayList<Integer>();
arrayListFirstName = arrListFN;
arrayListLastName = arrListLN;
arrayListGuests = arrListGuest;
arrayCustomOne = arrCustOne;
arTempId = arrTiketID;
chickinlist = chicklist;
context = mcontext;
mySqliteAdapter = new SQLiteAdapter(context);
for (int i = 0; i < arrayListFirstName.size(); i++) {
checks.add(i, false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.d("", "getCount" + arrayListFirstName.size());
return arrayListFirstName.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
Log.d("", "getItem" + arrayListFirstName.size());
return arrayListFirstName.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
final int pos = position;
views = null;
LayoutInflater layoutInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
views = (RelativeLayout) layoutInflator.inflate(
R.layout.guest_list_item, null);
final CheckBox chk = (CheckBox) views.getChildAt(0);
// Log.d("", "CheckBox Pos "+position);
chk.setId(position);
TextView txtView = (TextView) views.getChildAt(1);
TextView txtView2 = (TextView) views.getChildAt(2);
TextView txtView3 = (TextView) views.getChildAt(3);
final TextView txtView4 = (TextView) views.getChildAt(4);
TextView txtView5 = (TextView) views.getChildAt(6);
txtView5.setId(position);
// Log.d("", "Button Pos "+position);
txtView4.setId(position);
txtView4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, InfoScreen.class);
intent.putExtra("IDVALUE",arTempId.get(txtView4.getId()) );
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
// System.out.println(v + "##########" + " " + v.getId());
// System.out.println(v + "##########" + " " + arTempId.get(txtView4.getId()));
// System.out.println(v + "##########" + " " + chickinlist.get(txtView4.getId()));
}
});
Log.e("", "****************************************************** " );
// Log.v("", "Adapter arr pos " + pos);
// Log.v("", "Adapter arr position " + position);
Log.v("", "Adapter arr size " + arrayListFirstName.size());
Log.v("", "Passsing arr size " + chickinlist.size());
for (int dd = 0; dd < arrayListFirstName.size(); dd++) {
if (position == dd) {
// Log.d("", "Passsing arr size " + chickinlist.size());
Boolean result = chickinlist.get(position);
// Log.d("", "After " + result);
if (result == true) {
chk.setChecked(true);
arrCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_checked);
} else {
chk.setChecked(false);
arrUnCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_unchecked);
}
txtView.setText(arrayListFirstName.get(position));
txtView2.setText(arrayListLastName.get(position));
txtView3.setText("(" + arrayListGuests.get(position) + ")");
if(arrayCustomOne.get(position).equalsIgnoreCase("0")||arrayCustomOne.get(position).equalsIgnoreCase(null)||arrayCustomOne.get(position).equalsIgnoreCase(""))
{
txtView5.setText("");
}else
{
txtView5.setText(arrayCustomOne.get(position));
}
}
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
strExe = "update ticket_details set checkin_status=1 where tempid="+arTempId.get(chk.getId());
// Log.d("Adapter", "Checked Temp Id "+arTempId.get(chk.getId()));
Log.d("", "Position "+chk.getId()+"tempid "+arTempId.get(chk.getId()));
if (isChecked) {
// views.setBackgroundResource(R.drawable.list_item_checked);
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.create();
builder.setMessage(arrayListFirstName.get(chk.getId())
+ " " + arrayListLastName.get(chk.getId())
+ " has been checked in.");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// myGuestList = new GuestListScreen();
mySqliteAdapter.executeCheckQurey(strExe);
// myGuestList.ListUpdate();
dialog.dismiss();
}
}).show();
// Log.d("", "ID = " + buttonView.getId());
} else {
// views.setBackgroundResource(R.drawable.list_item_unchecked);
strExe = "update ticket_details set checkin_status=0 where tempid="+arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
// Toast.makeText(context, "check release", Toast.LENGTH_SHORT)
// .show();
}
}
});
return views;
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Integer index = (Integer) view.getTag();
boolean state = checks.get(index.intValue());
checks.set(index.intValue(), !state);
}
// private void showADialog(int posit) {
//
// AlertDialog.Builder builder = new AlertDialog.Builder(
// context);
// builder.create();
// builder.setMessage("The clicked row is "
// + arrayListFirstName.get(posit));
// builder.setPositiveButton("Ok?", new DialogInterface.OnClickListener() {
//
// #Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
//
// }).show();
// }
public void clearAdapter() {
if (arrayListFirstName != null) {
arrayListFirstName.clear();
arrayListFirstName = null;
arrayListLastName.clear();
arrayListLastName = null;
arrayListGuests.clear();
arrayListGuests = null;
arrayCustomOne.clear();
arrayCustomOne = null;
arTempId.clear();
arTempId = null;
chickinlist.clear();
chickinlist = null;
arrCheckedItems.clear();
arrCheckedItems = null;
arrUnCheckedItems.clear();
arrUnCheckedItems = null;
}
}
}
I just want to change the background of the checked item immediatly without updating the list again.
I think you need to tell the BaseAdapter to refresh the data when your OnCheckedChanged Listener is called.
GuestListAdapter.this.notifyDataSetChanged()

How to implement multiple downloads with progress bar updation??

Description:
I have a grid view with 4 items in landscape mode and 3 items on portrait mode. The grid element is a magazine thumbnail. On click of a thumbnail downloading of the magazine starts and a horizontal progress bar appears showing progress of download. But when i click to two thumbnails one after another , the progress bar of later clicked thumbnail only updates and at last corrupted magazine gets downloaded.
I have used asynchronous task for magazine download.
Code:
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
progress = (ProgressBar) arg1.findViewById(R.id.progress);
thumbnail = (ImageView) arg1.findViewById(R.id.thumbnail);
thumbnail.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Download Magazine
downloadMagazine.execute(bank.get(index).getPdfLink());
}
});
}
class DownloadMagazineTask extends AsyncTask<String, Integer, Long> {
File sdDir = Environment.getExternalStorageDirectory();
#Override
protected void onPreExecute() {
progress.setVisibility(View.VISIBLE);
}
#Override
protected Long doInBackground(String... arg0) {
String[] urls = arg0;
try {
URL url = new URL(urls[0]);
URLConnection con = url.openConnection();
int fileLength = con.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
File file = null;
File dir = new File(sdDir + "/BeSpoken/pdfs");
boolean flag = dir.mkdirs();
if (flag)
System.out.println("Directory created");
else {
System.out.println("Directory not created");
file = new File(dir+ "/"+ bank.get(index).getPdfLink().substring(bank.get(index).getPdfLink().lastIndexOf("/")));
}
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
String m = bank.get(index).getTitle();
manager.updateDownloadedMagazines(
Integer.parseInt(m.substring(m.lastIndexOf(" ") + 1)),
file.toString());
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
startActivity(getIntent());
finish();
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
progress.setProgress(values[0]);
}
#Override
protected void onPostExecute(Long result) {
super.onPostExecute(result);
progress.setVisibility(View.INVISIBLE);
}
}
Question:
How can i implement multiple download functionality so that progress bar shows progress of each download individually??
I have defined the image view and the progress bar as final and sending these references to the AsyncTask where the magazine downloading activity is going, on click of image view.
AsyncTask spawns multiple threads and that's how progress of each download can be updated.Code:
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
View grid;
if (convertView == null) {
grid = new View(context);
grid = layoutInflater.inflate(item, null);
} else {
grid = (View) convertView;
}
final TextView title = (TextView) grid.findViewById(R.id.mgntitle);
title.setText(bank.get(position).getTitle());
final ImageView imageView = (ImageView) grid
.findViewById(R.id.thumbnail);
imageView.setImageResource(R.drawable.icon);
final ProgressBar progress = (ProgressBar) grid
.findViewById(R.id.progress);
final ImageView downloadmark = (ImageView) grid
.findViewById(R.id.downloadmark);
String pdfLink = bank.get(position).getPdfLink();
String filename = pdfLink.substring(pdfLink.lastIndexOf("/") + 1);
final File targetDir = new File(fileLocation + filename);
System.out.println("target file name " + targetDir);
if (new File(fileLocation + filename).exists()) {
if (!getPrefName(filename).equalsIgnoreCase("NA")) {
downloadmark.setVisibility(View.VISIBLE);
}
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!targetDir.exists()) {
map.put(bank.get(position).getTitle(), progress);
new DoBackgroundTask(GridDisplayActivity.this, bank
.get(position).getPdfLink(), progress,
downloadmark, imageView, position)
.execute();
}
}
});
imageView.setImageBitmap(BitmapFactory.decodeByteArray(
bank.get(position).getCoverPages(), 0, bank.get(position)
.getCoverPages().length));
return grid;
}

Categories

Resources