androidiprogressdialog

Android loading listview with progress dialog


this is my code to load listview items

  @SuppressLint("DefaultLocale")
   public class SearchList extends Activity {

  private ArrayList<String> founded = new ArrayList<String>();
  private OrderAdapter m_adapter;


ListView lv;

/** Called when the activity is first created. */
@SuppressLint("DefaultLocale")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.searchlist);
    lv = (ListView) findViewById(R.id.listView1);

    new Load().execute();

    m_adapter = new OrderAdapter(this, R.layout.itemview, founded);

    lv.setAdapter(m_adapter);
    lv.setTextFilterEnabled(true);
    }

  private class Load extends AsyncTask<Void, Void, Void> {

    ProgressDialog progress;

    @Override
    protected void onPreExecute() {
        progress = new ProgressDialog(SearchList.this);
        progress.setMessage("loading....");
        progress.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
             try {

            for (int i = 0; i <500000; i++) {
             founded.add("String "+i);
               }

        } catch (Exception e) {

        }
            return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        // write display tracks logic here
        progress.dismiss(); // dismiss dialog
    }
}

when i run the code the progress dialog already appear but after its dismiss i found that the list is empty no items added to it i do not know what is the problem and why the list is empty after the dialog loading .Pls need help thanks in advance.


Solution

  • Set listadapter in onPostExecute Because you Are using AsyncTask to get adapter data and setting ListAdapter before Completing AsyncTask So Try to Set ListAdapter after Completing AsyncTask
    So add these

     m_adapter = new OrderAdapter(this, R.layout.itemview, founded);
    lv.setAdapter(m_adapter);
    lv.setTextFilterEnabled(true);
    

    lines in onPostExecute method instead of onCreate Method

     @Override
        protected void onPostExecute(Void result) {
    
            // write display tracks logic here
            progress.dismiss(); // dismiss dialog
         m_adapter = new OrderAdapter(YourActivity.this, R.layout.itemview, founded);
         lv.setAdapter(m_adapter);
         lv.setTextFilterEnabled(true);
        }