Reputation: 2053
I have my Main Activity and in that Activity I have a private AsyncTask class. In my public AsyncTask class, there is a String I will need access that my MainActivity after my AsyncTask has finished.
How would I be able to access the String in my Async Task class from my Main Activity?
EDIT: I'm calling AsyncTask in the OnCreate of my Activity
Async Task class(Near bottom is the String I need):
public class getLikes extends AsyncTask<String, String, String> {
JSONObject obj = null;
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
String jsonUser = fb.request("5027904559");
obj = Util.parseJson(jsonUser);
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
//I need to use this String elsewhere in my MainActivity
String name = obj.optString("likes");
}
}
Here is where I need to use the string(if it matters)
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1), true, names));
Upvotes: 0
Views: 457
Reputation: 145
Just make a constructor where you hand in an Observer like this one:
interface TaskCompletionObserver {
taskCompleted(Object result)
}
The constructor would look like this:
public GetLikes(TaskCompletionObserver observer){
super();
this.mObserver = observer;
}
Then in the onPosteExecute simply call:
mObserver.taskCompleted(whatever_you_want_to_pass);
Your activity should then implement TaskCompletionObserver and in the implementation of taskCompleted you can do what you need to do (e.g. update the UI)
You could then lateron extend your implementation to a fully fedged observer patter
It's good design and keeps your code maintainable and flexible.
Upvotes: 2