0
我我的Android應用程序的運行過程中不被此特定錯誤設置回收觀點:空指針異常的片段
java.lang.NullPointerException: Attempt to invoke virtual method`'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
at com.monkeyengineer.project.MyFragment.onCreateView(MyFragment.java:36)
我已經檢查了Android回收視圖和適配器文檔,但它並沒有幫助我爲什麼這是崩潰。
這是我在我的片段代碼,其中我打電話在容器視圖findViewById
方法(進口語句是爲簡潔起見省略了):
public class MyFragment extends Fragment {
private List<Project> data;
private RecyclerView recyclerView;
private TextView textView;
private boolean mIsRecyclerViewVisible = true;
public MyFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.my_fragment, container, false);
textView = (TextView) container.findViewById(R.id.text_view);
recyclerView = (RecyclerView) container.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLayoutManager);
Adapter adapter = new ProjectsAdapter(data);
recyclerView.setAdapter(adapter);
if (data != null) {
textView.setVisibility(View.INVISIBLE);
mIsRecyclerViewVisible = true;
} else {
recyclerView.setVisibility(View.INVISIBLE);
mIsRecyclerViewVisible = false;
}
return mView;
}
@Override
public void onStart() {
super.onStart();
if (mIsRecyclerViewVisible) {
recyclerView.setVisibility(View.VISIBLE);
textView.setVisibility(View.INVISIBLE);
} else {
recyclerView.setVisibility(View.INVISIBLE);
textView.setVisibility(View.VISIBLE);
}
}
@Override
public void onStop() {
super.onStop();
mIsRecyclerViewVisible = data != null;
}
}
這是我的片段佈局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.monkeyengineer.project.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:height="45dp"
android:drawableLeft="@android:drawable/ic_input_add"
android:drawableStart="@android:drawable/ic_input_add"
android:drawablePadding="8dp"
android:gravity="start|center"
android:padding="8dp"
android:text="Add stuff."
android:textStyle="bold"
android:layout_gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
那麼爲什麼它給出一個空指針異常,它必須是因爲回收視圖對象被分配給一個空值,但我想不出爲什麼。
謝謝。
@TomFinet請接受我的回答,如果這對你有幫助。 :) – SripadRaj
謝謝,這是一個明顯的錯誤。 –