简体   繁体   中英

How to resolve Null Pointer Exception for getView() in Fragment in HomeFragment Activity?

public class HomeFragment extends Fragment implements HomeView{

private HomeViewModel homeViewModel;
public static final String EXTRA_CATEGORY = "category";
public static final String EXTRA_POSITION = "position";
public static final String EXTRA_DETAIL = "detail";

@BindView(R.id.viewPagerHeader)
ViewPager viewPagerMeal;
@BindView(R.id.recyclerCategory)
RecyclerView recyclerViewCategory;

HomePresenter presenter;

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel.class);
    View root = inflater.inflate(R.layout.fragment_home, container, false);
    super.onCreate(savedInstanceState);
    ButterKnife.bind(getActivity());

    presenter = new HomePresenter(this);
    presenter.getMeals();
    presenter.getCategories();

    return root;
}

@Override
public void showLoading() {
    getView().findViewById(R.id.shimmerMeal).setVisibility(View.VISIBLE);
    getView().findViewById(R.id.shimmerCategory).setVisibility(View.VISIBLE);
}

@Override
public void hideLoading() {
    getView().findViewById(R.id.shimmerMeal).setVisibility(View.GONE);
    getView().findViewById(R.id.shimmerCategory).setVisibility(View.GONE);
}

@Override
public void setMeal(List<Meals.Meal> meal) {
    ViewPagerHeaderAdapter headerAdapter = new ViewPagerHeaderAdapter(meal, getActivity());
    viewPagerMeal.setAdapter(headerAdapter);
    viewPagerMeal.setPadding(20, 0, 150, 0);
    headerAdapter.notifyDataSetChanged();

    headerAdapter.setOnItemClickListener((view, position) -> {
        TextView mealName = view.findViewById(R.id.mealName);
        Intent intent = new Intent(getActivity().getApplicationContext(), DetailActivity.class);
        intent.putExtra(EXTRA_DETAIL,mealName.getText().toString());
        startActivity(intent);
    });
}

@Override
public void setCategory(List<Categories.Category> category) {
    RecyclerViewHomeAdapter homeAdapter = new RecyclerViewHomeAdapter(category, getActivity());
    recyclerViewCategory.setAdapter(homeAdapter);
    GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3,
            GridLayoutManager.VERTICAL, false);
    recyclerViewCategory.setLayoutManager(layoutManager);
    recyclerViewCategory.setNestedScrollingEnabled(true);
    homeAdapter.notifyDataSetChanged();

    homeAdapter.setOnItemClickListener((view, position) -> {
        Intent intent = new Intent(getActivity(), CategoryActivity.class);
        intent.putExtra(EXTRA_CATEGORY, (Serializable) category);
        intent.putExtra(EXTRA_POSITION, position);
        startActivity(intent);
    });
}

@Override
public void onErrorLoading(String message) {
    Utils.showDialogMessage(getActivity(), "Title", message);
}

} Here is fragment_home.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment"
android:fitsSystemWindows="true">

<android.support.v4.widget.NestedScrollView
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:fillViewport="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackground">
    <RelativeLayout
        android:id="@+id/headerView"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="300dp">
        <View
            android:layout_width="match_parent"
            android:layout_height="220dp"
            android:background="@color/colorPrimary" />

        <TextView
            android:id="@+id/title"
            android:textColor="@color/colorWhite"
            android:text="@string/app_name"
            android:textStyle="bold"
            android:textSize="30sp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.v7.widget.CardView
            android:id="@+id/cardSearch"
            android:layout_below="@id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="15dp"
            app:cardBackgroundColor="@color/colorPrimaryDark"
            app:cardCornerRadius="10dp"
            app:cardElevation="0dp">
            <TextView
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:padding="10dp"
                android:text="@string/search_your_recipes"
                android:textColor="@color/colorPrimaryLight"
                android:gravity="center_vertical"
                android:drawableLeft="@drawable/ic_search_primary_light"
                android:drawableStart="@drawable/ic_search_primary_light"
                android:drawablePadding="10dp"/>
        </android.support.v7.widget.CardView>

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPagerHeader"
            android:foregroundGravity="center"
            android:overScrollMode="never"
            android:clipToPadding="false"
            android:layout_below="@id/cardSearch"
            android:layout_marginTop="10dp"
            android:layout_width="match_parent"
            android:layout_height="150dp" />

        <include android:id="@+id/shimmerMeal"
            layout="@layout/item_view_pager_header_shimmer" />

        <TextView
            android:id="@+id/titleCategory"
            android:text="@string/meal_categories"
            android:textSize="19sp"
            android:textColor="@color/colorPrimary"
            android:textStyle="bold"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/viewPagerHeader"/>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerCategory"
            android:scrollbars="none"
            android:layout_marginTop="10dp"
            android:clipToPadding="false"
            android:layout_below="@id/titleCategory"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginBottom="50dp" />

        <include android:id="@+id/shimmerCategory"
            layout="@layout/item_recycler_category_shimmer" />

        <TextView
            android:padding="10dp"
            android:gravity="center"
            android:textColor="@color/colorWhite"
            android:text="@string/app_name"
            android:background="@color/colorPrimaryLight"
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"/>

    </RelativeLayout>
</android.support.v4.widget.NestedScrollView>

Getting error with the getView().findViewById() in showloading() and hideloading() Java.lang.NullPointerException .
How can I resolve this error? So far tried many ways to resolve this? Looked in many StackOverflow concepts about this I didn't got any idea how to make it get corrected.I had also included shimmer meal and container in fragmment_home.xml as shown in the xml code above.

check if fragment is added or not by this command before getView

if(isAdded()){
    getView().findViewById(R.id.shimmerMeal).setVisibility(View.VISIBLE);
}

The getView() method returns null because it is invoked before the onCreateView() method completes.

My suggestion is to store as class fields the UI widgets you need in the onCreateView() :

shimmerMeal = root.findViewById(R.id.shimmerMeal);
shimmerCategory = root.findViewById(R.id.shimmerCategory);

and then your showLoading() and hideLoading() can be changed as the following:

@Override
public void showLoading() {
    shimmerMeal.setVisibility(View.VISIBLE);
    shimmerCategory.setVisibility(View.VISIBLE);
}

@Override
public void hideLoading() {
    shimmerMeal.setVisibility(View.GONE);
    shimmerCategory.setVisibility(View.GONE);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM