-1

i want to recreate (reload) a fragment when i click on a OptionsItem from a Drawer Navigation Activity

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

        switch (id) {
            case R.id.fr:
                LocaleHelper.setLocale(getBaseContext(), "Fr");
                if(getVisibleFragment().isAdded()){
                    getVisibleFragment().getActivity().recreate();
                }
                return true;
            case R.id.ar:
                LocaleHelper.setLocale(getBaseContext(), "Ar");
                if(getVisibleFragment().isAdded()){
                    getVisibleFragment().getActivity().recreate();
                }
                return true;
            case R.id.en:
                LocaleHelper.setLocale(getBaseContext(), "En");
                if(getVisibleFragment().isAdded()){
                    getVisibleFragment().getActivity().recreate();
                }
                return true;
            case R.id.es:
                LocaleHelper.setLocale(getBaseContext(), "Es");
                if(getVisibleFragment().isAdded()){
                    getVisibleFragment().getActivity().recreate();
                }
                return true;
        }

    return super.onOptionsItemSelected(item);
}

when i click on an Option i get this error :

java.lang.IllegalStateException: Fragment NewsMainFragment{9a39a2f} not attached to a context

how can i achieve this properly ?

Umair
  • 6,366
  • 15
  • 42
  • 50
Anass Boukalane
  • 539
  • 10
  • 26
  • As far my knowledge says you can not recreate a fragment or activity!, You can refer [Here](https://stackoverflow.com/questions/28672883/java-lang-illegalstateexception-fragment-not-attached-to-activity) Recreation of fragments can be accessed via newInstrance() method. `getSupportFragmentManager().beginTransaction() .replace(R.id.container, YourFragment.newInstance()).commit();` – Hector Morris Jul 04 '18 at 13:01

1 Answers1

0

In this code:

getVisibleFragment().getActivity().recreate();

you recreate the whole activity, not the fragment. So, if the fragment you want recreate is in the activity where the method onOptionsItemSelected(MenuItem item) placed, you just recreate current activity, so you can call just:

recreate();

instead of your code.

But if you want just to recreate the fragment without recreating whole activity, you can put the code, where you initialize all views of your fragment, in separate public method and call them, like:

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

    public void updateUi() {
        // Your code
    }

and then:

case R.id.fr:
                LocaleHelper.setLocale(getBaseContext(), "Fr");
                if(getVisibleFragment().isAdded()){
                    ((YourFragment)getVisibleFragment()).updateUi();
                }
                return true;
Alexander Tumanin
  • 1,638
  • 2
  • 23
  • 37