1

I need to change my LoginMechanism into an asynchTask, so that it wont throw a android.os.NetworkOnMainThreadException in SDK 4.x. Its not clear for me how I can start a new intent in this asynctask. I understand that the work will be done in the doInBackground-Method and this return result will be processed in the onPostExecute method. In this method I tried to start my new activity and my service but it shows me compiler errors

The constructor Intent(MainActivity.LoginTask, Class<AttachService>) is undefined

and here is the onPostExecute Method

        @Override
    protected void onPostExecute(String result) {
        super.onPostExecute( result );
        if (result.equals("")){
            loginError.setText(R.string.login_error);
            loginError.setVisibility(View.VISIBLE);
        }
        else{
            loginError.setVisibility(View.INVISIBLE);
            startService(new Intent(LoginTask.this, AttachService.class));
            Log.d(TAG, "setting status of user " + login.getText().toString() + " to stored for service endpoint  " + service_endpoint_spinner.getSelectedItemId());
            if (appData.getLoggedInUser() == null){
                loggedInUser = DBManager.getInstance().storeUser(user,hashedPw,target, true);
                appData.setLoggedInUser(loggedInUser);
                DBManager.getInstance().setUserStatusToStored(loggedInUser);
            }
            startActivity(new Intent(this, ActionActivity.class));          
        }

    }

All the startservice and startActivity methods produces compiler error, can someone explain why. Thanks

Al Phaba
  • 6,545
  • 12
  • 51
  • 83
  • You may need to define the context as a local variable for the AsynchTask http://stackoverflow.com/questions/9118015/how-to-correctly-start-activity-from-postexecute-in-android – Woodsy Dec 18 '12 at 15:29

3 Answers3

3

use

startActivity(new Intent(Your_Current_Activity.this, ActionActivity.class));  

OR

startActivity(new Intent(getApplicationContext(), ActionActivity.class));

instead of

startActivity(new Intent(this, ActionActivity.class)); 

for starting new activity from onPostExecute

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
1

In:

new Intent(this, ActionActivity.class)

"this" means the AsyncTask object. Use (your class name).this instead.

Michał Kisiel
  • 1,050
  • 10
  • 12
0

Inside the AsyncTask, this refers to the object, which is an AsyncTask.

You want to refer the parent activity, or the context, so replace it with

startActivity(new Intent(ParentActivity.this, ActionActivity.class));
shalafi
  • 3,926
  • 2
  • 23
  • 27