【发布时间】:2021-09-21 17:32:22
【问题描述】:
首先,我是这方面的绝对初学者,如果这是一个愚蠢的错误,我很抱歉。但是我总是遇到这个错误
java.lang.NullPointerException:尝试在 com.example.loginregister.ui 的空对象引用上调用虚拟方法“void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)”。 home.HomeFragment$1.onResponse(HomeFragment.java:104)
每当我尝试运行我的应用程序时。我已经将 getActivity() 更改为 HomeFragment.this 或 getApplicationActivity() 但仍然出错,我被困了很长时间,因为我不太了解它是如何工作的,我希望有人能向我解释如何在片段中调用上下文,这里是我的java
public class HomeFragment extends Fragment {
private RecyclerView rvData;
private RecyclerView.Adapter adData;
private RecyclerView.LayoutManager lmData;
private List<DataModel> listData = new ArrayList<>();
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rvData = getActivity().findViewById(R.id.rv_user);
lmData = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
rvData.setLayoutManager(lmData);
retrieveData();
return inflater.inflate(R.layout.fragment_home, container, false);
}
public void retrieveData(){
APIRequestData ardData = RetroServer.connectRetrofit().create(APIRequestData.class);
Call<ResponseModel> showData = ardData.ardRetrieveData();
showData.enqueue(new Callback<ResponseModel>() {
@Override
public void onResponse(Call<ResponseModel> call, Response<ResponseModel> response) {
int code = response.body().getCode();
String message = response.body().getMessage();
Toast.makeText(getActivity(), "Code: "+code+"| Message: "+message, Toast.LENGTH_SHORT).show();
listData = response.body().getData();
adData = new AdapterData(getActivity(),listData);
rvData.setLayoutManager(lmData);
adData.notifyDataSetChanged();
}
@Override
public void onFailure(Call<ResponseModel> call, Throwable t) {
Toast.makeText(getActivity(), "Fail to Retrieve Data", Toast.LENGTH_SHORT).show();
}
});
}
这是我的 fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_user"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="@layout/card_item"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
【问题讨论】:
-
如果 RecyclerView 在片段布局中,你不能像在活动布局中那样使用
rvData = getActivity().findViewById(R.id.rv_user) -
如果在片段布局中,使用:
View view = inflater.inflate(R.layout.fragment_home, container, false); rvData = view.findViewById(R.id.rv_user);
标签: java android xml android-recyclerview