我正在使用MVP。我的活动包含一个片段。我正在初始化,然后将Presenter设置为在Create-Activity中创建方法,如下所示。
public class MainActivity extends AppCompatActivity {
private StashPresenter stashPresenter;
private MainFragment mainFragment;
FragmentManager fm;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App.getInstance().getAppComponent().inject(this);
setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
fm.beginTransaction()
.add(R.id.fragment_container, MainFragment.newInstance(),"mainFragment")
.commitNow();
mainFragment = (MainFragment) fm.findFragmentById(R.id.fragment_container);
stashPresenter = new StashPresenter(mainFragment);
mainFragment.setPresenter(stashPresenter);
}
在我的mainFrgament类中,我在setPresenterFunction中设置了Presenter,如下所示。
public class MainFragment extends Fragment implements
StashContract.PublishToView {
public StashContract.ToPresenter forwardInteraction;
public void setPresenter(StashContract.ToPresenter forwardInteraction)
{
this.forwardInteraction = forwardInteraction;
}
有时在执行搜索操作时,如下面的代码所示,在mainFragment的OnCreateView中,我收到错误说我的转发 "尝试在空对象引用上调用接口方法"
有时我会收到此错误,有时我却没有。我不明白为什么会发生这种情况
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
unbinder = ButterKnife.bind(this, view);
searchView.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
progressBar.setVisibility(View.VISIBLE);
forwardInteraction.searchButtonClick(actionId, searchView.getText().toString());
return true;
}
return false;
});
String[] artistNames = getResources().getStringArray(R.array.artistNamesSuggestion);
ArrayAdapter<String> adapterArtist = new ArrayAdapter<>(getActivity().getApplicationContext(), R.layout.fragment_main, R.id.search_phrase, artistNames);
searchView.setAdapter(adapterArtist);
searchView.setThreshold(1);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new SpaceItemDecoration(space, space, space, space));
return view;
}
答案 0 :(得分:0)
<强>解决方案强>
在&#34; onCreateView&#34;片段的方法,只初始化视图。
将其余代码移到&#34; onResume&#34;方法
错误原因
检查此图片
如您所见,&#34; onCreateView&#34;当你在&#34; onCreate&#34;活动中的方法。
在您的代码的当前状态中,有时您可能会在初始化之前尝试使用演示者。
因此,请将您的演示文稿设置为&#34; onCreate&#34;您的活动方法,并将其用于&#34; onStart&#34;或&#34; onResume&#34;你的片段。
您可以查看此project以更多地了解MVP架构。