iamcrypticcoder
iamcrypticcoder

Reputation: 2899

finish() method is not working inside of AsyncTask

I know finish() method is used to finish current activity while starting a new activity. But probably finish() method is not working in my AsyncTask override method. Okay, My current activity is LoginActivity in which I implemented AsyncTask and in one of my override methods of AsyncTask I am starting LoggedInActivity. In LoggedInActivity there are many fragments. This doesn't cause any problem I think so. When I press BACK button I get LoginActivity. I don't want that. Please take a look at my code:

public class LoginActivity extends Activity implements OnClickListener {
    private void startLoggedInActivity()
    {
        Intent i = new Intent(this, LoggedInActivity.class);
        startActivity(i);
        finish();
    }
    private class FetchProfileTask extends AsyncTask<String, Integer, JSONObject>
    {
        protected JSONObject doInBackground(String... strings) {
            bla....bla....
        }
        protected void onPreExecute() {
            bla....bla....
        }
        protected void onPostExecute(JSONObject jsonObject) {
            try {
                startLoggedInActivity();
            } catch (Exception e) {
                Log.w("Exception", "FetchProfileTask - onPostExecute()");
            } finally {

            }
        }
    }
}

I will be pleased if anyone helps me.....

Upvotes: 0

Views: 390

Answers (3)

Shivam Verma
Shivam Verma

Reputation: 8023

Activity activity; // Instance Variable

Inside On Create :

activity = this;

private void startLoggedInActivity()
{
    Intent i = new Intent(this, LoggedInActivity.class);
    startActivity(i);
    activity.finish();
}

Upvotes: 0

从此醉
从此醉

Reputation: 44

The back button will change to the last activity. If the activity is finished, Android will create it again(I'm not very sure).So I think you can rewrite the back button.

Upvotes: 0

Dan Harms
Dan Harms

Reputation: 4840

Add android:noHistory="true" to LoginActivity in your manifest.

What this does is mark the activity to not be added to your Activity stack after going to another activity. So when you press the back button, it will close your app rather than going back to the LoginActivity. With this approach, you no longer need the finish() call.

<activity
    ...
    android:noHistory="true">

Upvotes: 1

Related Questions