How to invoke a fragment from another activity?

0

I have MainActivity 2 fragments, when I go to SecondActivity from there I want to go back to the fragment2 of MainActivity by passing some data to it.

But I get an overflow error trying to get the fragment from MainActivity:

getSupportFragmentManager()
                    .getFragments()
                    .get(1)

The fragment Manager has no fragment.

Any suggestions? Thanks.

    
asked by JhonArias 13.09.2018 в 23:01
source

2 answers

0

When returning from one Activity to another it is to restart the activity so the fragmentManager does not have any fragment.

For this, from the second activity, it is necessary to pass to the intent some identifier (a name or a number) and then from the onCreate of the activity invoke the fragment that you want to show:

Intent intentMain = new Intent(SecondActivity.this, MainActivity.class);
intentMain.putExtras("previousFragment", 2); 
startActivity(intentMain);

And from the onCreate of MainActivity:

int previousFragment = getIntent().getExtras("previousFragment");
if(previousFragment == 2) {
    // llamar al fragment
    SegundoFragment fragment = SegundoFragment.newInstance();
    FragmentManager ft = getSupportFragmentManager();
    ft.beginTransaction().replace(R.id.fragment_container, 
    fragment).commit();
}
    
answered by 13.09.2018 в 23:25
0

I could not do it the way I was thinking, I had to add a listener in the fragment, in MainActivity implement that listener and use:

 viewPager.setCurrentItem(1); //On MainActivity

and overwrite the onAttach () of the Fragment2 to capture the listener and in the onViewCreated () invoke the listener passing (this) as a parameter, from MainActivity I capture the event, get the data from the bundary and invoke the Fragment2 method by passing on the data.

I do not know if it's the best solution.

    
answered by 14.09.2018 в 14:58