0

i am having trouble trying to figure out how to pass extra information into a fragment.

I want to pass in both a string and int.

I have managed to get this working with intents on another page and buttons using onClick and intent.putExtra before the getSupportFrag part. However, i have tried to do the same approach for the nav drawer with no luck. It actually opens an unrelated page for some reason.

Is there anyway to get this working with keeping the testStr and testInt parts in the fragment activity?

The fragment recieving the extra data uses

testStr = activity.getIntent().getStringExtra("test str");
testInt = activity.getIntent().getIntExtra("test int", 0);

The main activity

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {

    case R.id.nav_test1:
        //Used in a fragment activity on buttons and works with OnClick
        Intent intent = this.getIntent();
        intent.putExtra("test str", "test value");
        intent.putExtra("test int", 0);
        getSupportFragmentManager().beginTransaction().
        replace(R.id.fragment_container,
                    new LevelX()).addToBackStack(null).commit();
        //end

  }
  drawer.closeDrawer(GravityCompat.START);
  return true;
}
Sahdeep Singh
  • 1,342
  • 1
  • 13
  • 34

1 Answers1

0

You should use Bundle with Fragment.setArguments. Add required parameters to the Bundle object and add it to the fragment. Inside the fragment call getArguments() to get the Bundle. Please see the exact usage sample here: How to use setArguments() and getArguments() methods in Fragments?

Pavel B.
  • 805
  • 10
  • 13