Android Question

How to send data from activity and get it in Fragment

Hi guys I'm starting in the Android world and as the question suggests, I'm stuck there. I had made some researches and tried some of the answers posted in this community but I can not figure it out.

I have an activity that displays a list of contacts an every item in the list navigate to a detail view once is tapped. My goal is passed de item id to perform a request and display the response.

Here is my attempt:

public class PersonDetailActivity extends AppCompatActivity {

protected void onCreate(Bundle savedInstanceState) {

Intent intent = getIntent();

// This variables have the right value
String personName = intent.getStringExtra("personName");
String personID = intent.getStringExtra("personID");

Bundle bundle = new Bundle();
// I'm trying to send this variable to make a request later
bundle.putString("personID", personID);
// Set Fragment Arguments
PersonDetailFragment fragment = new PersonDetailFragment();


public class PersonDetailFragment extends Fragment {

public PersonDetailFragment() {
// Required empty public constructor

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

// This throw me a NPE
String data = null;
if (getArguments() != null) {
data = getArguments().getString("personID");
final View rootView = inflater.inflate(R.layout.person_detail_list, container, false);
return rootView;


Thanks in advance guys

Answer Source

Try to setup listener for your items like this:

public void onItemClick(ItemView itemView) { 
     personId = itemView.getPersonId(); 
     Fragment detailFragment = PersonDetailFragment.newInstance(personId); 
               .replace(*your_fragment_container*, detailFragment)

Next step is fragment initializing. It's good practice to use static method for fragment creation. Write this method in appropriate fragment class:

public static PersonDetailFragment newInstance(String personId) {
     Bundle args = new Bundle();
     args.putString("personId", personId);
     PersonDetailFragment fragment = new PersonDetailFragment();
     return fragment;