How can I save my data on phone orientation? - android

I'm having difficulties with making my app persistent. When I rotate my phone the data on the screen doesnt change. But after I click on a button to retrieve a new fragment I get an error saying "Can not perform this action after onSaveInstanceState". I have googled and seen similiar problems but I still dont know how to approach and solve this.
I have an activity class, a controller class and two fragment classes.
The activity class has a navigationviewer with 2 buttons that triggers a fragmenttransaction. That is, on each button click it will replace the current fragment with the one set in the button listener. My controller class initalizes the system and the fragments are just the UI.
My activity class:
public class LoggedInActivity extends AppCompatActivity {
private final String TAG = "LoggedInActivity: ";
private Controller controller;
private TextView navName;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.v(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
if(savedInstanceState == null) {
Log.v(TAG, "savedInstanceState == null");
initComponents();
setNavName();
initListener();
initializeSystem();
} else {
Log.v(TAG, "savedInstanceState != null");
initComponents();
setNavName();
initListener();
this.controller = (Controller)savedInstanceState.getSerializable("controller");
}
}
private void initComponents() {
navigationView = (NavigationView) findViewById(R.id.navigation_view);
View headerView = navigationView.getHeaderView(0);
navName = (TextView) headerView.findViewById(R.id.tv_name_surname);
}
private void initListener() {
navigationView.setNavigationItemSelectedListener(new MyNavigationItemListener());
}
private void initializeSystem() {
Log.v(TAG, "new controller");
controller = new Controller(this, null);
}
public void setFragment(Fragment fragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container_logged_in, fragment).commit();
}
private class MyNavigationItemListener implements NavigationView.OnNavigationItemSelectedListener {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()) {
case R.id.drawer_summary:
controller.setFragmentSummary();
break;
case R.id.drawer_income:
controller.setFragmentIncome();
break;
}
return false;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable("controller", controller);
super.onSaveInstanceState(outState);
Log.v(TAG, "onSaveInstanceState, saving the controller");
}
}
My controller class:
public class Controller implements Serializable {
private final String TAG = "Controller: ";
/********************** Fragments ***********************/
private Fragment_Income fragment_income;
private Fragment_Summary fragment_summary;
/********************************************************/
/********************** Activities **********************/
private LoggedInActivity logged_in_activity;
/********************************************************/
public Controller(LoggedInActivity logged_in_activity) {
this.logged_in_activity = logged_in_activity;
initLoggedInFragments();
setFragmentSummary();
}
}
/* Initializes fragments that are connected to LoggedInActivity */
private void initLoggedInFragments() {
fragment_income = new Fragment_Income();
fragment_income.setController(this);
fragment_summary = new Fragment_Summary();
fragment_summary.setController(this);
}
/* use to replace current fragment with the given one */
private void replaceFragmentWith(Fragment fragment) {
logged_in_activity.setFragment(fragment);
}
/***********************************************************
* METHODS REGARDING FRAGMENT INCOME *
**********************************************************/
public void setFragmentIncome() {
replaceFragmentWith(fragment_income);
}
/* Summary fragment is started at first */
public void setFragmentSummary() {
replaceFragmentWith(fragment_summary);
}
}
Fragment_Income:
public class Fragment_Income extends Fragment implements Serializable{
private final String TAG = "Fragment_Income: ";
private Controller controller;
private FloatingActionButton fab_income;
private ListView lv_income;
private ArrayList<LvData> incomeData;
private LvAdapterIncome lvAdapterIncome;
public Fragment_Income() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v(TAG, "onCreateView");
View view = inflater.inflate(R.layout.fragment_income, container, false); // Inflate the layout for this fragment
if(savedInstanceState != null) {
this.controller = (Controller) savedInstanceState.getSerializable("controller");
}
initComponents(view);
initListener();
setupListView();
return view;
}
private void initComponents(View view) {
fab_income = (FloatingActionButton) view.findViewById(R.id.fab_income);
lv_income = (ListView) view.findViewById(R.id.lv_income);
}
private void initListener() {
ButtonListener buttonListener = new ButtonListener();
fab_income.setOnClickListener(buttonListener);
}
private void setupListView() {
if (incomeData == null) { // checks if incomeData have been initalized before, if so do not change array to defualt
incomeData = new ArrayList<>();
lvAdapterIncome = new LvAdapterIncome(getContext(), incomeData);
}
lv_income.setAdapter(lvAdapterIncome);
}
public void setController(Controller controller) {
this.controller = controller;
}
#Override
public void onSaveInstanceState(Bundle outState) {
Log.v(TAG, "onSaveInstanceState, saving the controller");
outState.putSerializable("controller", this.controller);
super.onSaveInstanceState(outState);
}
}
Fragment_Summary:
public class Fragment_Summary extends Fragment implements Serializable {
private static final String TAG = "Fragment_Summary: ";
private Controller controller;
private TextView tv_user;
private TextView tv_total_revenue;
private TextView tv_total_expenditure;
private TextView tv_balance;
private float totalRevenue;
private float totalExpenditure;
private float balance;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_summary, container, false);// Inflate the layout for this fragment
initComponents(view);
setUserName();
if(savedInstanceState == null) {
//DO SOMETHING
}
return view;
}
private void addData() {
totalRevenue = controller.getTotalRevenue();
totalExpenditure = controller.getTotalExpenditure();
balance = totalRevenue - totalExpenditure;
tv_total_revenue.setText(String.valueOf(totalRevenue));
tv_total_expenditure.setText(String.valueOf(totalExpenditure));
tv_balance.setText(String.valueOf(balance));
}
private void initComponents(View view) {
tv_user = (TextView)view.findViewById(R.id.tv_user);
tv_total_revenue = (TextView)view.findViewById(R.id.tv_revenue);
tv_total_expenditure = (TextView)view.findViewById(R.id.tv_sum_exp);
tv_balance = (TextView)view.findViewById(R.id.tv_balance);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("revenue", String.valueOf(balance));
outState.putString("totalExpenditure", String.valueOf(balance));
outState.putString("balance", String.valueOf(balance));
super.onSaveInstanceState(outState);
}
public void setController(Controller controller) {
this.controller = controller;
}
}
I have removed all the header files and some methods from my classes becuase I tought they were not relevant for this problem.
Here is the error log:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1434)
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1452)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:708)
at android.app.BackStackRecord.commit(BackStackRecord.java:672)
at com.example.user.my_app.LoggedInActivity.setFragment(LoggedInActivity.java:85)
at com.example.user.my_app.Controller.replaceFragmentWith(Controller.java:89)
at com.example.user.my_app.Controller.setFragmentIncome(Controller.java:99)
at com.example.user.my_app.LoggedInActivity$MyNavigationItemListener.onNavigationItemSelected(LoggedInActivity.java:127)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:156)
at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:156)
at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:969)
at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:342)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

This looks like an activity state loss. See this excellent article by Alex Lockwood entitled "Fragment Transactions & Activity State Loss". I refer to it time and again.
To quote the intro to the posting:
The following stack trace and exception message has plagued StackOverflow ever since Honeycomb’s initial release:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)
This post will explain why and when this exception is thrown, and will conclude with several suggestions that will help ensure it never crashes your application again.

Related

Getting a null pointer exception when trying to pass a boolean via an interface

I am using an interface, as is standard (best?) practice to communicate between a series of fragments. The business logic requires the app to collect some information in fragment n+1 and if the "next" button is tapped then the user goes to fragment n+2. If the "back" button is tapped then the user goes to fragment n. I am also using a nice sliding animation to display the transition from one fragment to the other depending on the direction. I cannot figure out why this is not working and I am getting the null pointer error on this line:
createPlanListener.onCreatePlan(bundle);
Here is the initial fragment Mealplan.class where I trigger the transition. I have left all of the boiler plate code generated by Android Studio as is:
public class MealplanFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private FloatingActionButton createMealplan;
// bunch of variables
private Bundle bundle;
private OnCreatePlanListener createPlanListener;
public MealplanFragment() {
// Required empty public constructor
}
public static MealplanFragment newInstance(String param1, String param2) {
MealplanFragment fragment = new MealplanFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Other code that has nothing to do with the bundle or the listener
// Floating action bar
createMealplan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bundle.putBoolean("direction", true);
createPlanListener.onCreatePlan(bundle);
}
});
return mealplanView;
}
public void onButtonPressed(Bundle bundle) {
if (createPlanListener != null) {
createPlanListener.onCreatePlan(bundle);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mealplanContext = context;
if (context instanceof OnCreatePlanListener) {
createPlanListener = (OnCreatePlanListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
createPlanListener = null;
}
public interface OnCreatePlanListener {
void onCreatePlan(Bundle bundle);
}
#Override
public void onResume() {
super.onResume();
}
And here is MainActivity.class
public class MainActivity extends AppCompatActivity implements
MealplanFragment.OnCreatePlanListener {
// Non related variables
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// MealplanFragment is the default fragment at onCreate
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new MealplanFragment(), null).commit();
}
}
#Override
public void onCreatePlan(Bundle bundle) {
if (bundle != null) {
Boolean direction = bundle.getBoolean("direction");
ReceptionFragment fragment = new ReceptionFragment();
openFragment(bundle, fragment, direction);
}
}
private void openFragment(Bundle bundle, Fragment fragment, Boolean direction) {
fragment.setArguments(bundle);
//Starting fragment with animation
if (direction) {
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right).replace(R.id.frame_container, fragment, null);
fragmentTransaction.commit();
} else {
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_left).replace(R.id.frame_container, fragment, null);
fragmentTransaction.commit();
}
}
}
createMealplan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bundle.putBoolean("direction", true);
createPlanListener.onCreatePlan(bundle);
}
});
This is your click listener. bundle is defined as class variable but never initialized and hence the null pointer exception. I would suggest that you use a local variable -> create a new instance of bundle, add data and then invoke callback. Also, createPlanListener is nullable, so you should add a check for that as well.

Why does pressing back from detail activity after landscape-to-portrait-switch show an empty screen?

Below is the MainActivity class that I'm using. The code checks to see if the phone is in landscape or portrait. If it's in portrait, it will show the main fragment in the main activity only (the main fragment is a static fragment in the main_activity.xml file). Then if a "Recipe" is clicked it will open a detail activity with its own fragment. If the phone is in landscape mode, it will show the main fragment and the detail fragment side by side. Everything works perfectly fine however when I follow the procedure below I get a white screen instead of the main activity:
Procedure:
Switch to landscape
Switch back to portrait
Choose an item and wait for the detail activity to open
Press back
Here instead of the main activity window I get a white screen
If I don't switch to landscape and just start with the portrait mode everything is fine. It seems like switching to landscape does something that causes the problem and I can't figure out what. Any tip on what's going on or where to look would be much appreciated.
public class MainActivity extends AppCompatActivity implements RecipesFragment.OnRecipeClickListener {
private String RECIPE_PARCEL_KEY;
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RECIPE_PARCEL_KEY = getString(R.string.ParcelKey_RecipeParcel);
if (findViewById(R.id.linearLayoutTwoPane) != null) {
mTwoPane = true;
if (savedInstanceState == null) {
RecipeFragment recipeFragment = new RecipeFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.add(R.id.recipeFrameForTwoPane, recipeFragment)
.commit();
}
} else {
mTwoPane = false;
}
}
#Override
public void OnRecipeClick(Recipe recipe) {
if (mTwoPane) {
RecipeFragment recipeFragment = new RecipeFragment();
recipeFragment.setRecipe(recipe);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.recipeFrameForTwoPane, recipeFragment)
.commit();
} else {
Class destinationClass = DetailActivity.class;
Intent intentToStartDetailActivity = new Intent(this, destinationClass);
intentToStartDetailActivity.putExtra(RECIPE_PARCEL_KEY, recipe);
startActivity(intentToStartDetailActivity);
}
}
}
EDIT:
Adding RecipeFragment's code below:
public class RecipeFragment extends Fragment {
private Recipe mRecipe;
#BindView(R.id.tv_recipeName) TextView recipeNameTextView;
public RecipeFragment(){
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recipe_fragment,container,false);
ButterKnife.bind(this,view);
if(mRecipe!=null) {
recipeNameTextView.setText(mRecipe.getName());
}else{
recipeNameTextView.setText(getString(R.string.messageSelectARecipe));
}
return view;
}
public void setRecipe(Recipe recipe){
mRecipe = recipe;
}
}
EDIT:
I followed #mt0s's advice and created different background colors for the fragments and activities and finally narrowed down the problem to a line in my recyclerview adapter code. My adapter code is below. Inside loadInBackground() on line URL url = new URL(getString(R.string.URL_RecipeJSON)); I get a Fragment RecipesFragment{96e9b6a} not attached to Activity exception. I don't understand why I'm getting this exception and what the best way to resolve this is. Have I placed the right code in the right fragment methods (ie OnCreate vs OnActivityCreated vs OnCreateView vs etc)?
public class RecipesFragment extends Fragment
implements RecipeAdapter.RecipeAdapterOnClickHandler,
LoaderManager.LoaderCallbacks<ArrayList<Recipe>> {
#BindView(R.id.rv_recipes) RecyclerView mRecyclerView;
private RecipeAdapter mRecipeAdapter;
private static final int LOADER_ID = 1000;
private static final String TAG = "RecipesFragment";
private OnRecipeClickListener mOnRecipeClickListener;
public RecipesFragment(){
}
public interface OnRecipeClickListener {
void OnRecipeClick(Recipe recipe);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recipes_fragment, container, false);
ButterKnife.bind(this, view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
mRecipeAdapter = new RecipeAdapter(this);
mRecyclerView.setAdapter(mRecipeAdapter);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoaderManager().initLoader(LOADER_ID, null, this);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void OnClick(Recipe recipe) {
mOnRecipeClickListener.OnRecipeClick(recipe);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
mOnRecipeClickListener = (OnRecipeClickListener) context;
} catch (ClassCastException e){
Log.e(TAG, "onAttach: Host activity class must implement OnRecipeClickListener.");
}
}
#Override
public Loader<ArrayList<Recipe>> onCreateLoader(int i, Bundle bundle) {
return new AsyncTaskLoader<ArrayList<Recipe>>(getActivity()) {
#Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad();
}
#Override
public ArrayList<Recipe> loadInBackground() {
String response;
ArrayList<Recipe> recipes = null;
try {
URL url = new URL(getString(R.string.URL_RecipeJSON)); //***I get an exception here***
response = NetworkUtils.getResponseFromHttpUrl(url, getActivity());
recipes = RecipeJsonUtils.getRecipeFromJson(getActivity(), response);
} catch (Exception e) {
Log.e(TAG, "loadInBackground: " + e.getMessage());
}
return recipes;
}
};
}
#Override
public void onLoadFinished(Loader<ArrayList<Recipe>> loader, ArrayList<Recipe> recipes) {
mRecipeAdapter.setRecipeData(recipes);
}
#Override
public void onLoaderReset(Loader<ArrayList<Recipe>> loader) {
}
}
I finally figured out the problem and the solution. The problem is that onStartLoading() in the AsyncTaskLoader anonymous class in RecipesFragment class gets called every time the fragment is resumed whether the enclosing Loader is called or not. This causes the problem. I need to have control over when onStartLoading() is being called and I only want it to be called if and only if the enclosing Loader is being initialized or restarted. As such, I destroyed the loader in onPause() of the fragment and restarted it in onResume(). Hence, I added the following code to the RecipesFragment class:
#Override
public void onPause() {
super.onPause();
getLoaderManager().destroyLoader(LOADER_ID);
}
#Override
public void onResume() {
super.onResume();
getLoaderManager().restartLoader(LOADER_ID, null, this);
}
I also removed initLoader() from onCreate(). This way, every time the fragment is resumed (or created) onStartLoading() will be called. I tried this and it solves my problem.
When you switch from the landscape to portrait or the opposite the Android OS destroy your activity and recreate it again. this what probably trigger your problem

Restore savedInstanceState before Fragments onCreate method

I made a test application so I can learn how to save the InstanceState.
Now we have a Main Fragment Activity and two Tab Fragments. I have a variable in the Main Activity that it's value sat in the onCreate method.. and I would like to share it with the fragments.
So I created a public method in the Main Activity to call it inside the fragments when I need the value of that variable. ((TMainActivity) getActivity()).getTestString()
The problem is when the device is rotated I got the default value of the string and not the saved value.
And that's obviously because onRestoreInstanceState is called after the onCreate of the fragments.
Now, how can I work that out?
TMainActivity.java
public class TMainActivity extends FragmentActivity {
final private static String TAG = "TMainActivity";
final private static String EXTRA_TEST = "MAIN_KEY";
private CollectionPagerAdapter mCollectionPagerAdapter;
private ViewPager mainPager;
private String test = "Default";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v(TAG, "onCreate() Before test= " + test);
if (savedInstanceState == null) {
test = "New";
} else {
test = savedInstanceState.getString(EXTRA_TEST) + " - Restored";
}
Log.v(TAG, "onCreate() After test= " + test);
mainPager = (ViewPager) findViewById(R.id.main_pager);
mCollectionPagerAdapter = new CollectionPagerAdapter(getSupportFragmentManager());
mainPager.setAdapter(mCollectionPagerAdapter);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.v(TAG, "onSaveInstanceState()");
outState.putString(EXTRA_TEST, test);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.v(TAG, "onRestoreInstanceState()");
Log.v(TAG, "onRestoreInstanceState() savedInstanceState=" + (savedInstanceState != null));
test = savedInstanceState.getString(EXTRA_TEST);
}
public String getTestString() {
return test;
}
private class CollectionPagerAdapter extends FragmentStatePagerAdapter {
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
switch (i) {
case 0:
fragment = new Tab1Fragment();
break;
case 1:
fragment = new Tab2Fragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
}
Tab1Fragment.java
public class Tab1Fragment extends Fragment {
final private static String TAG = "Tab1Fragment";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate()");
Log.v(TAG, "getTestString()=" + ((TMainActivity) getActivity()).getTestString());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_tab1, container, false);
return rootView;
}
}
Tab2Fragment.java
public class Tab2Fragment extends Fragment {
final private static String TAG = "Tab2Fragment";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate()");
Log.v(TAG, "getTestString()=" + ((TMainActivity) getActivity()).getTestString());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_tab2, container, false);
return rootView;
}
}
I just had the same problem. First is called onCreate in the Activity and in this method you have already available that Bundle with your data. That means that you can restore the Activity and then use the data in onCreateView of the Fragment which is called later.
Basically you do not override the onRestoreInstanceState() method, but rename it and call it from onCreate in your Activity. The reason not to override that method is because it would be called 2 times—from onCreate by you and then as a part of the Activity life-cycle. That would reset the value if it was changed in the Fragment.
In your case you can just move
Log.v(TAG, "getTestString()=" + ((TMainActivity) getActivity()).getTestString());
from onCreate to onCreateView.
This not a good solution when you're restoring large amount of data. Your UI thread would get stuck on restoring the Activity. But in such a case you can restore just some part of the data that is needed in the Fragment and the rest restore in onRestoreInstanceState.

pass string from fragment main activity to fragments activity in viewpager

i wanna pass a string to all fragment(child) from fragment activity (main), may be this picture can explain what exactly what i want to do
https://dl.dropboxusercontent.com/u/57465028/SC20140205-163325.png
so, from above picture...i wanna pass a string from edittext by press a button to all activity in viewpager....how could i do that?
i tried to follow this code https://stackoverflow.com/a/12739968/2003393 but it can't solved my problem..
please help me...i'm stuck
thank in advance.
here is my code from fragment activity (MainActivity)
public class Swipe_Menu extends FragmentActivity {
//String KeyWord;
//private static final String KEYWORD = "keyword";
private ViewPager _mViewPager;
private ViewPagerAdapter _adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.swipe_menu_image);
Button Back = (Button)findViewById(R.id.account);
ImageButton Search = (ImageButton)findViewById(R.id.search);
EditText Keyword = (EditText)findViewById(R.id.keyword);
final String KeyWord = Keyword.getText().toString();
/**
* Back button click event
* */
Back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
setUpView();
setTab();
}
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", KeyWord );
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
and here is my fragment (Child Activity)
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
String KeyWord;
private TextView kata_keyword;
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
KeyWord = value;
}
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/*Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");*/
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
//ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}
You don't have access directly to your fragments that reside in ViewPager so you can't reference them directly.
What I am doing in these cases is send a broadcast message from Activity to Fragments. For this reason register a BroadcatReceiver in the fragment (either in onCreate or onCreateView - your decision)m, set a custom action for that receiver (ex. "my_package.actions.internal.BROADCAST_ACTION"), don't forget to unregister the receiver from complementary method.
When you want to send a message from activity, create an intent with above mentioned action, add the string in intent extra and send the broadcast.
In your receiver's onReceive method (within the fragment), get the String from intent paramter and there you have the string.
Makes sense?
EDIT: To provide some code, below are the changes that I would make for fragment:
public class Store_Swipe extends Fragment {
public static final String ACTION_INTENT = "my_package.action.UI_UPDATE";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(ACTION_INTENT.equals(intent.getAction())) {
String value = intent.getStringExtra("UI_KEY");
updateUIOnReceiverValue(value);
}
}
};
private void updateUIOnReceiverValue(String value) {
// you probably want this:
kata_keyword.setText(value);
}
String KeyWord;
private TextView kata_keyword;
public static Fragment newInstance(Context context) {
Store_Swipe f = new Store_Swipe();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Bundle bundle = this.getArguments();
KeyWord = bundle.getString("keyword");
View view = inflater.inflate(R.layout.store_swipe, container, false);
init(view);
return view;
}
void init(View view) {
kata_keyword = (TextView) view.findViewById(R.id.keyword);
ImageView image = (ImageView) view.findViewById(R.id.image_error);
kata_keyword.setText(KeyWord);
}
}
And this code I would have from activity, the parameter is the value from EditText:
protected void sendValueToFragments(String value) {
// it has to be the same name as in the fragment
Intent intent = new Intent("my_package.action.UI_UPDATE");
intent.putExtra("UI_KEY", value);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
You would call this from the click listener that you would set in onCreate:
findViewById(R.id.button_id).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String valueThatYouWantToSend = null; /// just the value
sendValueToFragments(valueThatYouWantToSend);
}
});
// I think this solution will solved your issue
// In Main activity put your code -----------------------------------
public void onPageSelected(int position)
{
System.out.println("nilesh");
PageOneFragment f = new PageOneFragment();
f.getText();
PageTwoFragment ff = new PageTwoFragment();
ff.setText();
}
//in General Class ------------------------------------------------
public class General
{
public static String name="";
}
// first Fragment ---------------------------------------------
public void getText()
{
General.name = edittext.getText().toString();
}
// second Fragment ----------------------------------------------
public void setText()
{
System.out.println("name**" + General.name);
tv.setText(General.name);
}

Communication between Fragments in ViewPager

I'm trying to do this: http://android-er.blogspot.com/2012/06/communication-between-fragments-in.html
Except that I'm using a FragmentStatePagerAdapter
I have an Activity with two fragments(FragmentA & FragmentB)
FragmentA has an edittext and a button, FragmentB has a textview
Now all I want is that whenever I enter something in the edittext and click the button, that something will appear on my textview.
MainActivity:
public class MainActivity extends FragmentActivity {
ViewPager viewPager = null;
String TabFragmentB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.pager);
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter (FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = null;
if (i == 0)
{
fragment = new FragmentA();
}
if (i == 1)
{
fragment = new FragmentB();
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
public void setTabFragmentB(String t) {
TabFragmentB = t;
}
public String getTabFragmentB() {
return TabFragmentB;
}
}
FragmentA:
public class FragmentA extends Fragment {
EditText et;
Button bt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fraga, container, false);
et = (EditText)v.findViewById(R.id.edit1);
bt = (Button)v.findViewById(R.id.button1);
bt.setOnClickListener(Click);
return v;
}
OnClickListener Click = new OnClickListener(){
#Override
public void onClick(View v) {
String textPassToB = et.getText().toString();
String TabOfFragmentB = ((MainActivity)getActivity()).getTabFragmentB();
FragmentB fragmentB = (FragmentB)getActivity()
.getSupportFragmentManager()
.findFragmentByTag(TabOfFragmentB);
fragmentB.updateText(textPassToB);
}
};
}
FragmentB:
public class FragmentB extends Fragment {
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragb, container, false);
tv = (TextView)v.findViewById(R.id.text1);
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
return v;
}
public void updateText(String t){
tv.setText(t);
}
}
LogCat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at lmf.sample1.FragmentA$1.onClick(FragmentA.java:43)
at android.view.View.performClick(View.java:4212)
at android.view.View$PerformClick.run(View.java:17476)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Whenever I click the button on my first fragment, my app crashes. What the hell is the problem?
You could use Intents (register broadcast receiver in fragment B and send broadcasts from fragment A.
Use EventBus: https://github.com/greenrobot/EventBus. It's my favorite approach. Very convinient to use, easy communications between any components (Activity & Services, for example).
Steps to do:
First, create some class to represent event when your text changes:
public class TextChangedEvent {
public String newText;
public TextChangedEvent(String newText) {
this.newText = newText;
}
}
Then, in fragment A:
//when text changes
EventBus bus = EventBus.getDefault();
bus.post(new TextChangedEvent(newText));
in fragment B:
EventBus bus = EventBus.getDefault();
//Register to EventBus
#Override
public void onCreate(SavedInstanceState savedState) {
bus.register(this);
}
//catch Event from fragment A
public void onEvent(TextChangedEvent event) {
yourTextView.setText(event.newText);
}
Fragments have access to there parent Activity.
Therefore the simplest approach is to register a callback in the parent Activity.
Update: Submit cache added to MainActivity.
public class MainActivity extends FragmentActivity {
private OnButtonClicked mOnButtonClicked;
private String mSubmitCache;
public interface OnButtonClicked {
void submit(final String s);
}
public void setOnButtonClicked(final OnButtonClicked c) {
mOnButtonClicked = c;
// deliver cached string, if any
if (TextUtils.isEmpty(mSubmitCache) == false) {
c.submit(mSubmitCache);
}
}
public void buttonClicked(final String s) {
if (mOnButtonClicked == null) {
// if FragmentB doesn't exist jet, cache value
mSubmitCache = s;
return;
}
mOnButtonClicked.submit(s);
}
}
public class FragmentA extends Fragment implements OnClickListener {
private MainActivity mMain;
private Button mButton;
#Override public onAttach(Activity a) {
mMain = (MainActivity) a;
}
#Override public void onClick(View v) {
mMain.buttonClicked("send this to FragmentB.");
}
}
public class FragmentB extends Fragment implements MainActivity.OnButtonClicked {
private MainActivity mMain;
private TextView mTextView;
// Called when the fragment's activity has been created
// and this fragment's view hierarchy instantiated
#Override public void onActivityCreated(Bundle savedState) {
mMain = (MainActivity) getActivity();
mMain.setOnButtonClicked(this);
}
#Override void submit(final String s) {
mTextView.setText(s);
}
}
I use Mr. Rodion's solution above. But in addition, Android Studio asked me to add #Subscribe annotation before onEvent method.
Like this:
#Subscribe
public void onEvent(TextChangedEvent event) {
textView.setText(event.newText);
}
According to EventBus’ API:
Subscribers implement event handling methods (also called “subscriber methods”) that will be called when an event is posted. These are defined with the #Subscribe annotation. Please note that with EventBus 3 the method name can be chosen freely (no naming conventions like in EventBus 2).
FragmentB is not even created until you switch to it so fragmentB.updateText(textPassToB); gives you NullPointerException.
You will need to store the text from the EditText in your activity and later when (if) the FragmentB is created you will need to read value from it.

Categories

Resources