1

I have 2 activities MainActivity and DetailActivity, if I click in the ListView in MainActivity will intent to DetailActivity with content "id", in DetailActivity I have 2 fragment (TabLayout-ViewPager).

My question is: How can fragment get "id" from that intent above???

Robert
  • 10,403
  • 14
  • 67
  • 117
Ahmad
  • 59
  • 1
  • 7
  • 1
    `getActivity().getIntent()`? But you probably should pass the intent's data "down" to the Fragment, rather than "reach up" for it. – OneCricketeer Apr 29 '16 at 15:03

3 Answers3

1

Fragment in android ,If Android decides to recreate your Fragment later, it's going to call the no-argument constructor of your fragment. So overloading the constructor is not a solution.for more detail please read this stack overflow answer

private int mId;
private static final String ID = "id";
public static DetailsFragment newInstance(int id) {
    DetailsFragment fragment = new DetailsFragment();
    Bundle args = new Bundle();
    args.putInt(ID, id);

    fragment.setArguments(args);
    return fragment;
}

get values in oncreate method

@Override

     public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null)
//mId is variable which contain (YourActivity)MainActivity value.you can use in fragment.
                mId = getArguments().getInt(ID);


        }

//call in your YourActivity(MainActivity) in oncreate method

 int id = yourid;
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,DetailFragment.newInstance(id)).commit();
Community
  • 1
  • 1
Muhammad Waleed
  • 2,517
  • 4
  • 27
  • 75
  • good answer, but a bit more descriptive text to explain your answer should help get your answer accepted – CSmith Apr 29 '16 at 18:46
  • java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference – Ahmad May 01 '16 at 14:45
0

from Android Developer's Fragment Page

DetailsFragment f = new DetailsFragment();

// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);

// add fragment to the fragment manager's stack
luckyhandler
  • 10,651
  • 3
  • 47
  • 64
0

Like @cricket_007 says, create a factory method in your fragment and pass the data through bundle arguments consider the example below

public static YourFragment newInstance(Bundle args) {
      Yourfragment fragment = new YourFragment();
      Bundle bundle = args;
      // Or if your args is a variable data for example a string
      // use Bundle bundle = new Bundle(); bundle.putString("extra_name",value);
        // Now set the fragment arguments
        fragment.setArguments(bundle);
     return fragment;
}

And now anywhere in your fragment you can do

Bundle args = getArguments();
// and access your extra by args.getString("extra_name"); ...
thunder413
  • 585
  • 3
  • 10