Search code examples
android-activityfragmentonresume

Called OnResume Method From Activity to Fragment is not Updating Variables


I have an issue which I couldn't figure out for hours,

I have a fragments inside an activity, and sometimes I call the fragment with the codes below:

        newsFeedFragment fragment = new newsFeedFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.hide(getSupportFragmentManager().findFragmentById(R.id.fragment_container));
        fragmentTransaction.hide(getSupportFragmentManager().findFragmentByTag("notifications_fragment"));
        fragmentTransaction.show(getSupportFragmentManager().findFragmentByTag("news_feed_fragment"));
        fragmentTransaction.addToBackStack(null);
        fragment.onResume();
        fragmentTransaction.commit();

As the onResume is not called while showing the fragments I use "fragment.onResume();" in the code below. And when the fragment is shown, the onResume is called. However, I try to update a variable in the onResume method, but it is not updated with the code below. When ever the onResume is called, I see "1" as the result in the log, however I was expecting it to increase by 1 every time. Is there a way to make it work?

int refreshNotificationVar = 0; //in the main class

 @Override
    public void onResume(){
        super.onResume();

        refreshNotificationVar = refreshNotificationVar + 1;

        System.out.println(refreshNotificationVar);

    }

Solution

  • You cannot rely on instance variables in case of onPause and onResume; you can rely on static variables to some extent; you can use onSaveInstanceState; or use a Singleton class to store variable values; or store in shared preferences; or maybe store in a database depending on your needs. In your case, I would use a Singleton class to store the values and get/set them in onPause/onResume.