Skip to content
Advertisement

Android NullPointer Attempt to invoke virtual method ‘boolean java.util.ArrayList.add(java.lang.Object)’ on a null object reference

I’m getting this error: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference and just to make it clear is that I know others with the same issue have asked the same question and I have read the solutions which are usually that you have to instantiate your ArrayList which however I am obviously doing but still receiving this error, so is there anyone that knows how I would be able to correct this error?

AddListActivity.java

public class AddListActivity extends AppCompatActivity {

private RecyclerView listsRecyclerView;
RecyclerView.LayoutManager layoutManager;
ListsRecyclerViewAdapter listsRecyclerViewAdapter;
EditText listEditText;
View addListButton;
View backButton;
//Instantiating the ArrayList right here
ArrayList<Category> categories = new ArrayList<>();

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

    listsRecyclerView = findViewById(R.id.listsRecyclerView);
    listEditText = findViewById(R.id.listEditText);
    addListButton = findViewById(R.id.addListButton);
    backButton = findViewById(R.id.backButton);

    Intent intent = getIntent();
    categories = intent.getParcelableExtra(MainActivity.KEY_NAME);

    initRecyclerView();

    listEditText.setOnEditorActionListener(editorActionListener);

    addListButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {onAddListClick();}
    });

    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {finish();}
    });
}

private void initRecyclerView()
{
    layoutManager = new LinearLayoutManager(this);
    listsRecyclerView.setLayoutManager(layoutManager);
    listsRecyclerViewAdapter = new ListsRecyclerViewAdapter(categories);
    listsRecyclerView.setAdapter(listsRecyclerViewAdapter);
    new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(listsRecyclerView);

    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
    dividerItemDecoration.setDrawable(getResources().getDrawable(R.drawable.divider_line, null));
    listsRecyclerView.addItemDecoration(dividerItemDecoration);

}

private TextView.OnEditorActionListener editorActionListener = new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        onAddListClick();

        return true;
    }
};

private void onAddListClick()
{
    final DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("CategoryList");

    final String text = listEditText.getText().toString();

    myRef.orderByValue().equalTo(text).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists())
            {
                Toast.makeText(AddListActivity.this, "This list already exists", Toast.LENGTH_SHORT).show();
            } else
                {
                    if (text.trim().length() > 0)
                    {

                        String autoGeneratedId = myRef.push().getKey();
                        //This following line is where I am getting the error!
                        categories.add(new Category(text, autoGeneratedId));

                        listsRecyclerViewAdapter.notifyDataSetChanged();

                        listEditText.getText().clear();

                        myRef.child(autoGeneratedId).setValue(text);

                        Toast.makeText(AddListActivity.this, "New list added", Toast.LENGTH_SHORT).show();
                        finish();
                    } else
                    {
                        Toast.makeText(AddListActivity.this, "You did not enter any text", Toast.LENGTH_SHORT).show();
                    }
                }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
        return false;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        final DatabaseReference myRef = FirebaseDatabase.getInstance().getReference("CategoryList");

        String categoryId = categories.get(viewHolder.getAdapterPosition()).getCategoryId();

        categories.remove(viewHolder.getAdapterPosition());

        myRef.child(categoryId).removeValue();

        listsRecyclerViewAdapter.notifyDataSetChanged();
    }
};
}

Runtime error:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.testapplication, PID: 12703
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
    at com.example.testapplication.AddListActivity$4.onDataChange(AddListActivity.java:111)
    at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@19.2.1:179)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
    at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
    at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at android.app.ActivityThread.main(ActivityThread.java:8669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:571)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1135)

Edit:

How I send it from MainActivity.java:

Intent intent = new Intent(this, AddListActivity.class);
intent.putExtra(KEY_NAME, categories);
startActivity(intent);

Advertisement

Answer

Solved by using putParcelableArrayListExtra() instead of putExtra() and getParcelableArrayListExtra() instead of getParcelableExtra() since I am using an ArrayList.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement