Niana Niana - 1 year ago 183
Android Question

Replace fragment from recycler adapter

I am working on an android app changing a listview to a recycler view.


Using an example project, I handle my clicks to the recylcer in the adapter view.
However, from this adapter, I am having a very had time calling a new fragment.

itemView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// fragmentManager = getFragmentManager();
// FragmentManager fragmentManager = ((Activity) context).getFragmentManager();

// FragmentManager manager = this.getSupportFragmentManager();
// FragmentManager manager= getContext().getFragmentManager();

// FragmentManager fragmentManager = newsAdapter().getActivity().getFragmentManager();
// getActivity().getFragmentManager();
Log.i("RecyclerViewItemClic", String.valueOf(getLayoutPosition()));

Log.i("RecyclerViewItemClic", personName.getText().toString());
String idnum = String.valueOf(personName.getText());
Log.i("RecyclerViewItemClic", idnum);
Log.i("RecyclerViewItemClic", personAge.getText().toString());

if (personName.getText().toString() .equals("1")) {
,new numNumbersFrag())

((FragmentActivity) context).getFragmentManager().beginTransaction()
.replace(, new numNumbersFrag())


The above is the code I attempted resulting in the error

Attempt to invoke virtual method '' on a
null object

I also get the same error if I try to use getSupportFragmentManager(), or I import fragment instead of the version4.

Any help would be appreciated.

Thank you

Answer Source


((FragmentActivity) context).getFragmentManager().beginTransaction()
                    .replace(, new numNumbersFrag())


((FragmentActivity) view.getContext()).getFragmentManager().beginTransaction()
                    .replace(, new numNumbersFrag())

because, in

public void onClick(View view)

view.getContext() will return context which will not be null.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download