I believe that your fragment is updated every time you switch the tab, which means that your field variables are reset.
You can probably use the saveInstance package to control the state of your fragment, but I find it more useful and easier to use SharedPreferences. It also has the advantage of saving a saved state, even if your application is restarted.
To read and write variables to SharedPreferences, I use this little helper class:
public class PreferencesData { public static void saveString(Context context, String key, String value) { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(context); sharedPrefs.edit().putString(key, value).commit(); } public static void saveInt(Context context, String key, int value) { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(context); sharedPrefs.edit().putInt(key, value).commit(); } public static void saveBoolean(Context context, String key, boolean value) { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(context); sharedPrefs.edit().putBoolean(key, value).commit(); } public static int getInt(Context context, String key, int defaultValue) { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(context); return sharedPrefs.getInt(key, defaultValue); } public static String getString(Context context, String key, String defaultValue) { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(context); return sharedPrefs.getString(key, defaultValue); } public static boolean getBoolean(Context context, String key, boolean defaultValue) { SharedPreferences sharedPrefs = PreferenceManager .getDefaultSharedPreferences(context); return sharedPrefs.getBoolean(key, defaultValue); } }
Now, as an example, to save the mIsViewInitiated variable, then in onPause:
@Override protected void onPause() { PreferencesData.saveBoolean(this, "isViewInitiated", mIsViewInitiated); super.onPause(); }
And return it again:
@Override public void onActivityCreated(Bundle savedInstanceState) { try { super.onActivityCreated(savedInstanceState); Log.e("AudioContainerFragmentClass", "onActivityCreated called"); // will now be true if onPause have been called mIsViewInitiated = PreferencesData.getBoolean(this, "isViewInitiated", false); if (!mIsViewInitiated) { mIsViewInitiated = true; initView(); } } catch (Exception e) { printException(e.toString()); } }
Since this example variable indicates whether any user interface has been loaded, then you can set it to false when destroying the activity.
@Override protected void onDestroy() { PreferencesData.saveBoolean(this, "isViewInitiated", false); super.onDestroy(); }
This answer is just one option and shows my personal preferences, while other options are better suited to your situation. I would suggest taking a look at http://developer.android.com/guide/topics/data/data-storage.html