Ricardo aprendizfc Ordoez Delg Ricardo aprendizfc Ordoez Delg - 10 months ago 43
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 {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(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();
fragment.setArguments(bundle);

setContentView(R.layout.persons);
}
}

public class PersonDetailFragment extends Fragment {


public PersonDetailFragment() {
// Required empty public constructor
}


@Override
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); 
     getSupportFragmentManager()
               .beginTransaction()
               .replace(*your_fragment_container*, detailFragment)
               .commit();
}

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();
     fragment.setArguments(args);
     return fragment;
}