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
Related
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.
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!!!
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
I have an issue when I am trying to download a file from server using FTP. I need to display seek-bar status of downloading file and download speed of the Internet. I am able to display seek-bar status and speed of the Internet for HTTP, but for FTP I am not able to perform that same task. In the attached image below I need to display seek-bar and network speed for FTP and HTTP. Below is the source code I used for HTTP and FTP. I don't know where I missed it?
HTTP Code:
class DownloadFileAsync extends AsyncTask<String, String, String> { //see the summary of asyncTask
long duration, pk;
private boolean sleep = false;
private HashMap<String, Object> map;
private ProgressBar bar;
private TextView real_time, test_avg, peak, status;
private ImageView pp;
//constructor
public DownloadFileAsync(HashMap<String, Object> map) {
this.map = map;
bar = (ProgressBar) map.get("bar");
// trans = (TextView) map.get("trans");
//real_time = (TextView) map.get("real_time");
test_avg = (TextView) map.get("test_avg");
//peak = (TextView) map.get("peak");
status = (TextView) map.get("status");
pp = (ImageView) map.get("pp");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count = 0;
try {
updateUI(pp, R.drawable.pause);
updateUI(status, "Connecting");
URL url = new URL(map.get("url").toString());
URLConnection conexion = url.openConnection();
conexion.connect();
final int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
updateUI(status, "Connected");
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
+ File.separator
+ Info.getInfo(con).HTTP_DOWNLOAD_FILE_NAME);
byte data[] = new byte[1024];
long total = 0;
final long started = System.currentTimeMillis();
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Downloading");
while ((count = input.read(data)) != -1) {
while (sleep) {
Thread.sleep(1000);
sleepingTime +=1000;
}
total += count;
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((speed / duration) / 1024 + " kbps");
if (pk <= (speed / duration) / 1024)
{
pk = (speed / duration) / 1024;
}
//peak.setText(pk + " kbps");
}
}
});
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
updateUI(status, "Success");
}
catch (final Exception e) {
e.printStackTrace();
updateUI(status, "Failed");
}
updateUI(pp, R.drawable.resume);
return null;
}
private void updateUI(final TextView tv, final String str) {
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
}
});
}
private void updateUI(final ImageView iv, final int id) { // may create problem
runOnUiThread(new Runnable() {
public void run() {
iv.setImageResource(id);
}
});
}
public void gotosleep(boolean val) {
sleep = val;
}
public boolean areYouSleeping() {
return sleep;
}
#Override
protected void onPostExecute(String unused) {
try {
//System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);
if (!PARALLEL_MODE //for sequence mode
&& (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size()
&& testRunning) {
/*System.out.println("Info.getInfo(con).data.indexOf(map) + 1 "+Info.getInfo(con).data.indexOf(map) + 1
+" Info.getInfo(con).data.size() "+Info.getInfo(con).data.size()+" testRunning "+testRunning);
System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);*/
System.out.println("asynclist "+asynclist.size());
asynclist.remove(0); //asynclist contains objects of (downloadAsync(map))
if(asynclist.size() > 0){
System.out.println("tlist in post execute+++"+tlist);
//DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
DownloadFileAsync dfa = (DownloadFileAsync) asynclist.get(0);
dfa.execute();
tlist.remove(0);
}
else{
startTests();
}
}
else if (PARALLEL_MODE && stopCount < asynclist.size() && testRunning) { //for parallel mode
System.out.println("stopCount before condition= " + stopCount);
if (stopCount == asynclist.size() -1 && testRunning) {
System.out.println("stopCount inside 1st condition= " + stopCount);
stopCount = 0;
// stopTests(0);
startTests();
System.out.println("Tests Started");
}
else {
stopCount++;
System.out.println("stopCount after increment = " + stopCount);
;
}
}
}
catch (Exception ed) {
ed.printStackTrace();
go.setText(R.string.go);
//testRunning = false;
}
}
}
For FTP:--
class FTPAsync extends AsyncTask<String, String, String> {
//private int mode = -1;
//added
long duration, pk;
private boolean sleep1 = false;
private HashMap<String, Object> map;
private ProgressBar bar;
private TextView real_time, test_avg, peak, status;
private ImageView pp;
//
public FTPAsync(int mode) {
// this.mode = mode;
}
//added
public FTPAsync(HashMap<String, Object> map) {
//Toast.makeText(con, "ftpAsync constructer is called" ,Toast.LENGTH_SHORT).show();
this.map = map;
bar = (ProgressBar) map.get("bar");
// trans = (TextView) map.get("trans");
//real_time = (TextView) map.get("real_time");
test_avg = (TextView) map.get("test_avg");
//peak = (TextView) map.get("peak");
status = (TextView) map.get("status");
pp = (ImageView) map.get("pp");
}
//
#Override
protected void onPreExecute() {
//Toast.makeText(con, "onPreExecute() is called" ,Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
int count = 0;
FTPClient ObjFtpCon = new FTPClient();
//Toast.makeText(con, "FTPasync doInBackground() is called" ,Toast.LENGTH_SHORT).show();
try {
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(0);
//real_time.setText(0 + " secs");
//test_avg.setText(0+ " kbps");
//peak.setText(0+" kbps");
}
});
updateUI(pp, R.drawable.pause);
//ObjFtpCon.connect("ftp.customhdclips.com");
ObjFtpCon.connect("ftp."+map.get("url").toString());
updateUI(status, "Connecting");
//if (ObjFtpCon.login("fstech#customhdclips.com", "fstech123")) {
if (ObjFtpCon.login(map.get("username").toString(), map.get("password").toString())) {
updateUI(status, "Connected");
// toast("Connected to FTP Server : ftp.customhdclips.com");
ObjFtpCon.enterLocalPassiveMode(); // important!
ObjFtpCon.cwd("/");// to send the FTP CWD command to the server, receive the reply, and return the reply code.
//if (mode == 0) {
if(Integer.parseInt((map.get("oprn").toString()))== 0){
// Download
System.out.println("download test is called");
File objfile = new File(
Environment.getExternalStorageDirectory()
+ File.separator + "/logo.png");
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/logo.png",
objFos);
objFos.close();
if (blnresult) {
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}
}
else {
// Upload
System.out.println("upload test is called");
//Toast.makeText(con, "upload FTP test is called", Toast.LENGTH_SHORT).show();
//ContextWrapper context = null;
//assetManager= context.getAssets();
assetManager = getResources().getAssets();
input1 = assetManager.open("hello.txt");
final long started = System.currentTimeMillis();
int size = input1.available();
//byte[] buffer = new byte[size];
byte dataByte[] = new byte[1024];
//input1.read(buffer);
//String data = "ZK DATA TESTER TEST DATA1sdfsdf";
String data = input1.toString();
System.out.println("dat value is........"+data);
final int lenghtOfFile = data.getBytes().length;
//final int lenghtOfFile = input1.getBytes().length;
System.out.println("length of file....."+lenghtOfFile);
ByteArrayInputStream in = new ByteArrayInputStream(
data.getBytes());
//toast("Uploading /test.txt");
//Toast.makeText(con,"File Size : " +data.getBytes().length + " bytes",Toast.LENGTH_SHORT).show();
//byte b[] = new byte[1024];
long total = 0;
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Uploading");
while ((count = in.read(dataByte)) != -1)
{
System.out.println("read value is...."+in.read(dataByte));
while (sleep1) {
Thread.sleep(1000);
System.out.println("ftp upload is in sleeping mode");
sleepingTime +=1000;
}
System.out.println("Total count --"+count);
total += count;
System.out.println("Only Total --"+total);
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
boolean result = ObjFtpCon.storeFile("/test.txt", input1);
//boolean result = ObjFtpCon.storeFile(map.get("file_address").toString()+"/test.txt", input1);
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((((speed / duration)*1000)*0.0078125)
+ " kbps");
/*if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}*/
if (pk <= ((speed / duration)*1000)*0.0078125) {
pk = (long)(((speed / duration)*1000)*0.0078125);
}
//peak.setText(pk + " kbps");
}
}
});
//in.close();
if (result) {
updateUI(status, "Uploaded");
// toast("Uploading succeeded");
// toast("Uploaded at /test.txt");
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
System.out.println("curreent time..... "+System.currentTimeMillis());
System.out.println("started time --"+started);
System.out.println("sleep tome...."+sleepingTime);
System.out.println("duration is....."+duration);
/*runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((speed / duration) / 1024
+ " kbps");
if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}
peak.setText(pk + " kbps");
}
}
});*/
}
/*while(!result){Thread.sleep(1000);}*/
}
in.close();
}
}
else{
System.out.println("password entered is incorrect");
//Toast.makeText(con, "Username or/and password is incorrect", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
try {
ObjFtpCon.logout();
ObjFtpCon.disconnect();
}
catch (IOException e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
return null;
}
#override
protected void onPostExecute(String unused) {
try {
//System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);
if (!PARALLEL_MODE //for sequence mode
&& (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size()
&& testRunning) {
System.out.println("ftpasynclist "+ftpasynclist.size());
ftpasynclist.remove(0); //asynclist contains objects of (FTPAsync(map))
if(ftpasynclist.size() > 0){
System.out.println("tlist in post execute+++"+ftplist);
//DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
FTPAsync dfa = (FTPAsync)ftpasynclist.get(0);
dfa.execute();
ftplist.remove(0);
}
else{
startTests();
}
}
else if (PARALLEL_MODE //for parallel mode
&& ftpStopCount <ftpasynclist.size()
&& testRunning) {
System.out.println("stopCount before condition= " +ftpStopCount);
if (ftpStopCount == ftpasynclist.size() -1 && testRunning) {
System.out.println("stopCount inside 1st condition= " + ftpStopCount);
ftpStopCount = 0;
// stopTests(0);
startTests();
System.out.println("Tests Started");
}
else {
ftpStopCount++;
System.out.println("stopCount after increment = " + ftpStopCount);
;
}
}
}
catch (Exception ed) {
ed.printStackTrace();
go.setText(R.string.go);
//testRunning = false;
}
super.onPostExecute(unused);
}
private void updateUI(final TextView tv, final String str) {
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
}
});
}
private void updateUI(final ImageView iv, final int id) { // may create problem
runOnUiThread(new Runnable() {
public void run() {
iv.setImageResource(id);
}
});
}
public void gotosleep(boolean val) {
sleep1 = val;
}
public boolean areYouSleeping() {
return sleep1;
}
}
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;
}