How to use seek bar in each row of recyclerview - android

I have a situation where I need to show seekbar in every row of recylerview to download the media(Audio). The file is downlaoding successfully but everytime I click the downlaod button , only the last seekbar of the recylerview work not the seekbar associated with the particular row.
This is my adapter from where I am downloading audio
public class ListenTestAdapter extends RecyclerView.Adapter<ListenTestAdapter.MyViewHolder> implements AdapterView.OnItemClickListener, View.OnClickListener, View.OnTouchListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener {
private static final int DOWNLOAD_THREAD_POOL_SIZE = 1;
private final Handler handler = new Handler();
public TextView testNameTextview, downloadTextView, seekBarTextView;
MyDownloadDownloadStatusListenerV1 myDownloadStatusListener = new MyDownloadDownloadStatusListenerV1();
int downloadId1;
private List<Listen> list = new ArrayList<>();
private Activity context;
private MediaPlayer mediaPlayer;
private SeekBar seekBarProgress;
private int mediaFileLengthInMilliseconds;
private String mp3Url;
private Handler durationHandler = new Handler();
private TextView duration;
private int timeElapsed;
private ThinDownloadManager downloadManager;
private String fileName;
private RetryPolicy retryPolicy ;
private File filesDir ;
private Uri downloadUri ;
private SeekBar seekBar ;
//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
//seekbar.setProgress((int) timeElapsed);
//set time remaing
double timeRemaining = mediaFileLengthInMilliseconds - timeElapsed;
duration = (TextView) context.findViewById(R.id.duration);
//222067.0
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
public ListenTestAdapter(Activity context, List<Listen> list) {
this.list = list;
this.context = context;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Toast.makeText(context, "You Clciked " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// buttonPlayPause.setImageResource(R.drawable.button_pause);
durationHandler.postDelayed(updateSeekBarTime, 100);
mediaFileLengthInMilliseconds = mediaPlayer.getDuration();
primarySeekBarProgressUpdater();
}
#Override
public void onClick(View v) {
}
#Override
public void onCompletion(MediaPlayer mp) {
context.findViewById(R.id.mediaPlayerLayout).setVisibility(View.GONE);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.listview_listen_item, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
testNameTextview.setText(list.get(position).getPassages());
seekBar.setMax(100);
seekBar.setProgress(0);
downloadManager = new ThinDownloadManager(DOWNLOAD_THREAD_POOL_SIZE);
retryPolicy = new DefaultRetryPolicy();
filesDir = context.getExternalFilesDir(Environment.DIRECTORY_MUSIC);
downloadTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp3Url = list.get(position).getQuestionGroupFile();
mp3Url = mp3Url.replace(" ", "%20");
if(!"".equals(mp3Url)){
downloadUri = Uri.parse(mp3Url);
fileName = mp3Url.substring(mp3Url.lastIndexOf('/') + 1);
//download audio
downLoadAudio();
}else{
Toast.makeText(context, "Audio is not avialable", Toast.LENGTH_SHORT).show();
}
}
});
}
private void downLoadAudio() {
Uri destinationUri = Uri.parse(filesDir + "/" + fileName);
final DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
.setDestinationURI(destinationUri).setPriority(DownloadRequest.Priority.LOW)
.setRetryPolicy(retryPolicy)
.setDownloadContext("Download1")
.setStatusListener(myDownloadStatusListener);
if (downloadManager.query(downloadId1) == DownloadManager.STATUS_NOT_FOUND) {
fileName = fileName.replace("%20", " ");
downloadId1 = downloadManager.add(downloadRequest);
} else {
Toast.makeText(context, "Please wait....Downloading is in progress", Toast.LENGTH_SHORT).show();
}
}
/**
* Method which updates the SeekBar primary progress by current song playing position
*/
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int) (((float) mediaPlayer.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
#Override
public int getItemCount() {
return list.size();
}
private String getBytesDownloaded(int progress, long totalBytes) {
//Greater than 1 MB
long bytesCompleted = (progress * totalBytes) / 100;
if (totalBytes >= 1000000) {
return ("" + (String.format("%.1f", (float) bytesCompleted / 1000000)) + "/" + (String.format("%.1f", (float) totalBytes / 1000000)) + "MB");
}
if (totalBytes >= 1000) {
return ("" + (String.format("%.1f", (float) bytesCompleted / 1000)) + "/" + (String.format("%.1f", (float) totalBytes / 1000)) + "Kb");
} else {
return ("" + bytesCompleted + "/" + totalBytes);
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View view) {
super(view);
testNameTextview = (TextView) view.findViewById(R.id.testNameTextview);
downloadTextView = (TextView) view.findViewById(R.id.downloadTextview);
seekBarTextView = (TextView) context.findViewById(R.id.duration);
seekBar = (SeekBar) view.findViewById(R.id.seekBar);
}
}
class MyDownloadDownloadStatusListenerV1 implements DownloadStatusListenerV1 {
#Override
public void onDownloadComplete(DownloadRequest request) {
final int id = request.getDownloadId();
if (id == downloadId1) {
seekBarTextView.setText("Downaloaded" + " Audio: " + fileName + " Completed");
//when download is complete encryption will start
EncryptDownloadedAudio.encrypt(context,mp3Url,fileName);
}
}
#Override
public void onDownloadFailed(DownloadRequest request, final int errorCode, final String errorMessage) {
final int id = request.getDownloadId();
if (id == downloadId1) {
context.runOnUiThread(new Runnable() {
#Override
public void run() {
seekBarTextView.setText("Failed to download: " + fileName + " Failed: ErrorCode " + errorCode + ", " + errorMessage);
seekBar.setProgress(0);
}
});
}
}
#Override
public void onProgress(DownloadRequest request, long totalBytes, long downloadedBytes, int progress) {
int id = request.getDownloadId();
System.out.println("######## onProgress ###### " + id + " : " + totalBytes + " : " + downloadedBytes + " : " + progress);
if (id == downloadId1) {
seekBarTextView.setText("Downloading: " + fileName + ", " + progress + "%" + " " + getBytesDownloaded(progress, totalBytes));
seekBar.setProgress(progress);
}
}
}
}

Check the concept of view tags, that will help you out. basically do a seekbar.setTag("UNIQUE ID FOR EVERY VIEW"); then while updating the seekbar use findViewWithTag("UNIQUE ID FOR PARTICULAR VIEW")
since you are fetching view by id it will only give the last view with that id.

Related

Countdown Timer sometime, counts 2 seconds before the actual time

I have tried to make an countdown timer in a list veiw implementation. Each list item has a separate countdown timer that can be started or stopped. However I have noticed that if I add the first timer in list and set its time. When I start the timer it starts two seconds less than the actual time. e.g If I added a count down of 12 seconds. Then it will start counting from 10. But when the countdown is taking place and I add another new timer and set its time, it starts on the exact given time. The new counter starts at the wrong time only when either there is no other counter in the list or when all counters are already stopped and not counting down. Similarly it will only start the right time only when other timers are counting down. Would really appreciate if someone can help me figure out where is the problem. I have been looking at the code for days.
Here's my Adapter class
public class CustomAdapterCounter extends ArrayAdapter<CounterData> {
private final LayoutInflater mInflater;
Context context;
Uri sound = Uri.parse("android.resource://com.tattooalarmclock.free/" + R.raw.counter);
String counterString = "";
private List<ViewHolder> lstHolders;
private List<CounterData> list = new ArrayList<CounterData>();
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
// if(!holder.counterData.isStopped)
holder.updateTimeRemaining(System.currentTimeMillis());
}
}
}
};
public CustomAdapterCounter(Context context, List<CounterData> l) {
super(context, 0, l);
this.context = context;
lstHolders = new ArrayList<>();
list = l;
mInflater = LayoutInflater.from(context);
for(int i=0; i<list.size(); i++) {
CounterData[] array = list.toArray(new CounterData[list.size()]);
if(!array[i].isStopped)
startUpdateTimer();
}
}
public double getScreenSize() {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int dens = dm.densityDpi;
double wi = (double) width / (double) dens;
double hi = (double) height / (double) dens;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
public static <T> List<T> stringToArray(String s, Class<T[]> clazz) {
T[] arr = new Gson().fromJson(s, clazz);
return Arrays.asList(arr); //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
}
public boolean getListSharedPreferences() {
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getString("CL", null) != null) {
counterString = sharedPreferences.getString("CL", null);
Gson gson = new Gson();
TypeToken<List<CounterData>> token = new TypeToken<List<CounterData>>() {};
list = gson.fromJson(counterString, token.getType());
return true;
}
else
return false;
}
public void saveListSharedPreferences(List counterList) {
Gson gson = new Gson();
counterString = gson.toJson(counterList);
SharedPreferences sharedPreferences = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("CL", counterString).commit();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
if(getScreenSize() <= 4 )
convertView = mInflater.inflate(R.layout.list_view_counter_small, parent, false);
else
convertView = mInflater.inflate(R.layout.list_view_item_counter, parent, false);
holder.counterTextView = (TextView) convertView.findViewById(R.id.counterTextView);
holder.stopCounter = (Button) convertView.findViewById(R.id.counterStopInList);
holder.startCounter = (Button) convertView.findViewById(R.id.counterStartInList);
holder.deleteCounter = (Button) convertView.findViewById(R.id.deleteCounter);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.setData2(getItem(position));
final ViewHolder finalHolder = holder;
holder.stopCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long store = finalHolder.counterData.expirationTime - System.currentTimeMillis();
finalHolder.counterData.isStopped = true;
finalHolder.counterData.expirationTime = store;
finalHolder.stopCounter.setEnabled(false);
finalHolder.stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
/* if(getListSharedPreferences()) {
System.out.println("List before change in stop button " + list.toString());
list = stringToArray(counterString, CounterData[].class);
list.set(position, finalHolder.counterData);
System.out.println("List before change in stop button " + list.toString());
saveListSharedPreferences(list);
}
else {
System.out.println(list.toString());
list.set(position, finalHolder.counterData);
System.out.println(list.toString());
saveListSharedPreferences(list);
}
*/
}
});
holder.startCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
finalHolder.counterData.isStopped = false;
//finalHolder.counterData.expirationTime = System.currentTimeMillis() + finalHolder.counterData.expirationTime;
//finalHolder.setData(finalHolder.counterData);
finalHolder.startCounter.setEnabled(true);
finalHolder.startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
finalHolder.stopCounter.setEnabled(true);
finalHolder.stopCounter.getBackground().setColorFilter(null);
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
startUpdateTimer();
/* if(getListSharedPreferences()) {
list = stringToArray(counterString, CounterData[].class);
System.out.println("List before change in start button " + list.toString());
list.set(position, finalHolder.counterData);
System.out.println("List after change in start button " + list.toString());
saveListSharedPreferences(list);
}
else {
list.set(position, finalHolder.counterData);
saveListSharedPreferences(list);
} */
}
});
final ViewHolder finalHolder1 = holder;
holder.deleteCounter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* if(finalHolder1.mediaPlayer.isPlaying()) {
finalHolder.mediaPlayer.stop();
// finalHolder.counterData.isSoundPlayedBefore = true;
} */
list.remove(position);
notifyDataSetChanged();
saveListSharedPreferences(list);
}
});
return convertView;
}
}
class ViewHolder {
public TextView counterTextView;
//public List<Long> l;
CounterData counterData;
Button startCounter;
Button stopCounter;
Button deleteCounter;
boolean stop = false;
long timeDiff;
// Context context;
// MediaPlayer mediaPlayer;
// List<CounterData> counterDataList;
public void setData(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void setData2(CounterData item) {
counterData = item;
updateTimeRemaining(System.currentTimeMillis());
}
public void updateTimeRemaining(long currentTime) {
if (!counterData.isStopped) {
timeDiff = counterData.expirationTime - currentTime;
//System.out.println("Time Diff Inside Method " + timeDiff);
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
stopCounter.setEnabled(true);
stopCounter.getBackground().setColorFilter(null);
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
} else {
counterTextView.setText("Times Up");
startCounter.setEnabled(false);
startCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
// Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
// v.vibrate(5000);
/* if(!counterData.isSoundPlayedBefore) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.stop();
}
});
counterData.isSoundPlayedBefore = true;
if(findIndex(counterData) != -1) {
int index = findIndex(counterData);
counterDataList.set(index,counterData);
saveListSharedPreferences(counterDataList);
}
} */
}
}
else {
long store = counterData.expirationTime + System.currentTimeMillis() - currentTime;
int seconds = (int) (store / 1000) % 60;
int minutes = (int) ((store / (1000 * 60)) % 60);
int hours = (int) TimeUnit.MILLISECONDS.toHours(store);
counterTextView.setText(hours + "H " + minutes + "M " + seconds + "S");
startCounter.setEnabled(true);
startCounter.getBackground().setColorFilter(null);
stopCounter.setEnabled(false);
stopCounter.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
}
}
}
And here's my CounterData class
class CounterData {
long expirationTime;
boolean isStopped;
boolean isSoundPlayedBefore;
int id;
public CounterData(long expirationTime, int id) {
this.expirationTime = expirationTime;
isStopped = true;
isSoundPlayedBefore = false;
this.id = id;
}
public String toString() {
return String.valueOf("Remaining Time: " + TimeUnit.MILLISECONDS.toMinutes(this.expirationTime) + ":" + TimeUnit.MILLISECONDS.toSeconds(this.expirationTime));
}
public void setCounterID(int id) {
this.id = id;
}
public int getCounterID() {
return this.id;
}
}
And I add the time from number pickers of Hour, Minute and Second.
case R.id.counterStartStopButton:
long hour = TimeUnit.HOURS.toMillis(numberPickerHour.getValue());
long minute = TimeUnit.MINUTES.toMillis(numberPickerMinute.getValue());
long second = TimeUnit.SECONDS.toMillis(numberPickerSecond.getValue());
// if(getListSharedPreferences()) {
if(getCounterIDSharedPreferences()) {
counterID = counterID + 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
else {
counterID = 1;
list.add(new CounterData(hour + minute + second, counterID));
saveCounterIDSharedPreferences(counterID);
}
UPDATE
Here's the shared preferences code
public void saveCounterIDSharedPreferences(int id) {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
sharedPreferences.edit().putInt("Counter ID123", id).commit();
}
public boolean getCounterIDSharedPreferences() {
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
if (sharedPreferences.getInt("Counter ID123", -1) != -1) {
counterID = sharedPreferences.getInt("Counter ID123", -1);
return true;
}
else
return false;
}
What turned out to work for me was changing the timer task as following:
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 500, 500);
}

Adapter, Timer and concurrency in Android

Main goal: android app-messendger for chating with company support.
Task: To impliment timers of waiting response from operator or client in listview.
Trouble: In all listview items rendering one of all timer, and then application is listing some timers for a moment are rendering for correctly result, but when they are overlap.
Visually you can see here: https://drive.google.com/file/d/0B_SjoeZavdZwdXlUQlU3QTVKeG8/view?usp=sharing]1
Code:
public class SessionAdapter extends BaseAdapter {
private static final String TAG = SessionAdapter.class.toString();
List<SessionInterface> sessions = new ArrayList<>();
Context context;
private Message mLastMessage;
private List<ViewHolder> lstHolders;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
long currentTime = System.currentTimeMillis();
for (ViewHolder holder : lstHolders) {
holder.updateTimeRemaining(currentTime, 0);
}
}
}
};
public SessionAdapter(List<SessionInterface> sessions, Context context) {
this.sessions = sessions;
this.context = context;
lstHolders = new ArrayList<>();
startUpdateTimer();
}
public void updateSessions(List<SessionInterface> sessionInterface) {
this.sessions = sessionInterface;
}
#Override
public int getCount() {
return sessions.size();
}
#Override
public SessionInterface getItem(int position) {
return sessions.get(position);
}
#Override
public long getItemId(int position) {
SessionInterface session = sessions.get(position);
return session.getId();
}
public long getPositionById(long id) {
for (int i = 1; i < sessions.size(); i++) {
long sessionId = getItemId(i);
Log.d(TAG, "getPositionById-i: " + i);
Log.d(TAG, "getPositionById-id: " + id);
Log.d(TAG, "getPositionById-sessionId: " + sessionId);
boolean eq = id == sessionId;
Log.d(TAG, "getPositionById-sessionId==id: " + eq);
if(eq) {
return i;
}
}
return 0;
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final SessionInterface session = sessions.get(position);
ViewHolder holder;
mLastMessage = session.getMessages().get(session.getMessages().size() - 1);
if(convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.adapter_sessions, null);
holder.label = (TextView) convertView.findViewById(R.id.label);
holder.sessionTitle = (TextView) convertView.findViewById(R.id.ticket_title);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.message = (TextView) convertView.findViewById(R.id.comment);
holder.status = (TextView) convertView.findViewById(R.id.status);
holder.chatStatusImage = (ImageView) convertView.findViewById(R.id.ticket_status);
holder.timeRemaining = (TextView) convertView.findViewById(R.id.time_remaining);
convertView.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.label.setText("Чат #" + session.getId());
holder.sessionTitle.setText(Helpers.stringLimit(session.getQueue().getName(), 30));
try {
Date jud = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", new Locale("ru")).parse(mLastMessage.getDate());
String targetFormat = new SimpleDateFormat("d MMMM, HH:mm", new Locale("ru")).format(jud);
long milliseconds = jud.getTime();
holder.date.setText(targetFormat);
if(session.getClosedTimeAgo() == null) {
holder.updateTimeRemaining(System.currentTimeMillis(), milliseconds);
holder.timeRemaining.setVisibility(View.VISIBLE);
} else {
holder.timeRemaining.setVisibility(View.GONE);
}
} catch (ParseException e) {
e.printStackTrace();
}
holder.message.setText(Helpers.stringLimit(Helpers.stripLineBreaks(mLastMessage.getText(), " "), 50));
if(session.getIs_closed() == 1) {
holder.setClosed(convertView);
} else {
if(mLastMessage.getSender_type().equals(Constants.CLIENT_TYPE)) {
holder.setClientWaiting(convertView);
} else {
holder.setOperatorWaiting(convertView);
}
}
return convertView;
}
private class ViewHolder {
TextView label;
TextView sessionTitle;
TextView date;
TextView message;
TextView status;
ImageView chatStatusImage;
TextView timeRemaining;
public void updateTimeRemaining(long currentTime, long timeAgo) {
Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(currentTime - timeAgo) = " + (currentTime - timeAgo));
Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(timeAgo - currentTime) = " + (timeAgo - currentTime));
long timeDiff = currentTime - timeAgo;
if (timeDiff > 0) {
int seconds = (int) (timeDiff / 1000) % 60;
int minutes = (int) ((timeDiff / (1000 * 60)) % 60);
int hours = (int) ((timeDiff / (1000 * 60 * 60)) % 24);
int hourMinutes = hours*60 + minutes;
timeRemaining.setText(hourMinutes + ":" + (seconds < 10 ? "0" + seconds : seconds));
} else {
timeRemaining.setText("Expired!!");
}
}
public void setClosed(View convertView) {
this.status.setText("Закрыто");
this.status.setTextColor(convertView.getResources().getColor(R.color.closedText));
this.chatStatusImage.setImageDrawable(convertView.getResources().getDrawable(R.drawable.chat_status_closed));
}
public void setOperatorWaiting(View convertView) {
this.status.setText("Оператор ожидает ваш ответ");
this.status.setTextColor(convertView.getResources().getColor(R.color.clientColor));
this.timeRemaining.setTextColor(convertView.getResources().getColor(R.color.clientColor));
this.chatStatusImage.setImageDrawable(convertView.getResources().getDrawable(R.drawable.chat_status_client));
}
public void setClientWaiting(View convertView) {
this.status.setText("Ожидается ответ оператора");
this.status.setTextColor(convertView.getResources().getColor(R.color.operatorColor));
this.timeRemaining.setTextColor(convertView.getResources().getColor(R.color.operatorColor));
this.chatStatusImage.setImageDrawable(convertView.getResources().getDrawable(R.drawable.chat_status_operator));
}
}
}
Fooh.. year.. It's was realy not easy..
Here is my resolving.. maybe it will help anobody in future..
import android.content.Context;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import ru.pinspb.pinsupport.R;
import ru.pinspb.pinsupport.common.Constants;
import ru.pinspb.pinsupport.pojo.Message;
import ru.pinspb.pinsupport.pojo.SessionInterface;
import ru.pinspb.pinsupport.utils.Helpers;
public class SessionAdapter extends RecyclerView.Adapter<SessionAdapter.Holder> {
public interface OnItemClickListener {
void onItemClick(SessionInterface item);
}
private static final String TAG = SessionAdapter.class.toString();
private final OnItemClickListener listener;
List<SessionInterface> sessions = new ArrayList<>();
Context context;
private Message mLastMessage;
private Handler mHandler = new Handler();
public SessionAdapter(List<SessionInterface> sessions, Context context, OnItemClickListener listener) {
this.sessions = sessions;
this.context = context;
this.listener = listener;
}
public void updateSessions(List<SessionInterface> sessionInterface) {
this.sessions = sessionInterface;
}
public int getCount() {
return sessions.size();
}
public SessionInterface getItem(int position) {
return sessions.get(position);
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_sessions, null);
return new Holder(v);
}
#Override
public void onBindViewHolder(final Holder holder, int position) {
final SessionInterface session = sessions.get(position);
mLastMessage = session.getMessages().get(session.getMessages().size() - 1);
holder.bind(session, listener);
holder.label.setText("Чат #" + session.getId());
holder.sessionTitle.setText(Helpers.stringLimit(session.getQueue().getName(), 30));
try {
SimpleDateFormat ru = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", new Locale("ru"));
ru.setTimeZone(TimeZone.getTimeZone("GMT+03:00"));
Date jud = ru.parse(mLastMessage.getDate());
String targetFormat = new SimpleDateFormat("d MMMM, HH:mm", new Locale("ru")).format(jud);
final long milliseconds = jud.getTime();
holder.date.setText(targetFormat);
if(session.getClosedTimeAgo() == null) {
startUpdateTimer(new Runnable() {
#Override
public void run() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Moscow"));
Date currentDate = calendar.getTime();
holder.updateTimeRemaining(currentDate.getTime(), milliseconds);
}
});
// Log.d(TAG, "Sid: " + session.getId() + " ;\nnow: " + System.currentTimeMillis() + ";\n last date: " + mLastMessage.getDate() + "; \nmill: " + milliseconds );
holder.timeRemaining.setVisibility(View.VISIBLE);
} else {
holder.timeRemaining.setVisibility(View.GONE);
}
} catch (ParseException e) {
e.printStackTrace();
}
holder.message.setText(Helpers.stringLimit(Helpers.stripLineBreaks(mLastMessage.getText(), " "), 50));
if(session.getIs_closed() == 1) {
holder.setClosed();
} else {
if(mLastMessage.getSender_type().equals(Constants.CLIENT_TYPE)) {
holder.setClientWaiting();
} else {
holder.setOperatorWaiting();
}
}
}
#Override
public long getItemId(int position) {
SessionInterface session = sessions.get(position);
return session.getId();
}
#Override
public int getItemCount() {
return sessions.size();
}
public long getPositionById(long id) {
for (int i = 1; i < sessions.size(); i++) {
long sessionId = getItemId(i);
boolean eq = id == sessionId;
if(eq) {
return i;
}
}
return 0;
}
private void startUpdateTimer(final Runnable runnable) {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(runnable);
}
}, 1000, 1000);
}
public static class Holder extends RecyclerView.ViewHolder {
TextView label;
TextView sessionTitle;
TextView date;
TextView message;
TextView status;
ImageView chatStatusImage;
TextView timeRemaining;
public Holder(View itemView) {
super(itemView);
this.label = (TextView) itemView.findViewById(R.id.label);
this.sessionTitle = (TextView) itemView.findViewById(R.id.ticket_title);
this.date = (TextView) itemView.findViewById(R.id.date);
this.message = (TextView) itemView.findViewById(R.id.comment);
this.status = (TextView) itemView.findViewById(R.id.status);
this.chatStatusImage = (ImageView) itemView.findViewById(R.id.ticket_status);
this.timeRemaining = (TextView) itemView.findViewById(R.id.time_remaining);
}
public void updateTimeRemaining(long currentTime, long timeAgo) {
// Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(currentTime - timeAgo) = " + (currentTime - timeAgo));
// Log.d(TAG, "updateTimeRemaining:\n currentTime - " + currentTime + ";\n timeAgo - " + timeAgo + ";\n timeDiff(timeAgo - currentTime) = " + (timeAgo - currentTime));
long timeDiff = currentTime - timeAgo;
long seconds = TimeUnit.MILLISECONDS.toSeconds(timeDiff) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(timeDiff));
String time = String.format("%d:%s",
TimeUnit.MILLISECONDS.toMinutes(timeDiff),
seconds < 10 ? seconds + "0" : String.valueOf(seconds)
);
timeRemaining.setText(time);
}
public void setClosed() {
this.status.setText("closed");
this.status.setTextColor(itemView.getResources().getColor(R.color.closedText));
this.chatStatusImage.setImageDrawable(itemView.getResources().getDrawable(R.drawable.chat_status_closed));
}
public void setOperatorWaiting() {
this.status.setText("some text");
this.status.setTextColor(itemView.getResources().getColor(R.color.clientColor));
this.timeRemaining.setTextColor(itemView.getResources().getColor(R.color.clientColor));
this.chatStatusImage.setImageDrawable(itemView.getResources().getDrawable(R.drawable.chat_status_client));
}
public void setClientWaiting() {
this.status.setText("some text");
this.status.setTextColor(itemView.getResources().getColor(R.color.operatorColor));
this.timeRemaining.setTextColor(itemView.getResources().getColor(R.color.operatorColor));
this.chatStatusImage.setImageDrawable(itemView.getResources().getDrawable(R.drawable.chat_status_operator));
}
public void bind(final SessionInterface item, final OnItemClickListener listener) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick(item);
}
});
}
}
}

Item deleting from listview affecting asynctask

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

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

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

ListView button at position not clicked proper click in android

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

Categories

Resources