0

I need to access an Object from AsyncTask. Here's the code of the AsyncTask:

private class DownloadTask extends AsyncTask<String, Void, String>{

    // Downloading data in non-ui thread
    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try{
            // Fetching the data from web service
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    // Executes in UI thread, after the execution of
    // doInBackground()
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);
    }
}

I want to access data. I have no idea how can I do it.

WWJD
  • 1,104
  • 4
  • 12
  • 31

2 Answers2

1

One alternative approch is that you declare data variable with private static modifier and create a public static get Method. From the second activity can directly access that public static method.

private class FirstAcitivity extends Activity
{
    private static String data = "";

    private class DownloadTask extends AsyncTask<String, Void, String>{

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {

            // For storing data from web service
            //String data = "";                                                    // Comment this line 

            try{
                // Fetching the data from web service
                data = downloadUrl(url[0]);
            }catch(Exception e){
                Log.d("Background Task",e.toString());
            }
            return data;
        }

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            ParserTask parserTask = new ParserTask();

            // Invokes the thread for parsing the JSON data
            parserTask.execute(result);
        }
    }

    public static String getData()
    {
        return data;
    }
}

Now access in Second Activity

public class SecondActivity extends Activity 
{ 
    String data = FirstActivity.getData();

}
user3301551
  • 350
  • 1
  • 14
1

You can also access it by declaring the variable as following:

 public static String data="";

Then you can access it in other Activity as:

 ClassName.data

where ClassName will be the name of class where you defined the variable.

pratiti-systematix
  • 792
  • 11
  • 28
  • While this is true answer but you shouldn't use public variable instead you should use private variable with public method, like I did. – user3301551 Feb 14 '14 at 11:03