Search code examples
javaandroidandroid-listviewandroid-asynctasklistadapter

How could I change ListView in the AsyncTask?


I have some AsyncTask class that executing from service:

public class DownloadTask extends AsyncTask<Void, Integer, Boolean {

    @Override
    protected Boolean doInBackground(Void... arg0) {
        // do something
        publishProgress(i);
    }

    @Override
    protected void onProgressUpdate(Integer ... progress) {
        if(textView()!=null) getTextView().setText(i + "%");
    }

    public void setTextView(TextView textView) {
        this.textView = textView;
    }

}

And ListAdapter, in method getView() I'm setting TextView in AsyncTask using method setTextView() of AsyncTask:

public class DownloadTasksAdapter extends BaseAdapter {
    private final Activity context;
    private DownloadTask[] downloadTasks;

    public DownloadTasksAdapter(Activity context, DownloadTask[] downloadTasks) {
        this.context = context;
        this.downloadTasks = downloadTasks;
    }

    public int getCount() {
        return downloadTasks.length;
    }

    public DownloadTask getItem(int position) {
        return downloadTasks[position];
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {       
        LayoutInflater inflater = (LayoutInflater) context.getLayoutInflater();
        final View rowView = inflater.inflate(R.layout.downloads_listview_row, parent, false);


        final TextView progressTxt = (TextView) rowView.findViewById(R.id.downloads_listview_row_progress);


        switch (downloadTasks[position].getStatus()) {
        case RUNNING:
            downloadTasks[position].setTextView(progressTxt);

            break;
        }

        return rowView;
    }
}

AsyncTask executing from service, but when I'm opening Activity that contains ListView, AsyncTask should update some field, how could I do this? :(


Solution

  • after completing task call

    mAdapter.notifyDataSetChanged();