Issue
Note: I'm not doing great with terminology as it's my first go on object-oriented programming and android studio.
In the android studio, I have created a class for a JSON fetching task. (I don't include the do in background override).
public class jsonTasks extends AsyncTask<String, String, String> {
public interface AsyncResponse {
void processFinish(String output);
}
private AsyncResponse delegate = null;
jsonTasks(AsyncResponse delegate){
this.delegate = delegate;
}
@Override
protected void onPostExecute(String result) {
delegate.processFinish(result);
}
In my activity now:
public class activity extends Activity {
// in here I've declared the string variable
String valuableInfo;
// FIRST TASK
jsonTasks asyncTask = new jsonTasks(new jsonTasks.AsyncResponse() {
@Override
public void processFinish(String output) {
String TAG = activity.class.getSimpleName();
JSONObject info;
//i do stuff with the json here
//i set the textboxes normally
txtSumName.setText(sumInfo.getString("name"));
//but setting the string valuableInfo is not working
valuableInfo = "info I took from json operation"
});
// and here I execute
asyncTask.execute("url");
// SECOND TASK
jsonTasks asyncTask2 = new .... {
.................
}
asyncTask2.execute("https://example.com/" + valuableInfo);
}
Where I want to use that variable is in another "asyncTask2" that with use the valuableInfo on the URL to continue fetching.
The variable is always null when I run the second "asyncTask2".
Solution
An AsyncTask performs operations asynchronously. This means that you won't get the result immediately, you have to wait until it finished before you can use valueableInfo
. There is a method which you can override, it's called onPostExecute
. This will trigger after your task is done and when the info is available. Execute your second task here and it won't be null at that point.
You could alternatively also merge the two tasks perhaps?
Answered By - Tim Kranen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.