简体   繁体   中英

Android MVP - loosing view reference in presenter “NullPointerException… null object reference”

I'm using MVP in my demo project, in my View(fragment) I have two editTexts(case number and user name) and button.

On Button click I want to insert that Case object to database. So, firstly check if is there case with same number. And if it's false, I'm gonna save it to database and notify user that case is saved in database. Otherwise, just sending back message, that operation is failed and to try again with different number.

So object goes through the layers, View > Presenter > Model > Repository. In Repository checking out conditions and sending a message back to view, trough same layers but vice versa (Repository>Model>Presenter>View).

I Log.d all classes for errors and everything is fine. But when it comes back to Presenter I'm getting "on a null object reference" for my view.

method in my Presenter called from Model where I gets an error...

public void sameCaseNumberMessage(String string){

    Log.d(TAG, "message from repository" + string);
    view.showToastMessage(string); //but here, view is  on a null object reference
}

In my View ...

@Inject
BottomFragmentContract.Presenter presenter;

...

@Override
public void onResume() {
    super.onResume();

    presenter.setView(this);
}

...

In my Presenter ...

@Nullable
private BottomFragmentContract.View view;

...

@Override
public void setView(BottomFragmentContract.View view) {

    this.view = view;
    Log.d(TAG, "Hashcode is fine : " + this.view.toString());
}

...

I'm guessing you are injecting your presenter into your model, in which case, check that it is the same instance as the one held (and bound) by your view.

In short. I think the model is holding a reference to a new instance of your presenter which has not had the view set.

Either mark the presenter as singleton or (better for testing) pass to the model as a constructor parameter.

I would also note that generally it is a good idea to only hold strong references in one direction.. IE:

  • View (strong)-> Presenter (strong)-> Model (strong)-> Repository
  • View <-(weak) Presenter <-(weak) Model <-(weak) Repository

.. so.. strong ownership, weak listeners ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM