Textview value changes during scroll in listview android - android

I am developing multiple file download app. in which, if switch is on then downloading is start and if switch is off then downloading is cancel. I am updating item value using timertask with handler. below is my code of adapter. everything is working fine but when I am scrolling listview, item value (percentage count) are conflict with other values which are other file downloaded progress.
Code:
public class DownloadAdapter extends ArrayAdapter<AudioSubModel> {
private static final String PDF_MIME_TYPE = "application/pdf";
private LayoutInflater lf;
Context mContext;
private List<ListContent> lstHolders;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
for (ListContent holder : lstHolders) {
holder.updateTimeRemaining();
}
}
}
};
AudioSubModel getAlarm(int position){
return ((AudioSubModel) getItem(position));
}
public DownloadAdapter(Context context, int resource, List<AudioSubModel> objects) {
super(context, resource, objects);
lf = LayoutInflater.from(context);
lstHolders = new ArrayList<ListContent>();
mContext = context;
Log.e("ADAPTER", "CONSTR");
startUpdateTimer();
}
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 view, ViewGroup parent) {
ListContent holder = null;
if (view == null) {
view = lf.inflate(R.layout.row_audio_desc_layout, null);
holder = new ListContent();
holder.ivImg = (CircleImageView)view.findViewById(R.id.row_audio_desc_ivImg);
holder.tvTitle = (TextView) view
.findViewById(R.id.row_audio_desc_tvTitle);
holder.tvDesc = (TextView) view
.findViewById(R.id.row_audio_desc_tvDesc);
holder.llDownload = (LinearLayout)view.findViewById(R.id.row_audio_desc_llDownload);
holder.PBDownload = (RoundCornerProgressBar)view.findViewById(R.id.row_audio_desc_PBDownload);
holder.tvReadPdf = (TextView)view.findViewById(R.id.row_audio_desc_tvReadPdf);
holder.tvMakeOffline = (TextView)view.findViewById(R.id.row_audio_desc_tvMakeOffline);
holder.swtchDownload = (Switch)view.findViewById(R.id.row_audio_desc_swtchDownloadOn);
holder.tvDownload = (TextView)view.findViewById(R.id.row_audio_desc_tvDownload);
holder.tvDownloadPercent = (TextView)view.findViewById(R.id.row_audio_desc_tvDownloadPercent);
holder.ivCancel = (ImageView)view.findViewById(R.id.row_audio_desc_ivCancel);
holder.ivPlay = (ImageView)view.findViewById(R.id.row_audio_desc_ivPlay);
holder.tvTitle.setTypeface(MyApplication.app_bold);
holder.tvDesc.setTypeface(MyApplication.app_light);
holder.tvReadPdf.setTypeface(MyApplication.app_bold);
holder.tvMakeOffline.setTypeface(MyApplication.app_bold);
holder.swtchDownload.setTypeface(MyApplication.app_bold);
holder.tvDownload.setTypeface(MyApplication.app_bold);
holder.tvDownloadPercent.setTypeface(MyApplication.app_bold);
view.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ListContent) view.getTag();
}
holder.setData(getAlarm(position));
// convertView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// ((MainActivity)mContext).ItemClickFetch(getItem(position).getId());
// }
// });
return view;
}
class ListContent {
LinearLayout llDownload;
RoundCornerProgressBar PBDownload;
CircleImageView ivImg;
ImageView ivCancel, ivPlay;
TextView tvTitle, tvDesc, tvReadPdf, tvMakeOffline, tvDownload, tvDownloadPercent;
Switch swtchDownload;
private AudioSubModel aItem;
DownloadFileFromURL dwnldFileUrl;
public void setData(AudioSubModel item) {
aItem = item;
dwnldFileUrl = new DownloadFileFromURL();
if(item.isPlaying()){
ivPlay.setImageResource(R.drawable.pausebtn);
}else{
ivPlay.setImageResource(R.drawable.playbtn);
}
if(aItem.isDownloading()){
swtchDownload.setOnCheckedChangeListener(null);
swtchDownload.setChecked(true);
tvDownloadPercent.setText(aItem.getPercent() + "");
}else{
swtchDownload.setOnCheckedChangeListener(null);
swtchDownload.setChecked(false);
tvDownloadPercent.setText("0");
}
// holder.tvDownloadPercent.setText(data.get(position).getPercent()+" %");
tvDownload.setText(aItem.getDwnLbl());
tvTitle.setText(aItem.getTitle());
tvDesc.setText(aItem.getDesc());
Bitmap bmp = BitmapFactory.decodeFile(aItem.getImage());
ivImg.setImageBitmap(bmp);
// Log.e("MAIN", "IS DONE: " + aItem.isOn());
tvReadPdf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isPDFSupported(mContext)){
Uri path = Uri.fromFile(new File(aItem.getPdf()));
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(objIntent);
}else{
if(GeneralClass.getConnectivityStatusString(mContext)){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://docs.google.com/gview?embedded=true&url="+aItem.getPdfurl()));
mContext.startActivity(browserIntent);
}else{
GeneralClass.showToast("Check internet connection to view pdf file", mContext);
}
}
}
});
ivPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(aItem.isPlaying()){
aItem.setPlaying(false);
((MainActivity)mContext).stopAudioFile();
}else{
aItem.setPlaying(true);
((MainActivity)mContext).playAudioFile(aItem);
}
}
});
swtchDownload.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// updateView(position, arg1);
Log.e("Audio ADAPTER", "file: " + arg1);
if(arg1){
aItem.setDownloading(true);
aItem.setDwnLbl("Downloading");
dwnldFileUrl.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, aItem.getAudiourl());
}else if(!arg1){
aItem.setDownloading(false);
aItem.setDwnLbl("Download");
dwnldFileUrl.cancel(true);
}
}
});
ivCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
aItem.setDownloading(false);
aItem.setDwnLbl("Download");
dwnldFileUrl.cancel(true);
// updateView(position, false);
// new DownloadFileFromURL(holder, position).execute(data.get(position).getAudiourl());
}
});
updateTimeRemaining();
}
public void updateTimeRemaining() {
// Log.e("MAIN", "GET TIME: " + aItem.getTimeStamp());
if(aItem.isDownloading()){
llDownload.setVisibility(View.VISIBLE);
tvDownloadPercent.setVisibility(View.VISIBLE);
tvDownloadPercent.setText(aItem.getPercent()+"");
// PBDownload.setProgress(aItem.getPercent());
tvDownload.setText(aItem.getDwnLbl());
}else{
llDownload.setVisibility(View.INVISIBLE);
tvDownloadPercent.setVisibility(View.INVISIBLE);
tvDownloadPercent.setText("0");
// PBDownload.setProgress(0);
tvDownload.setText(aItem.getDwnLbl());
}
// if(aItem.isOn()){
// tvTitle.setText(aItem.getPercent()+"");
// }else{
// tvTitle.setText("0");
// }
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
private volatile boolean running = true;
String finalFilePath="";
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
// URL url = new URL(f_url[0]);
URL url = new URL("http://www.robtowns.com/music/blind_willie.mp3");
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);
// Output stream to write file
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String outputFile = extStorageDirectory+"/"+GeneralClass.FILE_PATH;
finalFilePath = outputFile+"/audio"+aItem.getId()+".mp3";
OutputStream output = new FileOutputStream(finalFilePath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1 && running) {
if(isCancelled()){
Log.e("ADAPTER", "Async break");
break;
}
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onCancelled() {
running = false;
Log.e("ADAPTER", "Async cancelled");
}
/**
* Updating progress bar
* */
#Override
protected void onProgressUpdate(String... progress) {
// setting progress percentage
aItem.setPercent(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
Log.e("ADAPTER", "DONE ID: " + aItem.getId());
((MainActivity)mContext).updateAudioFileDownload(aItem.getId(), finalFilePath);
ivCancel.setVisibility(View.INVISIBLE);
}
}
}
public static boolean isPDFSupported(Context context) {
Intent i = new Intent( Intent.ACTION_VIEW );
final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}
}
Help me with this major issue.

Related

If Recyclerview scroll then item id change how to resolve?

public PDFListAdapter(Context context, ArrayList<NotesResponseInfo> pdfModelClasses, String final_nav_opt_name) {
this.context = context;
this.pdfModelClasses = pdfModelClasses;
this.final_nav_opt_name = final_nav_opt_name;
databaseNotes = new DatabaseNotes(context);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtBookName, txtBookTitle, txtBookBookDateOFIssue, txtBookCategory, txtDownload;
LinearLayout layout_open_pdf, layout_download_note_option;
ImageView imgDownloadNote, imgCancelDownloadNote;
ProgressBar progress_download_note;
public MyViewHolder(View view) {
super(view);
txtBookName = (TextView) view.findViewById(R.id.txtBookName);
txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
txtBookBookDateOFIssue = (TextView) view.findViewById(R.id.txtBookBookDateOFIssue);
txtBookCategory = (TextView) view.findViewById(R.id.txtBookCategory);
txtDownload = view.findViewById(R.id.txtDownload);
layout_open_pdf = (LinearLayout) view.findViewById(R.id.layout_open_pdf);
layout_download_note_option = (LinearLayout) view.findViewById(R.id.layout_download_note_option);
imgDownloadNote = (ImageView) view.findViewById(R.id.imgDownloadNote);
progress_download_note = (ProgressBar) view.findViewById(R.id.progress_download_note);
imgCancelDownloadNote = (ImageView) view.findViewById(R.id.imgCancelDownloadNote);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_pdf_adapter, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder1, int index) {
holder = holder1;
final int position = index;
pdfList = pdfModelClasses.get(position);
final DownloadedNotesDataBase databaseNotes = new DownloadedNotesDataBase(context);
holder.txtBookName.setText(pdfList.getSubjectName().toUpperCase());
holder.txtBookTitle.setText(StringUtils.getTrimString(pdfList.getTypeName()));
holder.txtBookBookDateOFIssue.setText(pdfList.getType());
holder.txtBookCategory.setText(StringUtils.getTrimString(pdfList.getDescription()));
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
holder.txtDownload.setVisibility(View.VISIBLE);
holder.layout_download_note_option.setVisibility(View.GONE);
} else {
holder.txtDownload.setVisibility(View.GONE);
holder.layout_download_note_option.setVisibility(View.VISIBLE);
}
holder.layout_open_pdf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pdfList = pdfModelClasses.get(position);
// holder = holder1;
Log.e("PDFListAdapter", "layout_open_pdf position = "+position);
Log.e("PDFListAdapter", "layout_open_pdf = "+pdfList.getId());
if (databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
DownloadeNotesModel downloadeNotesModel = databaseNotes.getNotesByID(pdfList.getId(), final_nav_opt_name);
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", downloadeNotesModel.getFileLocation());
intent.putExtra("from", "database");
intent.putExtra("getSubjectName", downloadeNotesModel.getSubjectName());
context.startActivity(intent);
} else {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Alert");
alertDialog.setCancelable(true);
alertDialog.setMessage("Notes not downloaded. Do you want to download it?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
}
});
/* alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(context, PDFResults.class);
intent.putExtra("pdfList", pdfList.getFileName());
intent.putExtra("from", "url");
intent.putExtra("getSubjectName", pdfList.getSubjectName());
context.startActivity(intent);
}
});*/
alertDialog.show();
}
}
});
holder.imgDownloadNote.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgDownloadNote = "+pdfList.getId());
pdfList = pdfModelClasses.get(position);
holder = holder1;
if (!databaseNotes.isPurchasedNoteSaved(pdfList.getId(), final_nav_opt_name)) {
if (UtilsMethods.isNetworkAvailable(context)) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
downloader = new Downloader();
new CheckSpace().execute(pdfList.getFileName());
} else {
Toast.makeText(context, "storage permission is not granted", Toast.LENGTH_SHORT).show();
PermissionCheck.checkWritePermission(context);
}
} else {
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
context.startActivity(new Intent(context, NoInternetActivity.class));
}
}
else Log.e("","Not in db");
}
});
holder.imgCancelDownloadNote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("PDFListAdapter", "imgCancelDownloadNote position = "+position);
Log.e("PDFListAdapter", "imgCancelDownloadNote = "+pdfList.getId());
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Are you sure want to cancel download?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
downloader.cancel(true);
}
});
alertDialog.show();
}
});
}
#Override
public int getItemCount() {
return pdfModelClasses.size();
}
#Override
public int getItemViewType(int position)
{
return position;
}
private void startSave(final Context context, NotesResponseInfo url) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
final base_url b = new base_url();
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(b.BASE_URL);
Retrofit retrofit = builder.client(httpClient.build()).build();
AllApis downloadService = retrofit.create(AllApis.class);
Call<ResponseBody> call = downloadService.downloadFileByUrl(StringUtils.getCroppedUrl(url.getFileName()));
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
downloader.execute(response.body());
} else {
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
}
private class Downloader extends AsyncTask<ResponseBody, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
#Override
protected void onProgressUpdate(Integer... values) {
mBuilder.setContentTitle("Download")
.setContentText("Download in progress")
.setSmallIcon(R.mipmap.lun);
mBuilder.setProgress(100, values[0], false);
mNotifyManager.notify(id, mBuilder.build());
super.onProgressUpdate(values);
}
#Override
protected void onCancelled() {
super.onCancelled();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
mNotifyManager.cancelAll();
}
#Override
protected Integer doInBackground(ResponseBody... params) {
ResponseBody body = params[0];
try {
URL url = new URL(pdfList.getFileName());
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestProperty("Accept-Encoding", "identity");
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
ContextWrapper wrapper = new ContextWrapper(getApplicationContext());
int lenghtOfFile = c.getContentLength();
Log.w("getContentLength",""+lenghtOfFile);
File file = wrapper.getDir("PDF", MODE_PRIVATE);
file = new File(file, pdfList.getSubjectName() + "_" + TimeUtils.getCurrentTimeStamp() + ".pdf");
FileOutputStream f = new FileOutputStream(file);
InputStream in = c.getInputStream();
float finalValue = 0;
byte[] buffer = new byte[100 * 1024];
int len1 = 0;
int progress = 0;
long total = 0;
if (!(isCancelled())) {
while ((len1 = in.read(buffer)) !=-1) {
if (UtilsMethods.isNetworkAvailable(context)) {
f.write(buffer, 0, len1);
total += len1;
setProgress(Integer.parseInt(("" + (int) ((total * 100) / lenghtOfFile))));
/* progress += len1;finalValue = (float) progress/body.contentLength() *100;
setProgress((int) finalValue);
mBuilder.setProgress((int) finalValue,0,false);*/
} else {
File file1 = new File(file.getPath());
file1.delete();
cancel(true);
}
}
new DownloadedNotesDataBase(context).addDonloadedNotesToDatabase(file.getPath(), pdfList);
} else {
File file1 = new File(file.getPath());
file1.delete();
holder.imgDownloadNote.setVisibility(View.VISIBLE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (ProtocolException e1) {
e1.printStackTrace();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
mBuilder.setContentText("Download complete");
mBuilder.setSmallIcon(R.mipmap.ic_logo);
mBuilder.setProgress(100, 100, false);
mNotifyManager.notify(id, mBuilder.build());
holder.txtDownload.setVisibility(View.VISIBLE);
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.GONE);
holder.progress_download_note.setVisibility(View.GONE);
}
private void setProgress(int progress) {
mBuilder.setContentText("Downloading...")
.setContentTitle(progress + "%")
.setSmallIcon(R.mipmap.ic_logo)
.setOngoing(true)
.setContentInfo(progress + "%")
.setProgress(100, progress, false);
mNotifyManager.notify(id, mBuilder.build());
holder.progress_download_note.setProgress(progress);
}
}
public class CheckSpace extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String file_size = "";
URL url = null;
try {
url = new URL(params[0]);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int fileSize = urlConnection.getContentLength();
file_size = UtilsMethods.generateFileSize(fileSize);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return file_size;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
#Override
protected void onPostExecute(String result) {
if (UtilsMethods.compareSpace(result)) {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Download this PDF of size " + result + " ?");
alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
holder.imgDownloadNote.setVisibility(View.GONE);
holder.imgCancelDownloadNote.setVisibility(View.VISIBLE);
holder.progress_download_note.setVisibility(View.VISIBLE);
startSave(context, pdfList);
}
});
alertDialog.show();
} else {
final AlertDialog alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogStyle).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Unable to download file. Storage space is not available");
alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void onClick(DialogInterface dialog, int which) {
alertDialog.hide();
}
});
alertDialog.show();
}
}
}
}
this is my adapter class
I have a RecyclerView. Each row has a Download button, Cancale button, and Progressbar. when click on the Download button have to Download PDF from my phone storage and have to progress Progressbar The problem is when I scroll down the recyclerview the change item Id .means I can fit 1 items on the screen at once.then scroll ItemId change

listview change to default when keyboard opens

In a list view i have image, text and image contains default image when list load with download complete , every thing works fine but when keyboard opens the downloaded image change to default image.
public class ChatScreen extends Activity implements OnClickListener
{
private void stopTimer()
{
if (mTimer1 != null)
{
mTimer1.cancel();
mTimer1.purge();
}
}
private void startTimer()
{
mTimer1 = new Timer();
mTt1 = new TimerTask()
{
public void run()
{
mTimerHandler.post(new Runnable()
{
public void run()
{
try
{
Date date1 = getDate(time);
Date date2 = getDate(getCurrentTime());
if (date2.getTime() - date1.getTime() == 5000)
{
stopTimer();
try
{
chat.setCurrentState(ChatState.paused,
chatWithJID, FromChatJID);
} catch (XMPPException e)
{
e.printStackTrace();
}
isTyping = false;
}
else if (date2.getTime() - date1.getTime() > 30000)
{
time = getCurrentTime();
try
{
chat.setCurrentState(ChatState.gone,
chatWithJID, FromChatJID);
} catch (XMPPException e)
{
e.printStackTrace();
}
isTyping = false;
}
}
catch (ParseException e)
{
e.printStackTrace();
}
catch(IllegalStateException e)
{
e.printStackTrace();
}
}
});
}
};
mTimer1.schedule(mTt1, 00, 5000);
}
#Override
protected void onPause()
{
super.onPause();
chat.setChatFragment(null);
System.out.println("onPasue called");
}
}
}
}
}
}
#Override
protected void onResume()
{
super.onResume();
session.saveCurrentName(this.getLocalClassName());
chat.setChatFragment(ctx);
System.out.println("onResume called");
if(checkForCurfew())
showHideView(true, 0);
else
showHideView(false, 0);
}
public void showHideView(final boolean value, final int type)
{
System.out.println("Called");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if(value)
{
btnSend.setEnabled(value);
btnSend.setAlpha(1.0f);
inputMessage.setEnabled(value);
btnSticker.setEnabled(value);
btnSticker.setAlpha(1.0f);
btnPicture.setEnabled(value);
btnPicture.setAlpha(1.0f);
doodle_btn.setEnabled(value);
doodle_btn.setAlpha(1.0f);
}
else
{
btnSend.setEnabled(value);
btnSend.setAlpha(0.5f);
inputMessage.setEnabled(value);
btnSticker.setEnabled(value);
btnSticker.setAlpha(0.5f);
btnPicture.setEnabled(value);
btnPicture.setAlpha(0.5f);
doodle_btn.setEnabled(value);
doodle_btn.setAlpha(0.5f);
}
if(!value && type == 0)
inputMessage.setHint("You can't chat during a curfew");
else if(!value && type == 1)
inputMessage.setHint("Can’t Access Internet");
else
inputMessage.setHint("Enter message here");
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
System.gc();
setContentView(R.layout.activity_fragment_chat);
System.out.println("Chat screen called.");
mcon = ChatScreen.this;
chat = ((RooChat) getApplication()).chat;
Bundle bundle = getIntent().getBundleExtra("bundle_data");
System.out.println("bundle- " + bundle);
chatWithJID = bundle.getString("chat_with");
chatWithName = bundle.getString("kid_name");
FromChatJID = bundle.getString("chat_from");
ChatRoomName = bundle.getString("chat_room");
indexOfChatRoom = Integer.parseInt(bundle.getString("index"));
CopyindexOfChatRoom = indexOfChatRoom;
typeFaceCurseCasual = AppFonts.getFont(mcon, AppFonts.CurseCasual);
typeFaceARLRDBDHand = AppFonts.getFont(mcon, AppFonts.ARLRDBDHand);
back = (Button) findViewById(R.id.back);
sendBtn=(Button)findViewById(R.id.send);
sendBtn.setOnClickListener(this);
erasebtn=(Button)findViewById(R.id.erase);
erasebtn.setOnClickListener(this);
smallers=(Button)findViewById(R.id.small_ers1);
smallers.setOnClickListener(this);
mediumers=(Button)findViewById(R.id.medium_ers1);
mediumers.setOnClickListener(this);
largeers=(Button)findViewById(R.id.large_ers1);
largeers.setOnClickListener(this);
smallline=(Button)findViewById(R.id.small);
smallline.setOnClickListener(this);
mediumline=(Button)findViewById(R.id.medium);
mediumline.setOnClickListener(this);
largeline=(Button)findViewById(R.id.large);
largeline.setOnClickListener(this);
back1=(Button)findViewById(R.id.back1);
back1.setOnClickListener(this);
drawView=(DrawingView)findViewById(R.id.Drawing);
doodle_btn=(Button)findViewById(R.id.doodle_btn);
doodle_btn.setOnClickListener(this);
doodle=(LinearLayout) findViewById(R.id.doodle);
back.setOnClickListener(this);
init();
String available = convertAvailability(chat.getUserAvailability(chatWithJID));
if (chatWithName.equalsIgnoreCase("echo") || chatWithName.equalsIgnoreCase("puzzle")
|| chatWithName.equalsIgnoreCase("msr"))
{
image.setImageResource(R.drawable.status_active);
}
else if (available.equalsIgnoreCase("offline"))
{
chat.sendIQForLastSeen(chatWithJID);
image.setImageResource(R.drawable.status_offline);
}
else
{
// chatState.setText(available);
image.setImageResource(R.drawable.status_active);
}
inputMessage.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (chat.isConnected())
{
try
{
time = getCurrentTime();
}
catch (ParseException e1)
{
e1.printStackTrace();
}
if (isTyping == false)
{
try
{
chat.setCurrentState(ChatState.composing, chatWithJID, FromChatJID);
isTyping = true;
startTimer();
}
catch (XMPPException e)
{
e.printStackTrace();
}
}
else if (isTyping == true)
{
stopTimer();
startTimer();
}
}
/*else
Toast.makeText(getApplicationContext(), "Please wait, connecting to server.", 0).show();
*/
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
}
});
inputMessage.setOnFocusChangeListener(new OnFocusChangeListener()
{
#Override
public void onFocusChange(final View v, final boolean hasFocus)
{
if (hasFocus && inputMessage.isEnabled() && inputMessage.isFocusable())
new Runnable()
{
#Override
public void run()
{
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(inputMessage, InputMethodManager.SHOW_IMPLICIT);
}
};
}
});
data = session.getUserDetails();
banned = session.getBannedWord();
System.out.println(banned);
JSONArray jsonArray;
if(!banned.equals(""))
{
try
{
jsonArray = new JSONArray(banned);
strArr = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++)
{
strArr[i] = jsonArray.getString(i);
}
//System.out.println(Arrays.toString(strArr));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
public void reFreshData()
{
indexOfChatRoom = db.getChatRoomIndex(chatWithName);
messages = db.getFriendChat(indexOfChatRoom);
adapter = new ChatMessageAdapter(mcon, messages);
chatList.setAdapter(adapter);
}
private void init()
{
db = new DatabaseHelper(mcon);
ctx = this;
chat.setChatFragment(ctx);
session = new SessionManager(mcon);
chatList = (ListView) findViewById(R.id.chatList);
chatWith = (TextView) findViewById(R.id.chat_with);
doodle_txt = (TextView) findViewById(R.id.doodle_txt);
chatState = (TextView) findViewById(R.id.chat_status);
btnPicture = (TextView) findViewById(R.id.picture);
btnPicture.setOnClickListener(this);
btnSticker = (TextView) findViewById(R.id.sticker);
btnSticker.setOnClickListener(this);
btnExtra = (TextView) findViewById(R.id.extra);
btnExtra.setOnClickListener(this);
btnSend = (TextView) findViewById(R.id.btn_send);
btnSend.setTypeface(typeFaceARLRDBDHand, Typeface.BOLD);
btnSend.setOnClickListener(this);
inputMessage = (EditText) findViewById(R.id.et_message);
inputMessage.setTypeface(typeFaceCurseCasual);
chatWith.setText(chatWithName);
image = (ImageView) findViewById(R.id.img_chat_status);
cross = (ImageView) findViewById(R.id.cross);
cross.setOnClickListener(this);
lay_sticker_main = (LinearLayout) findViewById(R.id.lay_sticker_main);
lay_sticker_child = (FlowLayout) findViewById(R.id.lay_sticker_child);
lay_sticker_group = (FlowLayout) findViewById(R.id.lay_sticker_group);
reFreshData();
chatList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, final View arg1, final int arg2,
long arg3) {
// TODO Auto-generated method stub
final ChatMessage msg=adapter.getItem(arg2);
final ImageView btn = (ImageView) arg1.findViewById(R.id.textView1);
final ImageView imgone = (ImageView)arg1.findViewById(R.id.imagev);
try{
if(!btn.getTag().toString().equals("")){
Log.v("","msg getting:..."+btn.getTag().toString());
DownloadImage di=new DownloadImage(ChatScreen.this, btn.getTag().toString(), new BitmapAsyncTaskCompleteListener() {
#Override
public void onTaskComplete(Bitmap result) {
// TODO Auto-generated method stub
Log.v("Img :",""+result);
imgone.setImageBitmap(result);
String filePath=saveImage(result,msg.getId(),msg.getFrom());
btn.setVisibility(View.GONE);
btn.setTag(filePath);
final int index = chatList.getFirstVisiblePosition();
View v = chatList.getChildAt(0);
final int top = (v == null) ? 0 : v.getTop();
Log.v("", "top :.."+top);
chatList.post(new Runnable() {
#Override
public void run() {
chatList.setSelectionFromTop(index,top);
}
});
}
});
di.execute();
}
}
catch(Exception ex){
btn.setVisibility(View.GONE);
btn.setTag("");
}
}
});
handler = new Handler(Looper.getMainLooper())
{
#Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case REFRESH_CHAT_LIST:
adapter.notifyDataSetChanged();
break;
case REFRESH_CHAT_STATUS:
if(text != null)
{
try
{
if (isNumeric(text))
{
chatState.setText(calculateTime(Long.parseLong(text)));
image.setImageResource(R.drawable.status_offline);
}
else
{
chatState.setText(text);
if (chatWithName.equalsIgnoreCase("echo")
|| chatWithName.equalsIgnoreCase("puzzle")
|| chatWithName.equalsIgnoreCase("msr")) {
image.setImageResource(R.drawable.status_active);
} else if (text.equalsIgnoreCase("offline")) {
chat.sendIQForLastSeen(chatWithJID);
image.setImageResource(R.drawable.status_offline);
} else {
image.setImageResource(R.drawable.status_active);
}
}
}
catch(NumberFormatException e)
{
image.setImageResource(R.drawable.status_offline);
e.printStackTrace();
}
}
break;
case REFRESH_MESSAGE_DELIVERY:
adapter.notifyDataSetChanged();
break;
default:
break;
}
}
};
}String filePath ="";
private String saveImage(Bitmap finalBitmap,int chatWith,String from) {
String fileName = chat.getCurrentDateTime();
//msg = "You got a photo. Display of photo will be added in next version of this app.";
final File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "/roo_kids/images/" + from + "/");
if (!dir.exists())
{
dir.mkdirs();
}
final File myFile = new File(dir, fileName + ".png");
if (!myFile.exists())
{
try
{
myFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(myFile);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
filePath= myFile.getAbsolutePath()+"::images::";
Log.v("","filePath after decoding:.."+filePath);
Log.v("","chatWith Id after decoding:.."+chatWith);
Log.v("","from after decoding:.."+from);
db.updateFriendChat(chatWith,filePath);
return filePath;
}
public void getAllFiles(String directoryName)
{
}
public boolean isFileExist(String directoryName, String filename)
{
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.picture:
openGallery();
break;
case R.id.extra:
break;
case R.id.btn_send:
sendMessageAndValidate();
break;
case R.id.back:
onBackPressed();
break;
default:
break;
}
}
private void openGallery()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
//intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(intent, SELECT_PICTURE);
}
private String encodeFileToBase64Binary(String path)throws IOException, FileNotFoundException
{
}
String cond="";
public class ExecuteImageSharingProcess extends AsyncTask<String, Integer, String>
{
String base64 = "";
ProgressDialog pd = null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(ChatScreen.this);
pd.setCancelable(false);
pd.setMessage("Please wait..");
pd.show();
}
#Override
protected String doInBackground(String... params)
{
try
{
//base64 = encodeFileToBase64Binary(params[0]);
Log.v("", "params[0].."+params[0]);
byte[] data = params[0].getBytes("UTF-8");
base64= new String(data);
Log.v("", "base64.."+base64);
return "yes";
}
catch (IOException e)
{
e.printStackTrace();
return "no";
}
catch(NullPointerException e)
{
return "no";
}
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(result.equals("yes"))
{
if(chat.isConnected())
{
String prefix = chat.generateRandomChar()+"imagePrefixEnd";
System.out.println("prefix-> "+prefix);
ctx.moveMessagetoXMPP(prefix + base64 + "::images::", 1);
base64 = "";
bitmap = null;
}
}
else
{
Toast.makeText(ctx, "File not found.", Toast.LENGTH_LONG).show();
}
try
{
if ((this.pd != null) && this.pd.isShowing())
{
this.pd.dismiss();
}
} catch (final IllegalArgumentException e)
{
} catch (final Exception e)
{
} finally
{
this.pd = null;
}
}
}
String imgDecodableString = null;
String imgbase64="";
AlertManager alert_dialog;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent i)
{
super.onActivityResult(requestCode, resultCode, i);
try
{
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && null != data)
{
String urlofimage=""; // here i send base64 image to server and it will returns url of image that is send in ExecuteImageSharingProcess method.
new ExecuteImageSharingProcess().execute(urlofimage);
}
});
ucIA.execute();
}
}
else if (resultCode == Activity.RESULT_CANCELED)
{
bitmap = null;
}
} catch (Exception e)
{
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
private void sendMessageAndValidate()
{
String msg=inputMessage.getText().toString().replace(" ","");
String msgone=msg.replace("\n", "");
if (msgone.length() > 0)
{
if (chat.isConnected())
{
ctx.moveMessagetoXMPP(inputMessage.getText().toString(), 0);
inputMessage.setText("");
stopTimer();
}
}
}
String thread="";
protected void moveMessagetoXMPP(String msg, final int type)
{
data = session.getUserDetails();
if (checkChatRoomAvailablity(chatWithName))
{
thread = db.getThreadFromChatroom(chatWithName);
}
if (thread.equals(""))
thread = ChatRoomName;
chat.sendMesage(indexOfChatRoom, msg, FromChatJID, chatWithJID, thread, type);
try
{
chat.setCurrentState(ChatState.paused, chatWithJID, FromChatJID);
}
catch (XMPPException e)
{
e.printStackTrace();
}
}
public class MyThread implements Runnable
{
String message;
File file;
public MyThread(String message, File file)
{
this.message = message;
this.file = file;
}
#Override
public void run()
{
String fileName;
if(message.contains("::images::"))
fileName = saveFile(decodeBase64(message.substring(message.indexOf("imagePrefixEnd")+14, message.indexOf("::images::"))), file);
else
fileName = saveFile(decodeBase64(message.substring(message.indexOf("imagePrefixEnd")+14, message.indexOf("::doodle::"))), file);
}
}
public void appendMessageInListView(long _id)
{
if (messages.size() > 0)
{
System.out.println(messages.get(messages.size() - 1).getId());
ChatMessage cm = db.getFriendChatMessage(indexOfChatRoom, ""+ messages.get(messages.size() - 1).getId());
messages.add(messages.size(), cm);
}
else
{
ChatMessage cm = db.getFriendChatMessage(indexOfChatRoom, "" + _id);
messages.add(messages.size(), cm);
}
refreshChatList();
}
public void refreshChatList()
{
int state = REFRESH_CHAT_LIST;
Message msg = handler.obtainMessage(state);
msg.sendToTarget();
}
public void refreshChatStatus() {
int state = REFRESH_CHAT_STATUS;
Message msg = handler.obtainMessage(state);
msg.sendToTarget();
}
public int getChatIndex2(String participant) {
return db.getChatRoomIndex(participant);
}
ImageView img;
View oldview;
public class ChatMessageAdapter extends BaseAdapter
{
public ArrayList<ChatMessage> messages;
private Context ctx;
public ChatMessageAdapter(Context ctx, ArrayList<ChatMessage> messages)
{
this.ctx = ctx;
this.messages = messages;
}
#Override
public int getCount()
{
return messages.size();
}
#Override
public long getItemId(int arg0)
{
return arg0;
}
#Override
public View getView(int position, View oldView, ViewGroup parent)
{
if (ctx == null)
return oldView;
final ChatMessage msg = getItem(position);
if (oldView == null || (((Integer) oldView.getTag()) != msg.getIsOutgoing()))
{
LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
if (msg.getIsOutgoing() == MyMessage.OUTGOING_ITEM)
{
oldView = inflater.inflate(R.layout.fragment_message_outgoing_item, null);
oldView.setTag(MyMessage.OUTGOING_ITEM);
}
else
{
oldView = inflater.inflate(R.layout.fragment_message_ingoing_item, null);
oldView.setTag(MyMessage.INGOING_ITEM);
}
}
TextView message = (TextView) oldView.findViewById(R.id.msg);
message.setTypeface(typeFaceCurseCasual);
LinearLayout lay_txt = (LinearLayout) oldView.findViewById(R.id.lay_txt);
LinearLayout lay_img = (LinearLayout) oldView.findViewById(R.id.lay_img);
img = (ImageView) oldView.findViewById(R.id.imagev);
FrameLayout fmlay=(FrameLayout) oldView.findViewById(R.id.fmlay);
ImageView textView1 = (ImageView) oldView.findViewById(R.id.textView1);
ImageView imgSticker = (ImageView) oldView.findViewById(R.id.img_sticker);
ImageView tickSent = (ImageView) oldView.findViewById(R.id.tickSent);
ImageView tickDeliver = (ImageView) oldView.findViewById(R.id.tickDeliver);
TextView timestamp = (TextView) oldView.findViewById(R.id.timestamp);
oldview=oldView;
timestamp.setTypeface(typeFaceCurseCasual);
message.setText(msg.getMessage());
System.out.println("message in adapter");
if (msg.getIsOutgoing() == MyMessage.OUTGOING_ITEM)
tickSent.setVisibility(View.VISIBLE);
else
tickSent.setVisibility(View.INVISIBLE);
if (msg.getIsDeliver() == true)
tickDeliver.setVisibility(View.VISIBLE);
else
tickDeliver.setVisibility(View.INVISIBLE);
if(msg.getTimeStamp()!= null) timestamp.setText(getTimeAgo(Long.parseLong(msg.getTimeStamp()),ctx));
if(msg.getMessage()!= null)
{
if(msg.getMessage().contains("::sticker::"))
{
lay_img.setVisibility(View.GONE);
lay_txt.setVisibility(View.GONE);
imgSticker.setVisibility(View.VISIBLE);
String Dir = msg.getMessage().substring(2, msg.getMessage().indexOf("-"));
String file = msg.getMessage().substring(2, msg.getMessage().indexOf("}}"));
if(isFileExist(Dir, file))
{
String path = ctx.getFilesDir() + "/booksFolder/"+Dir+"/"+file;
System.out.println("path- "+ path);
Uri imgUri = Uri.parse("file://"+path);
imgSticker.setImageURI(imgUri);
}
else
{
String url = "http://s3.amazonaws.com/rk-s-0ae8740/a/"+file;
System.out.println(url);
new ImageLoaderWithImageview(mcon).DisplayImage(url, imgSticker);
}
}
else if(!msg.getMessage().contains("::images::") && !msg.getMessage().contains("::doodle::"))
{
System.out.println("in text condition");
lay_img.setVisibility(View.GONE);
imgSticker.setVisibility(View.GONE);
lay_txt.setVisibility(View.VISIBLE);
System.out.println("msg coming :"+msg.getMessage());
message.setText(msg.getMessage());
}
else
{
lay_txt.setVisibility(View.GONE);
imgSticker.setVisibility(View.GONE);
lay_img.setVisibility(View.VISIBLE);
if (msg.getIsOutgoing() == MyMessage.INGOING_ITEM)
{
fmlay.setVisibility(View.VISIBLE);
}
Log.v("","msg getting:..."+msg.getMessage());
String pathOne = null ;
if(msg.getMessage().contains("imagePrefixEnd")){
Log.v("In images/doddle if", "askfk");
pathOne="default";
textView1.setVisibility(View.VISIBLE);
String imgpath=setdefaultImage(msg.getMessage());
textView1.setTag(imgpath);
}
else {
Log.v("In images else", "askfk");
try{
pathOne = msg.getMessage().substring(0, msg.getMessage().indexOf("::images::"));
}
catch(Exception ex){
pathOne = msg.getMessage().substring(0, msg.getMessage().indexOf("::doodle::"));
}
textView1.setVisibility(View.GONE);
Bitmap bitmap=setImage(pathOne);
img.setImageBitmap(bitmap);
textView1.setTag("");
}
}
}
return oldview;
}
#Override
public ChatMessage getItem(int position)
{
return messages.get(position);
}
}
public String setdefaultImage(String msg){
Bitmap bImage = BitmapFactory.decodeResource(ChatScreen.this.getResources(), R.drawable.dummyimage);
img.setImageBitmap(bImage);
String urlpath="";
try{
urlpath = msg.substring(0, msg.indexOf("::images::"));
}
catch(Exception ex){
urlpath = msg.substring(0, msg.indexOf("::doodle::"));
}
//Log.v("","msg getting:..."+urlpath);
String pt[]=urlpath.split("PrefixEnd");
//System.out.println("path :"+pt[1]);
return pt[1];
}
public Bitmap setImage(String pathOne){
Bitmap bitmap=null;
File imgFile = new File(pathOne);
//Log.v("","msg image path:..."+pathOne);
if(imgFile.exists())
{
//Log.v("","msg path exits:...");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap= BitmapFactory.decodeFile(pathOne, options);
}
else{
}
return bitmap;
}
}
Try to tag the data model/ data source with your list view view.setTag(dataModel) in getView method of your adapter class.
Why not try RecyclerView instead of ListView and use Fresco Image Library?

ListView sometimes does not react on tap on an element

I have a ListView in an activity. The list elements are generated from a BaseAdapter. The list is continously growing as the user scrolls down on the screen. Actually an AsyncTask is responsibe to download data from the internet and generate the View elements for the ListView.
Each View element has a set onClickListener. The OnClickListener class starts a new activity...
The problem is that sometimes the GUI does not react on the click action.
e.g.
1. start the app
2. tap on the first element -> nothing happens
3. tap on the 2nd element -> nothing happens
4. scroll down a but -> both corresponding activities appear (on each other)
ListAdapter:
private class HirdetesListaAdapter extends BaseAdapter {
private GSResult hirdetesek;
private final Context context;
private LayoutInflater inflater = null;
private SparseArray<ImageDownloaderThread> imageDownloadThreads;
private ListViewWorker worker;
private int thresHold = 45;
private ArrayList<View> views;
private boolean isWorkerThreadRunning = false;
public HirdetesListaAdapter(final Context context, GSResult result) throws IOException {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initAdapter(result);
}
public void initAdapter(GSResult result) {
if (views == null) {
views = new ArrayList<View>();
} else {
views.clear();
}
hirdetesek = result;
imageDownloadThreads = new SparseArray<ImageDownloaderThread>();
worker = new ListViewWorker();
worker.execute(null, null, null);
}
#Override
public int getCount() {
// Log.v("bar2", "HirdetesListaAdapter.getCount()=" + views.size());
return views.size();
}
#Override
public GSHirdetes getItem(int arg0) {
Log.v("bar", "HirdetesListaAdapter.getItem(" + arg0 + ")");
// Toast.makeText(getBaseContext(), "Találatok: " + gsr.size(),
// 100000).show();
return hirdetesek.get(arg0);
}
public void destroy() {
synchronized (worker) {
worker.notify();
Log.v("thread", "Working thread notified");
worker.cancel(true);
Log.v("thread", "Working thread cancelled");
for (int i = 0; i < this.imageDownloadThreads.size(); i++) {
imageDownloadThreads.get(i).cancel(false);
Log.v("thread", "ImageDownloadThread " + i + " cancelled");
}
}
}
#Override
public long getItemId(int arg0) {
Log.v("bar", "HirdetesListaAdapter.getItemId(" + arg0 + ")");
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if ((lv.getLastVisiblePosition() + thresHold) > views.size()) {
synchronized (worker) {
if (!this.isWorkerThreadRunning) {
Log.v("wthread", "Resuming worker thread");
worker.notify();
isWorkerThreadRunning = true;
}
}
}
synchronized (imageDownloadThreads) {
if (imageDownloadThreads.get(position) == null) {
Log.v("ithread", "Storing download thread: " + position);
ImageDownloaderThread thread = new ImageDownloaderThread();
imageDownloadThreads.put(position, thread);
thread.execute(position);
}
}
Log.v("thread", "getview finished for " + position);
return views.get(position);
}
private class ListViewWorker extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Log.v("thread", "ListViewWorker started");
int buffer = 20;
int i = 0;
try {
while ((views.size() != gsr.size()) && !this.isCancelled()) {
Log.v("thread", views.size() + "/" + gsr.size());
if (buffer != 0) {
views.add(i, makeView(i));
ResultActivity.this.runOnUiThread(new Runnable() {
public void run() {
lv.addFooterView(views.get(views.size() - 1));
}
});
i++;
buffer--;
} else {
synchronized (this) {
try {
Log.v("wthread", "Pausing worker thread");
buffer = 20;
this.wait();
HirdetesListaAdapter.this.isWorkerThreadRunning = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private View makeView(int position) {
Log.v("thread", "ListViewWorker.makeView(" + position + ")");
GSHirdetes hirdetes = hirdetesek.get(position);
View hirdetesView = inflater.inflate(R.layout.hirdetes_listaelem, null);
TextView hirdetesName = (TextView) hirdetesView.findViewById(R.id.hirdetesListaElemView_TextView_Name);
TextView hirdetesAr = (TextView) hirdetesView.findViewById(R.id.hirdetesListaElemView_TextView_Ar);
TextView hirdetesKategoria = (TextView) hirdetesView.findViewById(R.id.hirdetesListaElemView_TextView_Kategoria);
hirdetesName.setText(position + ". " + hirdetes.getHirdetesName());
// hirdetesName.setText(Integer.toString(position));
hirdetesAr.setText(hirdetes.getHirdetesPrice());
hirdetesKategoria.setText(hirdetes.getCategory());
ImageView hirdetesImage = (ImageView) hirdetesView.findViewById(R.id.hirdetesListaElemView_ImageView_HirdetesCover);
//hirdetesImage.setOnClickListener(new HirdetesImageListener(context, hirdetes));
//hirdetesView.setOnClickListener(new HirdetesListaListener(context, hirdetes));
//views.add(position, hirdetesView);
Log.v("gui", "ListViewWorker.makeView(" + position + ") finished");
return hirdetesView;
}
}
private class ImageDownloaderThread extends AsyncTask<Integer, Integer, Bitmap> {
private ProgressBar progressBar;
private TextView percent;
private URL imageUrl;
private View view;
private int sorszám = -1;
public void onPreExecute() {
super.onPreExecute();
// while (threadCounter >= threadPool) {
// try {
// Log.v("konti","threadCounter:"+threadCounter+" threadPool:"+threadPool);
// Thread.sleep(10);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
//
// threadCounter++;
}
public void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
float percentValue = (float) progressBar.getProgress() / progressBar.getMax();
DecimalFormat df = new DecimalFormat("#");
String percentString = df.format(percentValue * 100) + "%";
percent.setText(percentString);
// Log.v("konti", percentString);
}
#Override
protected Bitmap doInBackground(Integer... params) {
sorszám = params[0];
imageUrl = hirdetesek.get(sorszám).gethirdetesCoverImageUrl();
view = views.get(sorszám);
progressBar = (ProgressBar) view.findViewById(R.id.hirdetesListaElemView_ProgressBar_ImageDLProgressBar);
progressBar.setIndeterminate(false);
progressBar.setProgress(0);
percent = (TextView) view.findViewById(R.id.hirdetesListaElemView_TextView_ImageDLPercent);
if (imageUrl == null) {
return null;
}
Log.v("thread", "Starting ImageDownloaderThread for " + sorszám);
int size;
try {
size = imageUrl.openConnection().getContentLength();
progressBar.setMax(size);
InputStream is = imageUrl.openStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int read = 0;
Log.v("gui", "Downloading image for " + sorszám + ": " + imageUrl.getPath());
while ((read = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, read);
// Log.v("net", "Image download progress: " +
// baos.size());
publishProgress(progressBar.getProgress() + read);
}
baos.flush();
byte[] data = baos.toByteArray();
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (IOException e) {
Log.v("exception", "thread");
return null;
}
}
protected void onPostExecute(Bitmap bitmap) {
ResultActivity.this.runOnUiThread(new Runnable() {
public void run() {
ViewGroup vg = (ViewGroup) (progressBar.getParent());
vg.removeView(progressBar);
vg.removeView(percent);
}
});
ImageView im = (ImageView) view.findViewById(R.id.hirdetesListaElemView_ImageView_HirdetesCover);
if (bitmap == null) {
im.setImageResource(R.drawable.noimage_hu);
} else {
im.setImageBitmap(bitmap);
}
}
}
}
Listener:
public class HirdetesListaListener implements View.OnClickListener {
GSHirdetes hirdetes;
Context context;
public HirdetesListaListener(Context context, GSHirdetes hirdetes){
this.hirdetes = hirdetes;
this.context = context;
Log.v("konti","Listener: "+hirdetes.getHirdetesName());
}
#Override
public void onClick(View v) {
Log.v("konti","HirdetesListaListener.onClick(v) "+hirdetes.getHirdetesName());
Intent intent = new Intent(context, HirdetesActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("data", hirdetes);
context.startActivity(intent);
}
}
you should use this code:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "item at pos "+arg2+" clicked", Toast.LENGTH_LONG).show();
}
});

How to add list view row on the top if list view has dynamic data getting from server in android [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have a custom list view that is getting data from server and changing its content after each 3 seconds.this list view i am using for showing the visitor list who are visiting the site.Each row of list contains ipaddress,statustext,duration time,noofvisit and button text and data is updating and changing in list this part is working fine.For showing this list i am writing custom adapter for this.
Actually i have an issue i have to show the row on the top if status text is chat request.How can i do this?can anyone help me?
Actually i am using tabhost after login screen tabhost contains four tabs.First used for monitoring window that show list of visitor and other are chat window,operatorlist and controls.
As i define above if i got status chat request then that row should appear on the top and will contains two button Accept and deny and on accept button click a window will open for chat and deny will use for refusing chat.
Can anyone help me for solving this issue?
my code is following
public class BaseActivity extends Activity {
private ListView list =null;
private NotificationManager mNotificationManager;
private final int NOTIFICATION_ID = 1010;
public static Timer timer = new Timer();
private String response;
protected Dialog m_ProgressDialog;
String[] operatorList,operatorDetail,operatordetail,tempoperatordata;
String[] noofvisitors,opt;
private static final String DEB_TAG = "Error Message";
public static ArrayList<String> SessionText,IPText,DurationText,StatusText;
private ArrayList<String> NoOfVisit,ButtonText;
private int sizeoflist;
private String IP;
Context context;
private CustomAdapter adapter;
public static String from,sessionid,id,text,iptext,status,temo;
private int position,noofchat;
private boolean IsSoundEnable,IsChatOnly;
private Button logout;
NotificationManager notificationManager;
final HashMap<String, String> postParameters = new HashMap<String, String>();
private String url;
private Handler handler;
public void TimerMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.
//We call the method that will work with the UI
//through the runOnUiThread method.
this.runOnUiThread(Timer_Tick);
}
private Runnable Timer_Tick = new Runnable() {
public void run() {
//This method runs in the same thread as the UI.
try{
getVisitorDetailFromServer();
}catch(Exception e){
e.printStackTrace();
}
try {
Log.i("UPDATE", "Handler called");
list.invalidateViews();
playSound3();
} catch(Exception e) {
Log.e("UPDATE ERROR", "error");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.visitor);
list = (ListView) findViewById(R.id.list01);
logout = (Button) findViewById(R.id.btnlogout);
//list.addView("chat request", 0);
//-----------------Making the object of arrayList----------------
SessionText = new ArrayList<String>();
IPText = new ArrayList<String>();
DurationText = new ArrayList<String>();
StatusText = new ArrayList<String>();
NoOfVisit = new ArrayList<String>();
ButtonText = new ArrayList<String>();
Bundle extras = getIntent().getExtras();
if (extras != null) {
IsSoundEnable = Controls.IsSoundEnable;
IsChatOnly = Controls.IsChatOnly;
IsSoundEnable = extras.getBoolean("IsSoundOnly", Controls.IsSoundEnable);
IsChatOnly= extras.getBoolean("IsCOnlyhat", Controls.IsChatOnly);
extras.getString("From");
position=extras.getInt("Position");
}
}
#Override
protected void onStart() {
super.onStart();
//------------Getting the visitor detail-------------------------
try{
getVisitorDetailFromServer();
}catch(Exception e){
e.printStackTrace();
}
timer.schedule(new TimerTask() {
public void run() {
TimerMethod();
}
}, 0, 7000);
//---------------When user click on logout button-----------------------------------
logout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try{
logoutFromServer();
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
private void playSound3() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitors);
mp.start();
}
//----------------------------Getting the detail from server of monitoring window-------------------------
private void getVisitorDetailFromServer() {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_AllOnline;
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("nvar","Y");
postParameters.put("conly", "N");
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
//System.out.println("Output of httpResponse:"+response);
String result = response;
result = response;
String delimiter1 = "<ln>";
String delimiter2 = "<blk>";
String[] temp = result.split(delimiter2);
operatorDetail = result.split(delimiter1);
if(temp.length==7){
String visitorString = temp[0];
String strSound = temp[3];
String strCSRmsgOrChatTrans = temp[4];
String stroperator = temp[5];
String strvisitor = temp[1];
visitorString = visitorString.trim();
if(!(visitorString.equals(""))||(visitorString.equalsIgnoreCase("No Visitors online")||(visitorString.equalsIgnoreCase("No Users Online")))){
operatorDetail = result.split(delimiter1);
//sizeoflist =operatorDetail.length;
}
else{
sizeoflist = 0;
}
}
else{
sizeoflist = operatorDetail.length;
}
//System.out.println("operatordetail length"+operatorDetail.length);
System.out.println("firstresponse================"+operatorDetail[0]);
if(operatorDetail[0].equalsIgnoreCase("logout")){
sizeoflist = 0;
System.exit(0);
finish();
}
if(temp[0].equalsIgnoreCase("No Users Online")){
if(temp[1].equalsIgnoreCase("0")){
sizeoflist =0;
}
else if(temp[1].length()>0){
sizeoflist = 0;
}
else if(temp[0].equalsIgnoreCase("")){
sizeoflist = 0;
}
sizeoflist =0;
}
else{
sizeoflist =operatorDetail.length;
}
//operatorDetail = result.split(delimiter1);
//--------Getting the size of the list---------------------
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
//playsound3();
noofchat =0;
list.setAdapter(new CustomAdapter(BaseActivity.this));
list.getDrawingCache(false);
list.invalidateViews();
list.setCacheColorHint(Color.TRANSPARENT);
list.requestFocus(0);
list.setFastScrollEnabled(true);
//list.setSelected(true);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String item = ((TextView)view).getText().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_LONG).show();
}
});
}
});
}
else {
//ShowAlert();
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//--------------------When internet connection is failed show alert
private void ShowAlert() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final AlertDialog alert = builder.create();
alert.setTitle("Live2Support");
alert.setMessage("Internet Connection failed");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//startActivity(new Intent(CreateAccount.this,CreateAccount.class));
alert.dismiss();
}
});
alert.show();
}
//------------------------Getting the notification of no.of visitor on the site---------------------------
private void triggerNotification() {
// TODO Auto-generated method stub
CharSequence title = "No Of visitors";
CharSequence message = "New visit";
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, noofvisitors[0], System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(this, L2STest.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(BaseActivity.this, title, noofvisitors[0], pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
playsound4();
}
public void completed() {
//remove the notification from the status bar
mNotificationManager.cancel(NOTIFICATION_ID);
}
private void playsound4() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitsound);
mp.start();
}
//-----------------Logout from server--------------------
private void logoutFromServer() {
// TODO Auto-generated method stub
final String url ="http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_LOGOUT;
final HashMap<String, String> postParameters = new HashMap<String, String>();
try{
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("sid",Main.siteId.getText().toString());
}catch(Exception e){
e.printStackTrace();
}
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
// notificationManager.cancelAll();]
System.out.println(response);
showAlert1();
//getSharedPreferences(Main.PREFS_NAME,MODE_PRIVATE).edit().clear().commit();
Log.e(DEB_TAG, response);
//System.exit(0);
Intent intent = new Intent(BaseActivity.this,Main.class);
startActivity(intent);
//closeHandler();
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//----------------------Logout alert when user click on logout button------------------
private void showAlert1() {
// TODO Auto-generated method stub
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
CharSequence text = "You have Successfully logout.";
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 200, 200);
toast.show();
}
//-------------------Play sound3 when any new user visit----------------
private void playsound3() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.newvisitors);
mp.start();
}
//------------------The adapter class------------------------------
private class CustomAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public CustomAdapter(Context context) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.notifyDataSetChanged();
SessionText.clear();
IPText.clear();
DurationText.clear();
StatusText.clear();
NoOfVisit.clear();
ButtonText.clear();
}
public int getCount() {
return sizeoflist;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/* (non-Javadoc)
* #see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
*/
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row1, null);
holder = new ViewHolder();
holder.IP = (TextView) convertView.findViewById(R.id.ip);
holder.duration = (TextView) convertView.findViewById(R.id.duration);
holder.status =(TextView) convertView.findViewById(R.id.status);
holder.noOfVisit = (TextView) convertView.findViewById(R.id.NoOfvisit);
holder.invite =(Button)convertView.findViewById(R.id.btnjoin);
holder.deny = (Button) convertView.findViewById(R.id.btndeny);
//holder.accept = (Button) convertView.findViewById(R.id.btnaccept);
holder.deny.setVisibility(View.INVISIBLE);
holder.invite.setId(position);
holder.invite.setTag(position);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
String result = response;
String delimiter = "<fld>";
String delimiter1 = "<ln>";
for(int i=0;i<operatorDetail.length;i++){
if(operatorDetail!=null){
//System.out.println("Operator res=============="+operatorDetail[i]);
operatorList = operatorDetail[i].split(delimiter);
try{
if(operatorList[0]!=null){
SessionText.add(operatorList[0]);
sessionid = operatorList[0];
}
else{
onStart();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[1]!=null){
IPText.add(operatorList[1]);
iptext = operatorList[1];
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[4]!=null){
DurationText.add(operatorList[4]);
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[3]!=null){
StatusText.add(operatorList[3]);
status = operatorList[3];
}
else{
System.out.println("Oplst is null");
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(operatorList[2]!=null){
NoOfVisit.add(operatorList[2]);
}
else{
System.out.println("Oplst is null");
}
}catch(Exception e){
e.printStackTrace();
}
//ButtonText.add(operatorList[6]);
try{
if(IPText!=null){
holder.IP.setText(IPText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(DurationText!=null){
holder.duration.setText(DurationText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(StatusText!=null){
holder.status.setText(StatusText.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(NoOfVisit!=null){
holder.noOfVisit.setText(NoOfVisit.get(position));
}
}
catch(Exception e){
e.printStackTrace();
}
//----------------If status is chat request then check for this-----------------
try{
if(StatusText.get(position).equalsIgnoreCase("chat request")){
//playsound();
playsound();
holder.deny.setVisibility(View.VISIBLE);
holder.invite.setText("Accept");
holder.deny.setText("Deny");
convertView.bringToFront();
convertView.setFocusableInTouchMode(true);
convertView.setSelected(true);
//convertView.setFocusable(true);
convertView.requestFocus();
convertView.clearFocus();
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
holder.invite.setText("Join");
holder.deny.setVisibility(View.INVISIBLE);
try{
chatRequest(IPText.get(position), SessionText.get(position));
}
catch(Exception e){
e.printStackTrace();
}
Intent i = new Intent(BaseActivity.this,Chat1.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
try{
i.putExtra("SessionText",SessionText.get(position));
i.putExtra("IPTEXT",IPText.get(position));
i.putExtra("StatusText",StatusText.get(position));
}
catch(Exception e){
e.printStackTrace();
}
startActivity(i);
}
});
}
else{
holder.invite.setText("Invite");
holder.deny.setVisibility(View.INVISIBLE);
//---------------------When user click on invite Button---------------------
holder.invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
timer.purge();
try{
if(SessionText!=null){
callToServer(SessionText.get(position));
}
else{
System.out.println("null");
}
}
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
catch(Exception e){
e.printStackTrace();
}
//-----------------------------When user click on deny button------------------------
holder.deny.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
timer.purge();
try{
if(SessionText.get(position)!=null){
refuseToServer(SessionText.get(position));
holder.deny.setVisibility(View.INVISIBLE);
}
else{
System.out.println("null");
}
}catch(Exception e){
e.printStackTrace();
}
}
});
//-----------When user click on the listiview row-----------------------
convertView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
timer.purge();
if(SessionText!=null&&IPText!=null){
try{
Intent i=new Intent(BaseActivity.this,VisitorDetail.class);
i.putExtra("ID", id);
i.putExtra("Position",position);
i.putExtra("From", from);
i.putExtra("SessionText", sessionid);
i.putExtra("IPTEXT",iptext);
startActivity(i);
}catch(Exception e){
e.printStackTrace();
}
}
else{
timer.schedule(new TimerTask() {
public void run() {
TimerMethod();
}
}, 0, 5000);
}
}});
}
}
operatorDetail=null;
operatorList=null;
operatorDetail = result.split(delimiter1);
return convertView;
}
class ViewHolder {
TextView IP;
TextView duration;
Button deny;
TextView status;
TextView noOfVisit;
Button invite;
Button accept;
}
}
//------------------Play sound when user click on invite button-------------------------
private void playSound2() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.invite);
mp.start();
}
//---------------When any chat request come-----------------
private void playsound() {
// TODO Auto-generated method stub
MediaPlayer mp = MediaPlayer.create(this, R.raw.chatinvitation);
mp.start();
}
//------------When user click on deny button---------------------
private void refuseToServer(String sessionid) {
// TODO Auto-generated method stub
//final String url = "http://sa.live2support.com/cpn/wz-action.php?";
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ACTION;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("action","refuse");
postParameters.put("csesid", sessionid);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Deny Chat response:"+response);
System.out.println("Deny chat Success"+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
System.out.println("response================="+IP);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//---------------------When user click on invite button-----------------------
private void callToServer(String session) {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ACTION;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("action","cinvt");
postParameters.put("csesid", session);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
IP = response;
System.out.println("the resultant ip ===================="+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playSound2();
System.out.println("response================="+IP);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
//------------------Show invitation alert----------------------
private void showAlert(String ip) {
// TODO Auto-generated method stub
int duration = Toast.LENGTH_SHORT;
Context context = getApplicationContext();
CharSequence text = "Invitation sent to "+ip;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 50, 50);
toast.show();
}
//-----------------When in response we get the chat request--------------------------
private void chatRequest(String iptext, String sessionid) {
// TODO Auto-generated method stub
url = "http://"+Main.tempurl+"/"+Main.url1+"/"+Url.IDS_ONCHATREQUEST;
final HashMap<String, String> postParameters = new HashMap<String, String>();
postParameters.put("csesid", sessionid);
postParameters.put("ipaddr", iptext);
postParameters.put("sid",Main.siteId.getText().toString());
postParameters.put("adminid",Main.loginId.getText().toString());
postParameters.put("join", "Y");
Runnable searchThread = new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost1(url,postParameters);
Log.i(DEB_TAG, "Requesting to server"+response);
//CustomHttpClient.getResponseInString(response );
System.out.println("Output of httpResponse:"+response);
IP = response;
System.out.println("the resultant ip ===================="+IP);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(response!=null){
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
playSound2();
System.out.println("response================="+response);
showAlert(IP);
}
});
}
}
};
Thread thread = new Thread(null, searchThread, "MagentoBackground");
thread.start();
}
public void onNotifiyDataSetChanged(){
super.notifyAll();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i=new Intent(BaseActivity.this,Main.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
return true;
}
return super.onKeyDown(keyCode, event);
}
}
what can i do for setting the row that has chat request on the top?Can anyone help me?
ArrayList<String> userList = your list of data
// other list also
//userListA
//userListB
ArrayList<String> tempUserList = new ArrayList<String>();
// other list also
//tempuserListA
//tempuserListB
String text = "ChatRequest";
// to add CharRequest at top
for(int i=0;i<userList.size();i++)
{
if(userList.get(i).equals(text))
{
tempUserList.add(userList.get(i));
//tempuserlistA.add(userlistA.get(i));
//tempuserlistB.add(userlistB.get(i));
}
}
// to add other entry
for(int i=0;i<userList.size();i++)
{
if(!userList.get(i).equals(text))
{
tempUserList.add(userList.get(i));
//tempuserlistA.add(userlistA.get(i));
//tempuserlistB.add(userlistB.get(i));
}
}
//now temp list are you original list to use
userList = tempUserList;
//userListA = tempuserlistA;
//userListB = tempuserlistB;
// and then call your adapter with the arraylists
You can use an ArrayList holding your Data for the ListView and add an item at the beginning of the list by: myArrayList.add(0, newItem).
Below an example Adapter which can do this:
public class PlaylistAdapter extends BaseAdapter {
private Context context;
private List<Playlist> entries;
public PlaylistAdapter(Context context, List<Playlist> entries) {
this.context = context;
this.entries = entries;
}
public void add(Playlist item) {
if (entries.contains(item))
return;
entries.add(item);
this.notifyDataSetChanged();
}
public void add(int index, Playlist item) {
if (entries.contains(item))
return;
entries.add(index, item);
this.notifyDataSetChanged();
}
#Override
public int getCount() {
return entries.size();
}
#Override
public Playlist getItem(int arg0) {
return entries.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// inflate the layout you want to use for a single entry row
convertView = inflater.inflate(R.layout.playlists_adapter_entry,
null);
}
// fetches the current item
Playlist playlist = getItem(position);
// fill the entry layout with data
ImageView cover = (ImageView) convertView
.findViewById(R.id.playlist_adapter_entry_cover);
cover.setImageBitmap(playlist.getCover());
TextView title = (TextView) convertView
.findViewById(R.id.playlist_adapter_entry_title);
title.setText(playlist.getTitle());
return convertView;
}
}

Load record at scrolllistview

I need to prevent against lazy load in my custom list-view. so i found that scrollview onscroll listner are helpfull over there i have tryed it but not getting success to implement this functionality.
Code:
lviewAdapter = new ListViewAdapter(SaxParser2.this, Arr_ActivityName, Arr_AudioScript,Arr_RequestID,Arr_FolderPath,Arr_RequestTo);
lview.setOnScrollListener(SaxParser2.this);
#Override
public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
lview.setAdapter(lviewAdapter);
}
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
}
here is my BaseAdapter
package com.RecordingApp;
import it.sauronsoftware.ftp4j.FTPClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Sharedpreferance.GMailSender;
public class ListViewAdapter extends BaseAdapter {
public static Activity context;
String title[];
String description[];
String RequestId[];
String Folderpath[];
String RequestTo[];
boolean b_Flag_Record_or_not = false;
boolean b_upload_or_not = false;
boolean start_or_not = false;
boolean start_play = false;
boolean upload_or_not = false;
boolean b_play_or_not = false;
boolean isplaying2 = false;
Thread welcomeThread,welcomeThread2;
int glob_position;
MediaPlayer mPlayer2;
int flag_stop_position;
AudioRecorder recorder;
AnimationDrawable frameAnimation, frameAnimation_play;
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
Recording login = new Recording();
MediaPlayer MP_completeRequest = new MediaPlayer();
public ListViewAdapter(Activity context, String[] title,
String[] description, String[] req_id, String[] FolderPath,
String[] Arr_RequestTo) {
super();
this.context = context;
this.title = title;
this.description = description;
this.RequestId = req_id;
this.Folderpath = FolderPath;
this.RequestTo = Arr_RequestTo;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
Button record, stop, play, upload;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
glob_position = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView
.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView
.findViewById(R.id.textView2);
holder.record = (Button) convertView.findViewById(R.id.record);
holder.stop = (Button) convertView.findViewById(R.id.stop);
holder.play = (Button) convertView.findViewById(R.id.play1);
holder.upload = (Button) convertView
.findViewById(R.id.audio_upload);
holder.record.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isplaying2 == true) {
} else {
if (b_Flag_Record_or_not == true) {
} else {
try {
holder.record.setBackgroundResource(R.drawable.record_green);
b_Flag_Record_or_not = true;
b_play_or_not = true;
flag_stop_position = position;
AuthHandler dataHandler = new AuthHandler();
AuthDataset dataset = dataHandler
.getParsednewJobdtl_DataSet();
// Login l = new Login();
String str_useid = RequestTo[position];
recorder = new AudioRecorder(
"/audiometer/shanesh"
+ RequestId[position] + "-"
+ str_useid);
start_or_not = true;
recorder.start();
Toast.makeText(context, "Recording Started",
Toast.LENGTH_LONG).show();
CountDownTimer countDowntimer = new CountDownTimer(
120000000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
try {
Toast.makeText(
context,
"Stop recording Automatically ",
Toast.LENGTH_LONG).show();
recorder.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
countDowntimer.start();
} catch (IOException e) {
gotoGmail(e);
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
Typeface face = Typeface.createFromAsset(context.getAssets(),
"fonts/tahoma.ttf");
holder.txtViewTitle.setTypeface(face);
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
holder.stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
if (isplaying2 == true) {
mPlayer2.stop();
isplaying2 = false;
} else {
holder.record.setBackgroundResource(R.drawable.page7_15);
if (flag_stop_position == position) {
b_Flag_Record_or_not = false;
if (start_or_not == true) {
b_play_or_not = false;
recorder.stop();
upload_or_not = true;
start_play = true;
Toast.makeText(context, "Stoped Recording",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context,
" Please Start recording ",
Toast.LENGTH_LONG).show();
}
} else {
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
});
holder.play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String temp = SaxParser2.str_completeORpendingFlag;
if (temp.equalsIgnoreCase("c")) {
try {
final MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(Folderpath[position]);
mPlayer.prepare();
final int welcomeScreenDisplay = mPlayer
.getDuration();
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
isplaying2 = true;
mPlayer.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
isplaying2 = false;
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} catch (Exception e) {
gotoGmail(e);
}
} else if (temp.equalsIgnoreCase("p")) {
try {
if (b_play_or_not == true) {
} else {
String str_useid = RequestTo[position];
java.io.File file = new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/", "shanesh"
+ RequestId[position] + "-" + str_useid
+ ".amr");
if (file.exists()) {
Toast.makeText(context, "Playing",
Toast.LENGTH_LONG).show();
mPlayer2 = new MediaPlayer();
try {
mPlayer2.setDataSource(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[position]
+ "-"
+ str_useid + ".amr");
mPlayer2.prepare();
mPlayer2.start();
isplaying2 = true;
final int welcomeScreenDisplay = mPlayer2
.getDuration();
/**
* create a thread to show splash up to
* splash time
*/
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {mPlayer2.prepare();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
welcomeThread2 = new Thread() {
int wait = 0;
#Override
public void run() {
try {
mPlayer2.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
// frameAnimation_play.stop();
isplaying2 = false;
}
}
};
welcomeThread2.start();
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} else {
Toast.makeText(context, " File Not Found ",
Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
holder.upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
glob_position = position;
// String str_useid = RequestTo[position];
if (upload_or_not == true) {
try {
new xyz().execute();
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
return convertView;
}
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(context);
protected void onPreExecute() {
try {
this.dialog.setMessage("Uploading...Please Wait..");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
this.dialog.show();
// put your code which preload with processDialog
} catch (Exception e) {
gotoGmail(e);
}
}
#Override
protected Void doInBackground(Void... arg0) {
for (int i = 0; i < 100000; i++) {
}
it.sauronsoftware.ftp4j.FTPClient con = new it.sauronsoftware.ftp4j.FTPClient();
try {
String str_useid = RequestTo[glob_position];
con.connect("URL");
con.login("as", "asdasd");
con.changeDirectory("/rangam/RequestContent/audio");
con.setPassive(true);
con.setType(FTPClient.TYPE_BINARY);
con.upload(new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[glob_position] + "-" + str_useid + ".amr"));
String filename = "/shanesh" + RequestId[glob_position] + "-"
+ str_useid + ".amr";
con.logout();
con.disconnect(true);
String MachineName = Machinelist.str_Machinename;
sendFlagToServer(RequestId[glob_position], filename,
MachineName);
} catch (Exception e) {
gotoGmail(e);
}
return null;
}
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
AlertDialog.Builder alertbox = new AlertDialog.Builder(
context);
alertbox.setTitle("Message");
alertbox.setMessage(":: Uploaded Successfully ::");
alertbox.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
Intent intent_request = new Intent(context,
SaxParser2.class);
intent_request.putExtra("value", Machinelist.str_UIDValue);
intent_request.putExtra("machineName",
Machinelist.str_Machinename);
intent_request.putExtra("captureBack_or_not", 2);
context.startActivity(intent_request);
context.finish();
}
});
alertbox.show();
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
private void sendFlagToServer(String requestID, String filename,
String machineName) {
HttpURLConnection connection;
OutputStreamWriter request = null;
String MachineName = Machinelist.str_Machinename;
URL url = null;
String parameters = "RequestID=" + requestID + "&FileName=" + filename
+ "&MachineName=" + MachineName + "&RequestType=A";
try {
url = new URL(
"URL");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
reader.close();
} catch (Exception e) {
gotoGmail(e);
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
try {
context.finish();
} catch (Exception e) {
gotoGmail(e);
}
}
return false;
}
void gotoGmail(Exception e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String s = writer.toString();
}
}
Ok,
So first you'll have to define "what is the number of views I'd need to load in order my user not to see that it's lazy loading ?" :
Let's say, you'd want to load 20 rows...
Now in you onscroll, or wherever you want but somewhere like on scroll or Adapter.getView, you'll have to know what is displayed on screen at the moment... Let me explain :
I want to load 20 rows so my user doesn't notice,
I am display 10 of them
and 10 of them are just hidden (not displayed if the guy doesn't scroll).
Now, I wan't to load 10 more when the guy just hit my 15th row
What could be the best way to do that ???
Humm, let's see, trying to find something that returns the (ABSOLUTE) number of the last row displayed on screen - this could be a nice solution.
An otehr solution could be that your 10 or 15th row is the first one displayed on screen ?
etc, etc...
I think stuffs like that should do the trick. ;)
Here is a sample I grabbed from Net. It is loading the items by listening to the Scroll of the ListView . For sample it is loading dates in ListView. After reached the end position it will load next 15 dates. It is Never Ending List . You can modify the adapter to your custom adapter. The concept is:
You have set of data
Loading first n no of items
Set the scroll listener to the listview
If scroll reaches Last Visible Item in Listview , You trigger the worker thread to load additional m no of items.
Notify listview from an UI thread.
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> myListItems;
ArrayAdapter<String> adapter;
//For test data :-)
Calendar d = Calendar.getInstance();
this.getListView().setOnScrollListener(new OnScrollListener(){
//useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already ? Load more !
if((lastInScreen == totalItemCount) && !(loadingMore)){
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
//Load the first 15 items
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
//Runnable to load the items
private Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
myListItems = new ArrayList<String>();
//Get 15 new listitems
for (int i = 0; i < itemsPerPage; i++) {
//Fill the item with some bogus information
myListItems.add("Date: " + (d.get(Calendar.MONTH)+ 1) + "/" + d.get(Calendar.DATE) + "/" + d.get(Calendar.YEAR) );
// +1 day :-D
d.add(Calendar.DATE, 1);
}
//Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
//Since we cant update our UI from a thread this Runnable takes care of that!
private Runnable returnRes = new Runnable() {
#Override
public void run() {
//Loop thru the new items and add them to the adapter
if(myListItems != null && myListItems.size() > 0){
for(int i=0;i<myListItems.size();i++)
adapter.add(myListItems.get(i));
}
//Update the Application title
setTitle("Neverending List with " + String.valueOf(adapter.getCount()) + " items");
//Tell to the adapter that changes have been made, this will cause the list to refresh
adapter.notifyDataSetChanged();
//Done loading more.
loadingMore = false;
}
};
EDIT:
You can get tutorial and full project here

Categories

Resources