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 ?