-1

I want to add a fragment to the main activity, but it shows me an error if i insert the fragment's java file object as the second parameter for the add method. I imported android.support.v4.app.Fragment and it didn't help.

Here is my code :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FragmentManager managerFragment;
    managerFragment = getFragmentManager();
    FragmentTransaction tranzactieFragment = managerFragment.beginTransaction();
    frg_jos FragJos = new frg_jos();
    tranzactieFragment.add(R.id.frg,FragJos);
}
Zoe stands with Ukraine
  • 25,310
  • 18
  • 114
  • 149
  • 1
    I don't see you are doing .commit after adding the fragment https://developer.android.com/reference/android/app/FragmentTransaction.html#commit() – Cristian Gomez May 14 '18 at 20:18
  • 2
    As already pointed out, you’re missing a `.commit()` to your transaction. But also please, `frg_jos` is a very bad name for a Java/Kotlin class. It works, and it’s supported, but the _platform convention_ is to use `CamelCaseForClasses`. It will make your code easier to read for the rest of the world, which is helpful, for example, in this case where you need to share it. ;) – Martin Marconcini May 14 '18 at 20:22

2 Answers2

1

I would write it like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {        
         getSupportFragmentManager()
             .beginTransaction()
             .add(R.id.frg, FragJos.newInstance())
             .commit(); 
    }
}

and I would add

public static FragJos newInstance() {
    return new FragJos();
}

To your fragment. This is what Android/Google recommends. Don’t do new XXXFragment() directly, nor pass parameters via Fragment Constructor (for restore state reasons).

Martin Marconcini
  • 25,191
  • 19
  • 103
  • 139
0

Make it

    if (savedInstanceState == null) { 
       FragmentManager managerFragment;
       managerFragment = getSupportFragmentManager();
       FragmentTransaction tranzactieFragment = managerFragment.beginTransaction();
       frg_jos FragJos = new frg_jos();
       tranzactieFragment.replace(R.id.frg,FragJos);
       tranzactieFragment.commit();
    }
Álysson Alexandre
  • 1,067
  • 1
  • 7
  • 11
  • 1
    If you are going to use `add` then you need to ensure it’s protected from automatic reconstruction of saved state… so it needs to be inside an `if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction().add(R.id.frg, FragJos.newInstance()).commit(); }`. That’s code I’d expect to see. – Martin Marconcini May 14 '18 at 20:24
  • (I didn’t downvote, but I upvoted again, because your answer, albeit incomplete, does answer the question). – Martin Marconcini May 14 '18 at 20:27