简体   繁体   中英

Calling another activity from AsyncTask

I'm new to android and I have a problem with this code. I'm trying to get a JSON String and start another activity to display it as a ListView.
I'm not able to start the activity. It says that the The constructor Intent(RequestJsonString, Class) is undefined and The constructor Intent(RequestJsonString, Class) is undefined .

Here: Intent intent = new Intent(RequestJsonString.this,DisplayResults.class); and Here: RequestJsonString.this.startActivity(intent);

I have read many posts on this on stackoverflow and tried with activity , context and this . But still I'm not getting it right. I think I should be missing something. Any help is appreciated.

public class RequestJsonString extends AsyncTask<String, Void, JSONObject> {

@Override
protected JSONObject doInBackground(String... urls) {
    // Code HTTP Get Request and get JSONObject
            return jsonObject;
}

protected void onPostExecute(JSONObject jsonObj){
    try {

        Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);
        intent.putExtra("JSON_Object", jsonObj.toString());
        RequestJsonString.this.startActivity(intent);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Log.v("Json_OutPut","Done");

}

}

To start the activity from AsyncTask.

Intent intent = new Intent(YourActivityName.this,DisplayResults.class);

or you can do same like below.

Declare the context instance variable and initialize it in onCreate method.

private Context context;
public void onCreate(Bundle bundle) {
   ............
   context = this;
   ........
}

Start the activity like this.

Intent intent = new Intent(context,DisplayResults.class);
intent.putExtra("JSON_Object", jsonObj.toString());
startActivity(intent);

In your case you are referring to asynctask class context

Intent intent = new Intent(RequestJsonString.this,DisplayResults.class);

Use a Activity Context

Intent intent = new Intent(ActivityName.this,DisplayResults.class);

Check the link to know when to use getApplicationContext() and when to use Activity Context

When to call activity context OR application context?

Edit:

Pass the Activity context to the asynctask constructor

 new RequestJsonString(ActivityName.this).execute(params..);

In your asynctask constructor

 Context c;
 public  RequestJsonString( Context context)
 {
        c= context;
 }

Then

   Intent intent = new Intent(c,DisplayResults.class);
   startActivity(intent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM