我一直在使用烤面包对每种方法进行一些测试,以显示用户单击的ListItem
的索引。直到我测试了要接收它的片段中的索引值为止,在这种情况下,我得到了以下错误:Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
。所以我不完全明白我在这里做错了什么。这就是价值从何处传递到的地方...
MainActivity(将索引值传递给Fragment)
@Override
public void onIndexSelected(int index) {
fm.beginTransaction().replace(R.id.content_Frame, new PlayerFragment()).commit();
player.setSong(index);
}
PlayerFragment(从活动中接收索引)
public void setSong(int songIndex){
currentSongIndex = songIndex;
Toast.makeText(getActivity(), "Index number : " + " " + currentSongIndex, Toast.LENGTH_SHORT).show();
// Commented out for testing
//playSong(currentSongIndex);
}
在这一点上,我假设索引值变为null,因此迫使应用程序崩溃。有什么办法吗?谢谢!
编辑
LogCat
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:103)
at android.widget.Toast.makeText(Toast.java:260)
at mymusic.fragments.PlayerFragment.setSong(PlayerFragment.java:263)
at com.music.mymusic.MainActivity.onIndexSelected(MainActivity.java:144)
at mymusic.fragments.LibraryFragment$2.onItemClick(LibraryFragment.java:80)
at android.widget.AdapterView.performItemClick(AdapterView.java:305)
at android.widget.AbsListView.performItemClick(AbsListView.java:1201)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3218)
at android.widget.AbsListView$4.run(AbsListView.java:4032)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
最佳答案
是PlayerFragment的玩家实例吗?如果是,则错误在于
@Override
public void onIndexSelected(int index) {
fm.beginTransaction().replace(R.id.content_Frame, new PlayerFragment()).commit();
player.setSong(index);
}
您创建新的PlayerFragment,而不使用旧的PlayerFragment。
错误不是由参数引起的,而是由getActivity()作为未附加到任何活动的片段引起的