android – Attempt to invoke virtual method 'void com.firebase.ui.database.FirebaseRecyclerAdapter.startListening()' on a null object reference-ThrowExceptions

Exception or error:

I’m creating my first android studio app, where a user can post diary entries. The posting works (gets uploaded onto a real-time database in Firebase) and I am now trying to display these posts in the main activity page, in a card layout using recycler view. Sadly, I am getting this error when I run my app. I’ll attach my

MainActivity.java

public class MainActivity extends AppCompatActivity {

private RecyclerView mDiaryList;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseRecyclerAdapter<Journal, JournalViewHolder> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mDatabase = FirebaseDatabase.getInstance().getReference().child("Journal");

    mDiaryList = (RecyclerView) findViewById(R.id.diary_list);
    mDiaryList.setLayoutManager(new LinearLayoutManager(this));
    mDiaryList.setHasFixedSize(true);


    mDatabase = FirebaseDatabase.getInstance().getReference().child("Journal");

    DatabaseReference personRef = FirebaseDatabase.getInstance().getReference().child("Journal");
    Query query = personRef.orderByKey();

    mDatabase.keepSynced(true);
    FirebaseRecyclerOptions<Journal> options =
            new FirebaseRecyclerOptions.Builder<Journal>()
                    .setQuery(query, Journal.class)
                    .build();


    FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Journal, JournalViewHolder>(options) {
        @NonNull
        @Override
        public JournalViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.diary_list, parent, true);

            return new JournalViewHolder(view);
        }

        //
        @Override
        protected void onBindViewHolder(@NonNull JournalViewHolder holder, int position, @NonNull Journal model) {

            final String post_key = getRef(position).getKey().toString();
            holder.setTitle(model.getTitle());
            holder.setDesc(model.getDesc());

        }
    };
    mDiaryList.setAdapter(adapter);

}


@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}

//we need a viewholder to set up the Recycler  view.
public static class JournalViewHolder extends RecyclerView.ViewHolder {
    View mView;

    public JournalViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setTitle(String title) {
        TextView post_title = mView.findViewById(R.id.post_title);
        post_title.setText(title);
    }

    public void setDesc(String desc) {
        TextView post_desc = mView.findViewById(R.id.post_desc);
        post_desc.setText(desc);
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.options:
            // Red item was selected
            startActivity(new Intent(MainActivity.this, ProfileActivity.class));
            return true;

        case R.id.add_post:
            //add_post was selected
            startActivity(new Intent(MainActivity.this, PostActivity.class));
        default:
            return super.onOptionsItemSelected(item);
    }
}

Journal.java

public class Journal {
private String title, desc, uid;
public Journal(String title, String desc, String uid) {
    this.title = title;
    this.desc = desc;
    this.uid = uid;
}
public Journal() {
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDesc() {
    return desc;
}

public void setDesc(String desc) {
    this.desc = desc;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}
How to solve:
public class MainActivity extends AppCompatActivity {

private RecyclerView mDiaryList;
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseRecyclerAdapter<Journal, JournalViewHolder> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mDatabase = FirebaseDatabase.getInstance().getReference().child("Journal");

    mDiaryList = (RecyclerView) findViewById(R.id.diary_list);
    mDiaryList.setLayoutManager(new LinearLayoutManager(this));
    mDiaryList.setHasFixedSize(true);

    //This is unnecessary.
    mDatabase = FirebaseDatabase.getInstance().getReference().child("Journal");

    //In my opinion this is unnecessary too. You already have a DatabaseReference object you declared as local variable.
    DatabaseReference personRef = FirebaseDatabase.getInstance().getReference().child("Journal");

    //Change this line to Query query = mDatabase.orderByKey();
    Query query = personRef.orderByKey();

    mDatabase.keepSynced(true);
    FirebaseRecyclerOptions<Journal> options =
            new FirebaseRecyclerOptions.Builder<Journal>()
                    .setQuery(query, Journal.class)
                    .build();

    //Instantiate your adapter here
    adapter = new FirebaseRecyclerAdapter<Journal, JournalViewHolder>(options) {
        @NonNull
        @Override
        public JournalViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.diary_list, parent, true);

            return new JournalViewHolder(view);
        }

        //
        @Override
        protected void onBindViewHolder(@NonNull JournalViewHolder holder, int position, @NonNull Journal model) {

            final String post_key = getRef(position).getKey().toString();
            holder.setTitle(model.getTitle());
            holder.setDesc(model.getDesc());

        }
    };
    mDiaryList.setAdapter(adapter);

}


@Override
protected void onStart() {
    super.onStart();
    adapter.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    adapter.stopListening();
}

//we need a viewholder to set up the Recycler  view.
public static class JournalViewHolder extends RecyclerView.ViewHolder {
    View mView;

    public JournalViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setTitle(String title) {
        TextView post_title = mView.findViewById(R.id.post_title);
        post_title.setText(title);
    }

    public void setDesc(String desc) {
        TextView post_desc = mView.findViewById(R.id.post_desc);
        post_desc.setText(desc);
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.options:
            // Red item was selected
            startActivity(new Intent(MainActivity.this, ProfileActivity.class));
            return true;

        case R.id.add_post:
            //add_post was selected
            startActivity(new Intent(MainActivity.this, PostActivity.class));
        default:
            return super.onOptionsItemSelected(item);
    }
}

###

You’re locally defining a variable called adapter in onCreate that’s shadowning the member variable adapter at the class level. You should remove the type from its assignment to make sure that you’re assigning to the member variable instead of a local variable:

// Remove "FirebaseRecyclerAdapter" from this line.
adapter = new FirebaseRecyclerAdapter<>(options) ...

Leave a Reply

Your email address will not be published. Required fields are marked *