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.
Related
I am having a listview which I am populating from a database.
The listview is taking some time(<300ms) to populate the list.
If I am doing a smoothScrollToPosition on the onActivityCreated function it is doing nothing.
On the OnCreate function I had to wait for ~200ms before I could call smoothScrollToPosition before which even the ListView Object is not initialized.
I can use the getViewTreeObserver as below which runs fine but it requires the minimum sdk version 16. I was trying to get it working for version 14~15.
mListView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mListView.smoothScrollToPosition(adapter.getCount());
// unregister listener (this is important)
mListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
The code I am having -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<Chat>();
db = new DBAdapter(getContext());
adapter = new CustomChatAdapter(getContext(), list);
Log.d("ListView1", "Value of f: " + f);
thread= new Thread(){
#Override
public void run(){
try {
synchronized(this){
wait(200);
}
}
catch(InterruptedException ex){
Log.d("ListView1", "Interrupted Exception: " +ex.toString());
}
Log.d("ListView1", "Adapter Count: " +adapter.getCount());
mListView.smoothScrollToPosition(adapter.getCount());
}
};
getMsg("1", getActivity().getIntent().getStringExtra("key"));
thread.start();
Log.d("ListView1", "Adapter Count: " +adapter.getCount());
//mListView.smoothScrollToPosition(adapter.getCount());
}
public void getMsg(String myid, String friend_id) {
list.clear();
try {
Cursor cur = db.get_friend_shouts(myid,friend_id);
String img_id1 = "";
String img_id2 ="";
if (cur != null) {
if (cur.moveToFirst()) {
do {
img_id1 = cur.getString(cur.getColumnIndex("image_id"));
img_id1 = img_id1 == null ? "null" : img_id1;
img_id2 = cur.getString(cur.getColumnIndex("r_img_id"));
img_id2 = img_id2 == null ? "null" : img_id2;
list.add(new Chat( img_id1 , cur.getString(cur.getColumnIndex("firstname")) + " " + cur.getString(cur.getColumnIndex("lastname")), cur.getString(cur.getColumnIndex("user_id")),
cur.getString(cur.getColumnIndex("shout_msg")) ,
img_id2, cur.getString(cur.getColumnIndex("r_firstname")) + " " + cur.getString(cur.getColumnIndex("r_lastname")) , cur.getString(cur.getColumnIndex("r_user_id")) , cur.getString(cur.getColumnIndex("rec_time")) ));
//Log.d("ListView1", "User details: " + cur.getString(cur.getColumnIndex("user_id")) + " " + cur.getString(cur.getColumnIndex("firstname")) + cur.getString(cur.getColumnIndex("lastname")) + " " + cur.getString(cur.getColumnIndex("image_id")));
} while (cur.moveToNext());
}
}
adapter.notifyDataSetChanged();
if(mListView!=null)
mListView.smoothScrollToPosition(adapter.getCount());
} catch (Exception e) {
Log.d("ListView1", "getMsg Error: " + e.toString());
}
}
The ArrayAdapter class -
public class CustomChatAdapter extends ArrayAdapter<Chat> {
private final Context context;
private final List<Chat> list;
public CustomChatAdapter(Context context, ArrayList<Chat> presidents) {
super(context, R.layout.chatrowlayout, presidents);
this.context = context;
this.list = presidents;
}
static class ViewContainer { public ImageView imageView; public TextView txtMsg; public ImageView imageView1; public TextView txtTime; }
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewContainer viewContainer;
View rowView = view;
//---print the index of the row to examine---
//Log.d("ListView1",String.valueOf(position));
//if(rowView == null) {
viewContainer = new ViewContainer();
LayoutInflater inflater = LayoutInflater.from(context);
rowView= inflater.inflate(R.layout.chatrowlayout, null, true);
viewContainer.txtMsg = (TextView) rowView.findViewById(R.id.msgText);
viewContainer.imageView = (ImageView) rowView.findViewById(R.id.icon1);
viewContainer.imageView1 = (ImageView) rowView.findViewById(R.id.icon2);
viewContainer.txtTime = (TextView) rowView.findViewById(R.id.timeText);
rowView.setTag(viewContainer);
/*} else {
viewContainer = (ViewContainer) rowView.getTag();
}*/
viewContainer.txtMsg.setText(list.get(position).getMsg());
viewContainer.txtTime.setText(list.get(position).getMsg_time());
if(list.get(position).getS_id().equals("1")) {
viewContainer.imageView.setImageBitmap(BitmapFactory.decodeFile(new Info().p + File.separator+ "image_" + list.get(position).getPic_id1() + ".jpeg" ));
viewContainer.imageView1.setAlpha(0);
viewContainer.txtMsg.setGravity(Gravity.LEFT);
} else {
viewContainer.imageView1.setImageBitmap(BitmapFactory.decodeFile(new Info().p + File.separator+ "image_" + list.get(position).getPic_id1() + ".jpeg" ));
viewContainer.imageView.setAlpha(0);
viewContainer.txtMsg.setGravity(Gravity.RIGHT);
}
return rowView;
}
}
removeGlobalOnLayoutListerner for pre SDK 16, addOnGlobalLayout works for pre 16.
OnCreate is too early.
You should wait for the layout to be inflated. Smooth scrolling in onResume should do the trick:
#Override
protected void onResume() {
mListView.smoothScrollToPosition(adapter.getCount());
}
Half month i trying fix this problem, its my second solution and i get old error.
My goal is to write a listView with timer in every row with Start and Stop buttons, after rotating screen all timers should work correctly, but how in pre-solution after rotation screen, first position in listview get time last/lower position.
As for link with these two solution i see just logic of getView() method, and i'm on 100% sure that is the main problem.
Can anybody help me with this, i am at an impasse. Problematic piace of code:
if(isItStart.get(position)){
holder.stop.setEnabled(true);
holder.start.setEnabled(false);
handler.postDelayed(updateTimeThread,0);
}
Here is full class.
ListView listView;
MyAdapter adapter;
Handler handler;
SQLiteDatabase db;
List<Tracker> trackerList;
Tracker tracker;
List<Boolean> isItStart,historyIsItStart;
List<Long> startTime,historyStartTime;
List<Long> lastPauseList,historyLastPauseList;
List<Long> updateTimeList, historyUpdateTimeList;
List<Long> daysList,historyDayList;
List<Long> hoursList,historyHoursList;
List<Long> minutesList,historyMinutes;
List<Long> secondsList,historySecondsList;
int trackerCount;
static final String LOG_TAG = "myTag";
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
db = RemindMe.db;
trackerList = Tracker.getListAll(db);
trackerCount=trackerList.size();
initLists();
for (int i = 0; i < trackerCount; i++) {
startTime.add(0L);
lastPauseList.add(0L);
updateTimeList.add(0L);
daysList.add(0L);
hoursList.add(0L);
minutesList.add(0L);
secondsList.add(0L);
isItStart.add(false);
historyStartTime.add(startTime.get(i));
historyLastPauseList.add(lastPauseList.get(i));
historyUpdateTimeList.add(updateTimeList.get(i));
historyDayList.add(daysList.get(i));
historyHoursList.add(hoursList.get(i));
historyMinutes.add(minutesList.get(i));
historySecondsList.add(secondsList.get(i));
historyIsItStart.add(isItStart.get(i));
}
listView = (ListView)findViewById(R.id.listView);
String[] from = {Tracker.COL_NAME,Tracker.COL_ELAPSED_TIME,Tracker.COL_ELAPSED_TIME,Tracker.COL_ELAPSED_TIME,Tracker.COL_ELAPSED_TIME};
int[] to = {R.id.tvName,R.id.tvDays,R.id.tvHours,R.id.tvMinutes,R.id.tvSeconds};
adapter = new MyAdapter(this,R.layout.list_item,Tracker.getAll(db),from,to,0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
long day,hour,min,sec;
long time = cursor.getLong(columnIndex);
switch(view.getId()){
case R.id.tvDays:
TextView days = (TextView)view;
days.setText("days");
return true;
case R.id.tvHours:
TextView hours = (TextView)view;
hours.setText("hours");
return true;
case R.id.tvMinutes:
TextView minutes = (TextView)view;
minutes.setText("min");
return true;
case R.id.tvSeconds:
TextView seconds = (TextView)view;
if(time!=0){
sec = time/1000;
seconds.setText(String.valueOf(sec));
}else{
seconds.setText("null");
}
return true;
}
return false;
}
});
listView.setAdapter(adapter);
getSupportLoaderManager().initLoader(1,null,this).forceLoad();
}
void initLists(){
startTime = new ArrayList<Long>(trackerCount);
lastPauseList = new ArrayList<Long>(trackerCount);
updateTimeList = new ArrayList<Long>(trackerCount);
daysList = new ArrayList<Long>(trackerCount);
hoursList = new ArrayList<Long>(trackerCount);
minutesList = new ArrayList<Long>(trackerCount);
secondsList = new ArrayList<Long>(trackerCount);
isItStart = new ArrayList<Boolean>(trackerCount);
historySecondsList = new ArrayList<Long>(trackerCount);
historyMinutes = new ArrayList<Long>(trackerCount);
historyHoursList = new ArrayList<Long>(trackerCount);
historyDayList = new ArrayList<Long>(trackerCount);
historyUpdateTimeList = new ArrayList<Long>(trackerCount);
historyLastPauseList = new ArrayList<Long>(trackerCount);
historyStartTime = new ArrayList<Long>(trackerCount);
historyIsItStart = new ArrayList<Boolean>(trackerCount);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this,AddTrack.class);
startActivity(intent);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new TrackerLoader(this,db);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
static class TrackerLoader extends android.support.v4.content.CursorLoader{
SQLiteDatabase db;
TrackerLoader(Context context,SQLiteDatabase db){
super(context);
this.db=db;
}
#Override
public Cursor loadInBackground() {
return Tracker.getAll(db);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(LOG_TAG, "onSavedInstanceState---------------------------------------------------------------!");
for (int i = 0; i <trackerCount ; i++) {
historyStartTime.set(i,startTime.get(i));
historyLastPauseList.set(i, lastPauseList.get(i));
historyUpdateTimeList.set(i,updateTimeList.get(i));
historyDayList.set(i, daysList.get(i));
historyHoursList.set(i,hoursList.get(i));
historyMinutes.set(i, minutesList.get(i));
historySecondsList.set(i,secondsList.get(i));
historyIsItStart.set(i, isItStart.get(i));
outState.putSerializable("startTime " + i, historyStartTime.get(i));
outState.putSerializable("lastPause " + i, historyLastPauseList.get(i));
outState.putSerializable("updateTime " + i, historyUpdateTimeList.get(i));
outState.putSerializable("dayList " + i, historyDayList.get(i));
outState.putSerializable("hoursList " + i, historyHoursList.get(i));
outState.putSerializable("minutesList " + i, historyMinutes.get(i));
outState.putSerializable("secondsList " + i, historySecondsList.get(i));
outState.putSerializable("isItStart " + i, historyIsItStart.get(i));
Log.d(LOG_TAG, "startTime " + getTime((Long) outState.getSerializable("startTime " + i)));
Log.d(LOG_TAG, "lastPause " + getTime((Long) outState.getSerializable("lastPause " + i)));
Log.d(LOG_TAG, "updateTime " + getTime((Long) outState.getSerializable("updateTime " + i)));
Log.d(LOG_TAG, "dayList " + getTime((Long) outState.getSerializable("dayList " + i)));
Log.d(LOG_TAG, "hoursList " + getTime((Long) outState.getSerializable("hoursList " + i)));
Log.d(LOG_TAG, "minutesList " + getTime((Long) outState.getSerializable("minutesList " + i)));
Log.d(LOG_TAG, "secondsList " + outState.getSerializable("secondsList " + i));
Log.d(LOG_TAG, "isItStart " + outState.getSerializable("isItStart " + i));
Log.d(LOG_TAG, "position " + i);
Log.d(LOG_TAG,"-----------------------------------!");
}
Log.d(LOG_TAG,"END onSavedInstanceState-------------------------------------------------------------!");
for (int i = 0; i < trackerCount; i++) {
Log.d(LOG_TAG,"secondsList "+i+ " "+secondsList.get(i));
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(LOG_TAG, "onRestoreInstanceState-------------------------------------------------------!");
for (int i = 0; i <trackerCount ; i++) {
historyStartTime.set(i,(Long)savedInstanceState.getSerializable("startTime "+i));
historyLastPauseList.set(i,(Long)savedInstanceState.getSerializable("lastPause "+i));
historyUpdateTimeList.set(i,(Long)savedInstanceState.getSerializable("updateTime "+i));
historyDayList.set(i,(Long)savedInstanceState.getSerializable("dayList "+i));
historyHoursList.set(i,(Long)savedInstanceState.getSerializable("hoursList "+i));
historyMinutes.set(i,(Long)savedInstanceState.getSerializable("minutesList "+i));
historySecondsList.set(i,(Long)savedInstanceState.getSerializable("secondsList "+i));
historyIsItStart.set(i,(Boolean)savedInstanceState.getSerializable("isItStart "+i));
startTime.set(i,historyStartTime.get(i));
lastPauseList.set(i,historyLastPauseList.get(i));
updateTimeList.set(i,historyUpdateTimeList.get(i));
daysList.set(i,historyDayList.get(i));
hoursList.set(i,historyHoursList.get(i));
minutesList.set(i,historyMinutes.get(i));
secondsList.set(i,historySecondsList.get(i));
isItStart.set(i, historyIsItStart.get(i));
Log.d(LOG_TAG, "startTime " + getTime((Long) savedInstanceState.getSerializable("startTime " + i)));
Log.d(LOG_TAG,"lastPause " + getTime((Long) savedInstanceState.getSerializable("lastPause " + i)));
Log.d(LOG_TAG,"updateTime " + getTime((Long) savedInstanceState.getSerializable("updateTime " + i)));
Log.d(LOG_TAG,"dayList " + getTime((Long) savedInstanceState.getSerializable("dayList " + i)));
Log.d(LOG_TAG,"hoursList " + getTime((Long) savedInstanceState.getSerializable("hoursList " + i)));
Log.d(LOG_TAG,"minutesList " + getTime((Long) savedInstanceState.getSerializable("minutesList " + i)));
Log.d(LOG_TAG, "secondsList " + savedInstanceState.getSerializable("secondsList " + i));
Log.d(LOG_TAG,"isItStart "+savedInstanceState.getSerializable("isItStart " + i));
Log.d(LOG_TAG,"position "+i);
Log.d(LOG_TAG,"----------------------------------------------------------------");
}
Log.d(LOG_TAG,"END onRestoreIntstanceState-------------------------------------------------------------!");
}
private class MyAdapter extends SimpleCursorAdapter{
Context context;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
MyAdapter(Context context,int resourceID,Cursor cursor,String[] from,int[]to,int flags){
super(context, resourceID, cursor, from, to, flags);
this.context = context;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
tracker = trackerList.get(position);
if(row==null){
holder = new ViewHolder();
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(R.layout.list_item,parent,false);
holder.name= (TextView)row.findViewById(R.id.tvName);
holder.days = (TextView)row.findViewById(R.id.tvDays);
holder.hours = (TextView)row.findViewById(R.id.tvHours);
holder.minutes = (TextView)row.findViewById(R.id.tvMinutes);
holder.seconds = (TextView)row.findViewById(R.id.tvSeconds);
holder.start = (Button)row.findViewById(R.id.btStart);
holder.stop = (Button)row.findViewById(R.id.btStop);
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
holder.start.setEnabled(true);
holder.stop.setEnabled(false);
holder.name.setText(tracker.getName());
final Runnable updateTimeThread = new Runnable() {
#Override
public void run() {
updateTimeList.set(position, (System.currentTimeMillis() - startTime.get(position)) + lastPauseList.get(position));
secondsList.set(position, updateTimeList.get(position) / 1000);
minutesList.set(position, secondsList.get(position) / 60);
hoursList.set(position, minutesList.get(position) / 60);
secondsList.set(position, (secondsList.get(position) % 60));
minutesList.set(position, (minutesList.get(position) % 60));
hoursList.set(position, (hoursList.get(position) % 24));
holder.days.setText(String.format("%04d", daysList.get(position)));
holder.hours.setText(String.format("%02d", hoursList.get(position)));
holder.minutes.setText(String.format("%02d", minutesList.get(position)));
holder.seconds.setText(String.format("%02d", secondsList.get(position)));
handler.postDelayed(this, 0);
}
};
if(isItStart.get(position)){
holder.stop.setEnabled(true);
holder.start.setEnabled(false);
handler.postDelayed(updateTimeThread,0);
}
View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btStart:
startTime.set(position,System.currentTimeMillis());
handler.post(updateTimeThread);
holder.start.setEnabled(false);
holder.stop.setEnabled(true);
isItStart.set(position,true);
break;
case R.id.btStop:
lastPauseList.set(position, updateTimeList.get(position));
handler.removeCallbacks(updateTimeThread);
holder.stop.setEnabled(false);
holder.start.setEnabled(true);
isItStart.set(position,false);
break;
}
}
};
holder.start.setOnClickListener(onClickListener);
holder.stop.setOnClickListener(onClickListener);
return row;
}
class ViewHolder{
TextView name,days,hours,minutes,seconds;
Button start,stop;
}
}
String getTime(long time){
int hours = (int)(time/3600000);
int minutes = (int)(time -hours*3600000)/60000;
int seconds = (int)(time-hours*3600000-minutes*60000)/1000;
String hour = (hours<9?"0"+hours:hours).toString();
String min = (minutes<9?"0"+minutes:minutes).toString();
String sec = (seconds<9?"0"+seconds:seconds).toString();
return ""+hour+":"+min+":"+sec;
}
}
Add android:configChanges="orientation|screenSize" in manifest.xml and delete your onRestore and onSaved.
When you rotating the screen the application refresh the activity i had the same kind of problem so i just locked the screen for one way in the android mainifest by
android:screenOrientation="portrait"
found this great answer by:Xion
"you could distinguish the cases of your activity being created for the first time and being restored from savedInstanceState. This is done by overriding onSaveInstanceState and checking the parameter of onCreate.
You could lock the activity in one orientation by adding android:screenOrientation="portrait" (or "landscape") to in your manifest.
You could tell the system that you meant to handle screen changes for yourself by specifying android:configChanges="orientation" in the tag. This way the activity will not be recreated, but will receive a callback instead (which you can ignore as it's not useful for you)."
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
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