当前,我正在使用Android上的RecyclerView
来显示从Firebase获得的一些数据。我正在使用MVC设计模式,因此必须将一些数据从视图(actViewDB
)传递到控制器(Controller
),然后传递给Model类(DataModel
)。不幸的是,我总是遇到这样的Java NullPointerException
错误
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ryzen.pajakcerdas, PID: 3138
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ryzen.pajakcerdas/com.example.ryzen.pajakcerdas.actViewDB}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.ryzen.pajakcerdas.dataAdapter.setNotes(java.util.List)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.ryzen.pajakcerdas.dataAdapter.setNotes(java.util.List)' on a null object reference
at com.example.ryzen.pajakcerdas.actViewDB.showModelList(actViewDB.java:22)
这是代码
actViewDB.java
public class actViewDB extends AppCompatActivity {
private List<DataModel> modelList;
private RecyclerView rc;
private dataAdapter adapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_viewdatabase);
rc = findViewById(R.id.recycler_view);
rc.setLayoutManager(new LinearLayoutManager(this));
rc.setHasFixedSize(true);
modelList = new ArrayList<>();
}
private void showModelList() {
modelList.add(new DataModel("a", 2, 1, 3));
adapter.setNotes(modelList);
rc.setAdapter(adapter);
}
}
为什么会这样?很抱歉,如果已经提出此问题,从上周开始我已经多次搜索了答案,但仍然无法解决。我发现最接近的问题是这个android: recycler view adapter,但仍然不能解决我的问题。
答案 0 :(得分:0)
您必须初始化adapter
,然后调用其方法
adapter = new DataAdapter();