2

Here is my problem:

I need to do several requests on a server. These requests have to be made one after the other in order to avoid mixing. For that, I'm using monitors.

Here is what I've come up so far:

public class TestActivity extends Activity
{
  private String key;
  private HashMap<String, String> values;

  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    values = new HashMap<String, String>();

    ArrayList<String> list = new ArrayList<String>();
    list.add("foo");
    list.add("bar");
    list.add("baz");

    createValues(list);
  }

  private void createValues(final ArrayList<String> list)
  {
    Thread thread = new Thread(new Runnable() {
      @Override
      public void run()
      {
        key = null;
        for (String element : list)
        {
          if (key != null) // Every time except the first time.
          {
            synchronized (key)
            {
              try
              {
                key.wait();
              }
              catch (InterruptedException e)
              {
              }
            }
          }
          key = element;
          DataProcessor dataProcessor = new DataProcessor();
          dataProcessor.execute("Processed " + element);
        }
      }
    });
  }

  private void putDataInValue(String element)
  {
    synchronized (key)
    {
      values.put(key, element);
      key.notify();
    }
  }

  private class DataProcessor extends AsyncTask<String, Void, String>
  {
    @Override
    protected String doInBackground(String... params)
    {
      // Fetching data on a server. This takes time.
      try
      {
        Thread.sleep(10000);
      }
      catch (InterruptedException e)
      {
      }
      return params[0] + " from the server";
    }

    @Override
    protected void onPostExecute(String result)
    {
      putDataInValue(result);
    }
  }
}

What I would like after that is that the content of values is:

[
 "foo" => "Processed foo from the server",
 "bar" => "Processed bar from the server",
 "baz" => "Processed baz from the server"
]

I need to keep the values in the list and know which one corresponds to what content (hence the monitor).

My problem is that I keep getting an error message in my LogCat:

Can't create handler inside thread that has not called Looper.prepare()

I've searched the web, found some people who had that problem, looked at the answers, most of them saying I needed to use Handlers. Handlers don't work either. I tried replacing the thread by

handler = new Handler(Looper.getMainLooper);
handler.post(new Runnable //...
//...

but it simply freezes.

I am ready to admit that my approach is wrong and start again from scratch if you think I'm in a dead end. What would you do ?

SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
  • Short answer to your error message, AsyncTask.execute() must be invoked on the UI thread, check out API [here](http://developer.android.com/reference/android/os/AsyncTask.html). What Android version is your app targeting to run? – yorkw Dec 04 '11 at 20:17
  • I'm using API 8 (android 2.2). As for the UI thread, I tried to use `runOnUiThread()` but my application freezes. – SteeveDroz Dec 05 '11 at 09:53

1 Answers1

0

You have probably already arrived at a solution for this, but in any case, here is one way you can enforce the sequential order of your requests using an Executor:

public class SequentialTaskExampleActivity extends Activity {

    /**
     * will only execute one job at a time, in the order given to it.
     */
    private Executor executor = Executors.newSingleThreadExecutor();
    private Map<String, String> values = new HashMap<String, String>();
    private TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        textView = new TextView(this);
        textView.setTextSize(24);
        setContentView(textView);

        // Initialise jobs and add to queue 
        ArrayList<String> list = new ArrayList<String>();
        list.add("foo");
        list.add("bar");
        list.add("baz");

        for (String key : list) {
            executor.execute(new Job(key));
        }
    }

    public void addToResult(String key, String value) {
        values.put(key, value);

        // display result to UI
        textView.setText(String.format("%s %s => %s\n", textView.getText(), key, value));
    }

    private class Job implements Runnable {
        private String key;

        public Job(String key) {
            this.key = key;
        }

        @Override
        public void run() {
            // simulate work
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // retrieve result
            final String value = key + " from the server";

            // post result back to UI
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    addToResult(key, value);
                }
            });
        }
    }
}

If you are targeting API 11+ you can specify a particular executor to use with your AsyncTask instead (in fact, I think the default new behaviour is serial processing). In any case, you should always create and execute the AsyncTask on the UI thread; this is the only way to ensure AsyncTask.onPostExecute() behaves correctly.

antonyt
  • 21,863
  • 9
  • 71
  • 70