javaandroidparse-platformnullpointerexceptionparse-android-sdk

Activity returning null and producing NullPointerException even though I implemented it


I have a class extending ParseQUeryAdapter so I can use the notifyDataSetChanged feature. The adapter class is called mainAdapter. Here's my notifyDataSetCHanged method in the mainAdapter:

@Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();
    MainActivity mainActivity = new MainActivity();
    mainActivity.getItems();
}

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 if so that I can see if adapter was null. But it still crashes. According to the debugger, it says in green after getting to the if 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()


Solution

  • 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.

    IE:

    private MainActivity activity;
    public void setup(MainActivity activity){ this.activity = activity;}
    
    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
        if(activity != null){
            activity.getItems();
        }
    }