AbAppletic AbAppletic - 3 months ago 5x
Java Question

Activity returning null and producing NullPointerException even though I implemented it

I have a class extending ParseQUeryAdapter so I can use the

feature. The adapter class is called
Here's my notifyDataSetCHanged method in the mainAdapter:

public void notifyDataSetChanged() {
MainActivity mainActivity = new MainActivity();

Here's my getItems() method in MainActivity:

public void getItems(){
if(adapter == null){
Toast.makeText(MainActivity.this, "null", Toast.LENGTH_SHORT).show();

The app crashes on loading. As you can see, I planted an
so that I can see if
was null. But it still crashes.
According to the debugger, it says in green after getting to the
line, "adapter:null". However, I have this in onCreate():

adapter = new mainAdapter(this);

And I declared it:

mainAdapter adapter

Is there a method I can put in that will solve my issue? Although I am implementing the class, why is it still null? I clearly stated that
adapter = new mainAdapter()


If you want to reference an existing activity then you have to pass the activity object to where you want to use it (or use getContext or getActivity when your in a class that has that available).

One of the things you can do is create a method that passes the MainActivity object into your ParseQUeryAdapter. Then when you are calling stuff in your adapter do: activityObject.whatevermethodyouwantocallontheactiviy() be shure to error check the activity object first though.


private MainActivity activity;
public void setup(MainActivity activity){ this.activity = activity;}

public void notifyDataSetChanged() {
    if(activity != null){