我正在尝试在项目的活动中声明RecyclerView。当我切换到此活动时,项目崩溃。 尝试实例化RecyclerView时出现NullPointerException,请参见以下错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.marykate.marykatefordefyp, PID: 13490
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.marykate.marykatefordefyp/com.example.marykate.marykatefordefyp.ViewFavourites}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2264)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2313)
at android.app.ActivityThread.access$1100(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5336)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.marykate.marykatefordefyp.ViewFavourites.onCreate(ViewFavourites.java:54)
at android.app.Activity.performCreate(Activity.java:5302)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2228
我在此网站上也曾看过类似的问题,但没有一个正在寻找答案。我没有引用错误的xml文件,而是在调用正确的RecyclerView。 请参阅下面的代码:
RecyclerView eventsListview;
List<Favourite> favourites = new ArrayList<>();
FaveAdapter adapter = new FaveAdapter(this, R.layout.eventlist_layout, favourites);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_favourites);
eventsListview.findViewById(R.id.eventsListview1); //the line causing an error
有人知道这是什么原因吗?
答案 0 :(得分:1)
eventsListview = (RecyclerView)findViewById(R.id.eventsListview1);