Rectangle 27 2

Well, you can't move back in the current stack without finishing the activity. Perhaps you could detect onBackPressed() and then launch the home intent in a new task:

public void onBackPressed() {
    Intent i = new Intent("android.intent.action.MAIN");
        i.addCategory("android.intent.category.HOME");
        i.addCategory("android.intent.category.DEFAULT");
        i.addCategory("android.intent.category.LAUNCHER");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    return;             
}

Let me know if that works.

i didnt try this one as the one-line solution from NeTe worked, but thanks nevertheless!

That is a nifty method: wasn't aware it was out there.

android - onBackPressed to hide Not destroy activity - Stack Overflow

android
Rectangle 27 10

When you rotate the device, Android saves, destroys, and recreates your Activity and its ViewPager of Fragments. Since the ViewPager uses the FragmentManager of your Activity, it saves and reuses those Fragments for you (and does not create new ones), so they will hold the old references to your (now destroyed) original Activity, and you get that IllegalStateException.

Fragments
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    Log.v(TAG, "onAttach");

    // Check if parent activity implements our callback interface
    if (activity != null) {
        try {
            mParentCallback = (Callbacks) activity;
        }
        catch (ClassCastException e) {
        }
    }
}

Then when a selection occurs:

if(mParentCallback != null) {
    mParentCallback.onItemSelected(selectedLink);
}

Since onAttach gets called as part of the Fragment lifecycle, your Fragments will update their callback reference on rotation.

Unfortunately this doesn't work. My onAttach method already looks like the one you provided. On orientation change my onAttach method is not called again and as a result my callback is not being updated. The parent Fragment has setRetainInstance(true), I guess this prevents this child Fragment from being detached?

Hmm according to the documentation onAttach should still be getting called even if setRetainInstance(true) is set, so something else may be going wrong here. Could you post more of your code around setting and calling your callback? Also, check out the answer to this question, using setRetainInstance(true) is not a good practice in this situation, you should be saving and restoring state - stackoverflow.com/questions/11182180/

I found a solution. Because I had nested Fragments like this: (FragmentActivity -> Fragment 1 -> Fragment 2 (with ViewPager) -> ViewPager Child Fragments) I had to move the callbacks to Fragment 1 (where onAttach and onDetach were being called). I then made a static call from the onItemSelected method in the ViewPager's child Fragments to the callback in the parent Fragment (Fragment 1). This seems a bit of a hack but works well. I use setRetainInstance(true) in Fragment 1 so the child Fragments retain state too.

Ahh I see so your architecture is a bit more complex. I have done something similar this before, where a Fragment calls back to its parent Fragment. I used the same code as above in onAttach, but instead of casting the parent Activity to my callback, I casted getParentFragment() to get a ref to the parent Fragment who implemented the callback. Maybe that could help make a cleaner solution, but glad you found one either way.

Thanks a lot guys. At first I was confused why this was the accepted answer, but comment 3 and 4 helped a lot. This is what I had: Parentfragment -> viewpager with fragments - > child fragment. I put a listener in viewpager fragments to ParentFragment, using getParentFragment in onAttach, then a second listener to pass that data on in parentfragment to fragmentactivity. I think that is what Steven meant. Now I can get everything to attach correctly:)

android - 'IllegalStateException: Activity has been destroyed' when 'g...

android android-fragments android-viewpager illegalstateexception
Rectangle 27 10

When you rotate the device, Android saves, destroys, and recreates your Activity and its ViewPager of Fragments. Since the ViewPager uses the FragmentManager of your Activity, it saves and reuses those Fragments for you (and does not create new ones), so they will hold the old references to your (now destroyed) original Activity, and you get that IllegalStateException.

Fragments
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    Log.v(TAG, "onAttach");

    // Check if parent activity implements our callback interface
    if (activity != null) {
        try {
            mParentCallback = (Callbacks) activity;
        }
        catch (ClassCastException e) {
        }
    }
}

Then when a selection occurs:

if(mParentCallback != null) {
    mParentCallback.onItemSelected(selectedLink);
}

Since onAttach gets called as part of the Fragment lifecycle, your Fragments will update their callback reference on rotation.

Unfortunately this doesn't work. My onAttach method already looks like the one you provided. On orientation change my onAttach method is not called again and as a result my callback is not being updated. The parent Fragment has setRetainInstance(true), I guess this prevents this child Fragment from being detached?

Hmm according to the documentation onAttach should still be getting called even if setRetainInstance(true) is set, so something else may be going wrong here. Could you post more of your code around setting and calling your callback? Also, check out the answer to this question, using setRetainInstance(true) is not a good practice in this situation, you should be saving and restoring state - stackoverflow.com/questions/11182180/

I found a solution. Because I had nested Fragments like this: (FragmentActivity -> Fragment 1 -> Fragment 2 (with ViewPager) -> ViewPager Child Fragments) I had to move the callbacks to Fragment 1 (where onAttach and onDetach were being called). I then made a static call from the onItemSelected method in the ViewPager's child Fragments to the callback in the parent Fragment (Fragment 1). This seems a bit of a hack but works well. I use setRetainInstance(true) in Fragment 1 so the child Fragments retain state too.

Ahh I see so your architecture is a bit more complex. I have done something similar this before, where a Fragment calls back to its parent Fragment. I used the same code as above in onAttach, but instead of casting the parent Activity to my callback, I casted getParentFragment() to get a ref to the parent Fragment who implemented the callback. Maybe that could help make a cleaner solution, but glad you found one either way.

Thanks a lot guys. At first I was confused why this was the accepted answer, but comment 3 and 4 helped a lot. This is what I had: Parentfragment -> viewpager with fragments - > child fragment. I put a listener in viewpager fragments to ParentFragment, using getParentFragment in onAttach, then a second listener to pass that data on in parentfragment to fragmentactivity. I think that is what Steven meant. Now I can get everything to attach correctly:)

android - 'IllegalStateException: Activity has been destroyed' when 'g...

android android-fragments android-viewpager illegalstateexception
Rectangle 27 1

1. AsyncTasks don't follow Activity instances' life cycle. If you start an 
    AsyncTask inside an Activity and you rotate the device, the Activity 
    will be destroyed and a new instance will be created. But the AsyncTask 
    will not die. It will go on living until it completes.

    AsyncTask processes are not automatically killed by the OS. AsyncTask 
    processes run in the background and is responsible for finishing it's 
    own job in any case. You can cancel your AsycnTask by calling 
    cancel(true) method. This will cause subsequent calls to isCancelled() 
    to return true. After invoking this method, onCancelled(Object) method 
    is called instead of onPostExecute() after doInBackground() returns.

  2. intentService or AsyncTask or Volley or Retrofit , there are so many 
     way for connecting with web services and all has it's importance. But 
     you can use Volley is now officially supported by Google.

android - garbage collector and AsyncTask associated with the destroye...

android android-activity android-asynctask
Rectangle 27 0

It'll be better if you implement your logic otherwise. The first screen in your application can be HomeScreenActivity in which you'll check if the user is logged and start LoginActivity if needed.

public class HomeScreenActivity extends Activity {

    /* some declaration */
    public void onCreate(Bundle savedInstanceState) {
        /* some other stuff */
        if (!userIsLogged()) {
            Intent intent = new Intent(this,LoginActivity.class);
            startActivity(intent);
        }
    }
}

android - Kill and destroy activity - Stack Overflow

android android-activity kill destroy
Rectangle 27 0

This can be solved by taking a closer look at your intent flags. Check out http://developer.android.com/reference/android/content/Intent.html and they give more information about what lifecycle you are shooting for.

Also, don't forget that you can override the back button functionality. This may be helpful in case you want to manage your life cycle more closely. For example, you can also make sure to go back to A if back from B. And close your app if back on A.

android - How to destroy an Activity so it doesn't show up when the ba...

android android-activity ondestroy activity-finish recreate
Rectangle 27 0

I have managed to work out exactly what you want: switch between 2 activities using Back button and keep them all not to be destroyed! For example: you have 2 activities A & B. A will be started first, then A calls B. When B is loaded, user press Back button and switches back to activity A from B. From now B should not be destroyed and just goes to background, and when user starts activity B from A again, activity B will be brought to foreground, instead of being re-created again or created new instance! How to implement this: 1. Override onBackPressed() of activity B:

@Override
public void onBackPressed() {
    Intent backIntent = new Intent(this, ActivityA.class);
    backIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(backIntent);
}
public void callActivityB() {
    Intent toBintent = new Intent(this, ActivityB.class);
    toBIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    startActivity(toBintent);
}

android - How to make an activity stop, rather then be destroyed, from...

android
Rectangle 27 0

private BroadcastReceiver finishReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };
public void onCreate() {
LocalBroadcastManager.getInstance(this)
                .registerReceiver(finishReceiver ,
                        new IntentFilter("B-finish"));
}
public void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(
                finishReceiver );
}
LocalBroadcastManager.getInstance(this).sendBroadcast(
                new Intent("B-finish"));
Intent intent_to_a=new Intent(C.this,A.class);
                intent_to_home.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent_to_a);

android - Flag Activity Clear Top destroys target activity and than cr...

android android-intent android-activity android-lifecycle
Rectangle 27 0

/**
 * Ask the currently running looper to quit.  If the thread has not
 * been started or has finished (that is if {@link #getLooper} returns
 * null), then false is returned.  Otherwise the looper is asked to
 * quit and true is returned.
 */
public boolean quit() {
    Looper looper = getLooper();
    if (looper != null) {
        looper.quit();
        return true;
    }
    return false;
}

Above is the 'quit' method of the source code of HandlerThread.java, just invoke it directly.

Why should called quit? Below is 'run' method of the source code of HandlerThread.java.

public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();//always loop except for a Message with null target

    mTid = -1;
}

android - Should I manually close HandlerThreads created by my applica...

android activity-lifecycle android-handler
Rectangle 27 0

This thing is device specific, some devices didnt go to onresume, and start life cycle from start, To handle that you can use Savedinstatnce, to save a state .

android - Pressing back button stops and destroys my Activity insted o...

android listview android-tabhost onresume onpause
Rectangle 27 0

i think there are little conceptual problem Actually FLAG_ACTIVITY_CLEAR_TOP flag is Use is check here: http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP so in that case there are no need finish() method it is already Remove mainActivity class but according to document you have to add one more Flag FLAG_ACTIVITY_NEW_TASK to your intent.

with

Intent i = new Intent(MainActivity.this, LoginActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

Android : destroy activity before intent to another activity - Stack O...

android android-intent
Rectangle 27 0

What to do is start the activity C with the some request code from B... and accordingly finish the activity with this request code

android - How to destroy previous activity in Activity? - Stack Overfl...

android android-activity destroy activity-finish
Rectangle 27 0

It looks like your Runnable is closing over a reference to your activity. When you press back and then start your activity again, your old activity is destroyed and a new instance is created. Your background thread continues to make changes to the original activity, which no longer exists, therefore making changes to its views has no effect.

You need to either stop the updating thread when the actiivty is paused or stopped as appropriate and restart it when the activty is resumed or started (again, as appropriate) and make sure that you are always updating the activty that is actually visible.

java - runOnUiThread stops Working When Application is Destroyed - Sta...

java android multithreading
Rectangle 27 0

Had a similar issue. Basically if the ViewPager just has couple of fragments, then store references to them in current activity. DO NOT call pagerAdapter's getItem() because it creates a new fragment and it is not attached to any activity and that's why we see "Activity has been destroyed" exception. If you don't want to keep fragment references, then you can use findViewWithTag() method to get Fragment object.

android - 'IllegalStateException: Activity has been destroyed' when 'g...

android android-fragments android-viewpager illegalstateexception
Rectangle 27 0

Try starting your sub activities B and C with the flag FLAG_ACTIVITY_NO_HISTORY.

Interesting, I haven't messed with intent flags before. These seem to just replicate the functionality of overriding B and C's onStop though (scorched earth), but they do give back some null returns back on the main activity's onActivityResult that I could capture for persistence.... I'll tinker with some other flags that look promising and report back.

I still couldnt get it to work as imagined, but I did learn a good deal about intent flags in the process so ill mark it as correct. I ended up going the scorched-earth route (override onStop, call finish();) because leaving my data in an inconsistent state just wasnt acceptable.

Android - Tell if parent activity has been destroyed - Stack Overflow

android android-activity oncreate ondestroy
Rectangle 27 0

  • pass the data via intent in a bundle
  • Save it in shared preferences
  • Save it in a database
  • Save the data to a file
  • save the data on the webserver

android - Using objects of one activity in another after activity is d...

android android-activity activity-lifecycle
Rectangle 27 0

The following will dispose of the current activity while launching the next intent:

Intent launchNext = new Intent(getApplicationContext(), NextActivity.class);
launchNext.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(launchNext);

To override the back button, use the following:

@Override
public void onBackPressed() {
    super.onBackPressed();
    this.finish(); // or do something else
}

Overriding onBackPressed() simply to call finish() is redundant... Take a look at the source code, the only thing that onBackPressed() does is call finish().

@Sam that is why I put // or do something else

I'm not certain why someone downvoted you, using "clear top" is good advice... (Upvote from me!) However calling "super.onBackPressed() and finish()", is the same as suggesting that TheBeatlemaniac should call "super.onBackPressed() and super.onBackPressed()" or "finish() and finish()"... Also the "clear top" flag closes the current Activity, so ironically calling finish() is redundant here too.

android - How to destroy an Activity so it doesn't show up when the ba...

android android-activity ondestroy activity-finish recreate
Rectangle 27 0

method and start there the activity like this:

@Override
    public void onBackPressed() {
    Intent intent = new Intent(this, activityA.class);
    startActivityForResult(intent, PICK_CONTACT_REQ);
}

android - Not to destroy current activity on back button is pressed - ...

android android-activity
Rectangle 27 0

When you rotate the device, Android saves, destroys, and recreates your Activity and its ViewPager of Fragments. Since the ViewPager uses the FragmentManager of your Activity, it saves and reuses those Fragments for you (and does not create new ones), so they will hold the old references to your (now destroyed) original Activity, and you get that IllegalStateException.

Fragments
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    Log.v(TAG, "onAttach");

    // Check if parent activity implements our callback interface
    if (activity != null) {
        try {
            mParentCallback = (Callbacks) activity;
        }
        catch (ClassCastException e) {
        }
    }
}

Then when a selection occurs:

if(mParentCallback != null) {
    mParentCallback.onItemSelected(selectedLink);
}

Since onAttach gets called as part of the Fragment lifecycle, your Fragments will update their callback reference on rotation.

Unfortunately this doesn't work. My onAttach method already looks like the one you provided. On orientation change my onAttach method is not called again and as a result my callback is not being updated. The parent Fragment has setRetainInstance(true), I guess this prevents this child Fragment from being detached?

Hmm according to the documentation onAttach should still be getting called even if setRetainInstance(true) is set, so something else may be going wrong here. Could you post more of your code around setting and calling your callback? Also, check out the answer to this question, using setRetainInstance(true) is not a good practice in this situation, you should be saving and restoring state - stackoverflow.com/questions/11182180/

I found a solution. Because I had nested Fragments like this: (FragmentActivity -> Fragment 1 -> Fragment 2 (with ViewPager) -> ViewPager Child Fragments) I had to move the callbacks to Fragment 1 (where onAttach and onDetach were being called). I then made a static call from the onItemSelected method in the ViewPager's child Fragments to the callback in the parent Fragment (Fragment 1). This seems a bit of a hack but works well. I use setRetainInstance(true) in Fragment 1 so the child Fragments retain state too.

Ahh I see so your architecture is a bit more complex. I have done something similar this before, where a Fragment calls back to its parent Fragment. I used the same code as above in onAttach, but instead of casting the parent Activity to my callback, I casted getParentFragment() to get a ref to the parent Fragment who implemented the callback. Maybe that could help make a cleaner solution, but glad you found one either way.

Thanks a lot guys. At first I was confused why this was the accepted answer, but comment 3 and 4 helped a lot. This is what I had: Parentfragment -> viewpager with fragments - > child fragment. I put a listener in viewpager fragments to ParentFragment, using getParentFragment in onAttach, then a second listener to pass that data on in parentfragment to fragmentactivity. I think that is what Steven meant. Now I can get everything to attach correctly:)

android - 'IllegalStateException: Activity has been destroyed' when 'g...

android android-fragments android-viewpager illegalstateexception