[英]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. 我在演示项目中使用MVP,在View(片段)中,我有两个editTexts(案例编号和用户名)和按钮。
On Button click I want to insert that Case object to database. 在“按钮”上,单击“我想将该Case对象插入数据库”。 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. 因此,对象将遍历各层,依次单击“视图”>“ Presenter”>“模型”>“存储库”。 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. 我Log.d所有类的错误,一切都很好。 But when it comes back to Presenter I'm getting "on a null object reference" for my view.
但是当回到Presenter时,我的观点是“基于空对象引用”。
method in my Presenter called from Model where I gets an error... 从Model调用的Presenter中的方法出现错误...
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: 我还要指出,通常最好只在一个方向上保留强引用。.IE:
.. so.. strong ownership, weak listeners ;-) ..如此..强所有权,弱听者;-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.