Niana Niana - 24 days ago 8
Android Question

Replace fragment from recycler adapter

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

Problem

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() {
@Override
public void onClick(View view) {
// android.app.FragmentManager 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")) {
/*
fragmentManager.beginTransaction()
.replace(R.id.content_frame
,new numNumbersFrag())
.commit();


*/
((FragmentActivity) context).getFragmentManager().beginTransaction()
.replace(R.id.content_frame, new numNumbersFrag())
.commit();


}
}


The above is the code I attempted resulting in the error


Attempt to invoke virtual method 'android.app.FragmentManager
android.support.v4.app.FragmentActivity.getFragmentManager()' 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

change

((FragmentActivity) context).getFragmentManager().beginTransaction()
                    .replace(R.id.content_frame, new numNumbersFrag())
                    .commit();

to

((FragmentActivity) view.getContext()).getFragmentManager().beginTransaction()
                    .replace(R.id.content_frame, new numNumbersFrag())
                    .commit();

because, in

public void onClick(View view)

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

Thanks,