Question

I'm relatively new in Android's world and the UI/Thread model is still confusing.

Here is what I am trying to do:

Load data from the web Handle them Show them Show an AlertDialog if there is a problem

I'm currently doing like this, but I'm not sure that using many thread like that is the best way to do it.

Inside the onCreate()

  final ProgressDialog pd = ProgressDialog.show(this, "", loadingText, true);
  final AlertDialog.Builder b = new AlertDialog.Builder(this);

  new Thread(new Runnable() {

   @Override
   public void run() {
    try {
     loadResorts();
    } catch (ResortsRetrievalException e) {
     runOnUiThread(new Runnable() {
      @Override
      public void run() {
       b.setMessage(R.string.resorts_retrieval_error)
       .show();
      }
     });
    }
    pd.dismiss();
   }
  }).start();

And my loadResorts method finishes with

  final BaseAdapter a = new ResortAdapter(this, R.layout.resort_item, resorts);

  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    resortsList.setAdapter(a);
   }
  });

I have one Thread and two calls of runOnUiThread for that. I feel that there could be a better solution without having to deal with these threads. Am I right?

Thanks

Was it helpful?

Solution

Use AsyncTask - it was created for this kind of scenarios: running a background task or (long) process, while still updating the UI in correct way (on EDT).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top