在onPostExecute()中调用另一个asynctask

时间:2015-04-08 13:11:17

标签: android

我试图在我的onPostExcute中调用另一个Asynchtask。 Logcat说我对第二个异步任务的最后一行有问题。我找不到问题。任何帮助将不胜感激。

LoginActivity有一个方法loginUser,它调用第一个Asynchtask PostLoginData,它调用第二个名为VitalService的函数。

Logcat说问题出在第二个asynctask的最后一行

这是代码

LoginActivity

public class LoginActivity extends ActionBarActivity {

    public final static String EXTRA_MESSAGE = "com.cinch.loginapp.MESSAGE";
    public static final String urlString = RestApiPaths.LOGIN;
    public static Context context;
    LoginActivity loginActivity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        context = this.getBaseContext();

    }
    public void loginUser(View view) {
        EditText user = (EditText) findViewById(R.id.enter_username);
        EditText pass = (EditText) findViewById(R.id.enter_password);
        String username = user.getText().toString();
        String password = pass.getText().toString();
        if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
            PostLoginData postLoginData = new PostLoginData(LoginActivity.this);
            postLoginData.execute(urlString, username, password);
        }

    }
}

PostLoginData.java

public class PostLoginData extends AsyncTask<String, String, String> {

    public LoginActivity loginActivity;
    private Activity activity;
    private Context context;
    public PostLoginData(LoginActivity activity){
        super();
        this.activity = activity;
        this.context = this.activity.getApplicationContext();
    }

    @Override
    protected String doInBackground(String... params) {

        String username = params[1].toString();
        String password = params[2].toString();
        String message = null;
        HttpClient httpClient = ServiceHelper.getHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost("http://test.gogch.com/gch-restful/login");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username",username));
        nameValuePairs.add(new BasicNameValuePair("password",password));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
        catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        try {
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            Log.d("Http Post Response:" ,Integer.toString(statusCode));
            message = EntityUtils.toString(response.getEntity());
            Log.d("Http Post Response:" ,message);
        }
        catch(ClientProtocolException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return message;
    }

    protected void onPostExecute(String result) {

        try {
            JSONObject json = new JSONObject(result);
            String status = json.getString("status");
            if(status.equals("true"))
                new VitalService(activity).execute();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

VitalService

public class VitalService extends AsyncTask<String, String, String> {

    public final static String VITAL_RESPONSE = "com.cinch.loginapp.VITALS";
    private Context context;
    private Activity activity;

    public VitalService(Activity activity){
        super();
        this.activity = activity;
        this.context = this.activity.getApplicationContext();
    }
    protected String doInBackground(String... params){

        String vitalsResponseText = null;
        HttpClient httpClient = ServiceHelper.getHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet("http://test.gogch.com/gch-restful/vitals/custome/added/parentvitals");
        Log.d("KMN", "Sucess");
        try {
            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            vitalsResponseText = EntityUtils.toString(response.getEntity());
        }
        catch(ClientProtocolException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return vitalsResponseText;
    }

    protected void onPostExecute(String responseText){

        Intent intent = new Intent(context, VitalListActivity.class);
        intent.putExtra(VITAL_RESPONSE,responseText);
        Log.d("putextra","success");
        context.startActivity(intent);

    }

}

VitalListActivity

public class VitalListActivity extends ActionBarActivity {

    private static List<String> vitalList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_vital_list);
        Log.d("rfvb","ok");
        Intent intent = getIntent();
        String status = intent.getStringExtra(VitalService.VITAL_RESPONSE);
        TextView tv = new TextView(this);
        tv.setText(status);
        setContentView(tv);
    }
}

logcat的

04-08 18:17:30.028    3716-3716/com.cinch.getvitalsapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.cinch.getvitalsapp, PID: 3716
    android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
            at android.app.ContextImpl.startActivity(ContextImpl.java:1232)
            at android.app.ContextImpl.startActivity(ContextImpl.java:1219)
            at android.content.ContextWrapper.startActivity(ContextWrapper.java:322)
            at com.cinch.getvitalsapp.services.VitalService.onPostExecute(VitalService.java:65)
            at com.cinch.getvitalsapp.services.VitalService.onPostExecute(VitalService.java:28)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

3 个答案:

答案 0 :(得分:1)

我不确定它会起作用。基于我的想法

Intent i = new Intent().setClass(context, YourActivity.class);  
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

// Launch the new activity and add the additional flags to the intent
context.startActivity(i);

一旦我遇到同样的问题。我解决了这个不确定你的情况。试试这个。

答案 1 :(得分:0)

使用您的本地字段activity而不是context来启动新的Activity。它将此标记为问题,因为context字段实际上是应用程序上下文而不是Activity上下文。

答案 2 :(得分:0)

请勿使用applicationContext代替传递活动。

public class VitalService扩展了AsyncTask {

    public final static String VITAL_RESPONSE = "com.cinch.loginapp.VITALS";
    private Context context;
    private Activity activity;

    public VitalService(Activity activity){
        super();
        this.activity = activity;
        this.context = this.activity.getApplicationContext();
    }
    protected String doInBackground(String... params){

        String vitalsResponseText = null;
        HttpClient httpClient = ServiceHelper.getHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet("http://test.gogch.com/gch-restful/vitals/custome/added/parentvitals");
        Log.d("KMN", "Sucess");
        try {
            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            vitalsResponseText = EntityUtils.toString(response.getEntity());
        }
        catch(ClientProtocolException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return vitalsResponseText;
    }

    protected void onPostExecute(String responseText){
        if(activity == null){
         //please handle this state because it might happen
}
        Intent intent = new Intent(activity, VitalListActivity.class);
        intent.putExtra(VITAL_RESPONSE,responseText);
        Log.d("putextra","success");
        activity.startActivity(intent);

    }

}