Home Can't set activity's variable from class method
Reply: 1

Can't set activity's variable from class method

quelotic Published in 2017-12-04 16:20:06Z

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;

protected void onPostExecute(String result) {

In my activity now:

public class activity extends Activity {
    // in here I've declared the string variable
    String valuableInfo;

    jsonTasks asyncTask = new jsonTasks(new jsonTasks.AsyncResponse() {

        public void processFinish(String output) {
            String TAG = activity.class.getSimpleName();
            JSONObject info;

            //i do stuff with the json here
            //i set the textboxes normally

            //but setting the string valuableInfo is not working
            valuableInfo = "info I took from json operation"

    // and here I execute

    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".

Tim Kranen
Tim Kranen Reply to 2017-12-04 16:23:46Z

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?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301747 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO