Kurlicue Kurlicue - 1 year ago 93
Java Question

Android: showing dialogFrag on adapter gives NullPointerException

I'm trying to open a dialogFragment through an adapter, I've been all over the documentation and other questions, I can't find the problem. This is the full error line from the log

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.FragmentManager android.app.Activity.getFragmentManager()' on a null object reference

My adapter:

public class SubjectsAdapter extends RecyclerView.Adapter<SubjectsAdapter.ViewHolder> {

public List<String> items = new ArrayList<>();
public Activity mcontext;

public SubjectsAdapter(Activity context) {
assert mcontext != null;


//...usual adapter code here...

static int i;

class ViewHolder extends RecyclerView.ViewHolder{

public Button GridButton;

public ViewHolder(View itemView) {

GridButton = (Button) itemView.findViewById(R.id.grid_button);

GridButton.setText("Button " + i);

assert GridButton != null;
GridButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Fragment_Subject_Edit newFragment = Fragment_Subject_Edit.newInstance();
newFragment.show(mcontext.getFragmentManager(), "Title");

the DialogFragment:

public static Fragment_Subject_Edit newInstance() {

return new Fragment_Subject_Edit();
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

LayoutInflater inflater = getActivity().getLayoutInflater();

// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.fragment_subject_edit, null));

return builder.create();

Ok so what am I missing here to show my DialogFragment when I click in the GridButton?

Answer Source

At this line:

newFragment.show(mcontext.getFragmentManager(), "Title");

You are asking to mcontext for the fragmentManager and your problem is that at that point mcontext is null. Like George said, unless you really need it, just set the context straight ahead instead of its parent, thats a potential cause of the Null.