我想从MainFragment.java
MainActivity.java
的方法
我在这里尝试过:
MainActivity.java
MainFragment mainFragment;
........
mainFragment = new MainFragment();
.........
mainFragment.deom();
MainFragment.java
public void deom() {
Toast.makeText(getActivity(), "Demo", Toast.LENGTH_LONG).show();
}
日志
java.lang.NullPointerException
at android.widget.Toast.<init>(Toast.java:93)
at android.widget.Toast.makeText(Toast.java:241)
at com.example.x.b(Unknown Source)
at com.example.MainActivity.onOptionsItemSelected(Unknown Source)
at android.app.Activity.onMenuItemSelected(Activity.java:2633)
at android.support.v4.b.ao.onMenuItemSelected(Unknown Source)
at android.support.v7.app.t.onMenuItemSelected(Unknown Source)
at android.support.v7.view.n.onMenuItemSelected(Unknown Source)
at android.support.v7.view.n.onMenuItemSelected(Unknown Source)
我可以知道我在做错了吗?我错过了什么?我为什么要获得NPE。
答案 0 :(得分:1)
您必须初始化MainFargment。
MainFragment mainFragment = (MainFragment) getFragmentManager.findFragmentById(R.id.theId);
mainFragment.deom();