Demo Do not keep Activity - Solution (with source code)

Updated: 04 June 2013

Tested in:
HTC desire S (android 2.3.5), Samsung Galaxy S3 (android 4.1.2)

Base on:
Eclipse Indigo build in 20120216-1857, Java 1.6, Android 4.2.2

Download Source code:
DemoDontKeepActivity20130604.rar

Description:
This tutorial focused on ONE of many problems caused by "Activity killed" and give you a simple solutions.
When activity re-created, if you don't control the fragment manager, all fragments exist and overlap.
(Notice: make all fragments 's background TRANSPARENT to see the problem).

Screen shot:



Solution:
1. When creating a fragment, add it to backstack:

 ft.add(R.id.layoutContent, newFragment);
 ft.show(newFragment);
 mFragmentList.put(newFragmentName, newFragment);
 ft.addToBackStack(createTimeStamp());
 mCurrentFragment = newFragment;

2. When init Fragment Manager, check the backstack and remove all Fragments which we can't control.

 try {
  for (int i = mFragmentManager.getBackStackEntryCount() - 1; i >= 0; i--) {
   Log.e(TAG, "remove fragment");
   mFragmentManager.popBackStack();
  }
 } catch (Exception e) {
 }

References:
n/a

Leave a Reply

Powered by Blogger.