Reputation: 37
i've a little problem with my code. I'm trying to perform a volley request on doInBackground behaviour and then to use its result to set some layout elements. Here's the async snippet:
private class MyAsyncTask extends AsyncTask<String, Void, Message>
{
@Override
protected Message doInBackground(String... params) {
rm = new RequestManager(MessageDisplay.this);
idM = params[0];
retrieveMessage(new VolleyCallbackOp(){
public void onSuccess(List<Message> ml) {
m = ml.get(0);
Log.d("print1", m.getContent()); <---- this is fine
}
});
Log.d("print2", m.getContent()); <---- m always null
return m;
}
@Override
protected void onPostExecute(Message m) {
super.onPostExecute(m);
Log.d("messaggio", m.getContent());
mds = new MessageDisplaySetter(MessageDisplay.this);
View v = mds.setMessageDisplayInfo(m, 3);
contentD.addView(v);
}
}
});
}
this code is called in activity onCreate():
Message m = new Message();
String target2 = i.getExtras().getString("messageId");
new MyAsyncTask().execute(target2);
The problem is that the Log "print2" tell the variable m is null while "print1" is ok. Have you any tip to pass the result of this request to the related onPostExecute()?
Upvotes: 0
Views: 198
Reputation: 37594
The reason why your log for print2
is null - is because you are in a race condition. By calling new VolleyCallbackOp
you are doing an asynchrounous network call which might take a while to complete. Your code does not wait until it's finished. That's why print2
is null most of the time.
There are several solutions for your case. One of them is to use the callback mechanism of onSuccess
and do your logic there.
Upvotes: 2