简体   繁体   中英

How to correctly use if statement for inflater null checker

After trying to create a CardView programmatically, a NullPointerException but I've used an if statement and the warning is gone, but I'm not sure what needs to go in else part of the if statement.

Method invocation 'inflate' may produce java.lang.NullPointerException

Java

//start of CardView
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);
if(inflater1 != null) {
View inflatedCardviewLayout = inflater.inflate(R.layout.my_cardview,  new RelativeLayout(getContext()), false);
inflatedCardviewLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.green));

TextView cv_tv1a = inflatedCardviewLayout.findViewById(R.id.cardview_titleA);
cv_tv1a.setText(getString(R.string.titleA));

ImageView imgPictogram = inflatedCardviewLayout.findViewById(R.id.image_pictogram);
imgPictogram.setImageResource(R.drawable.ic_pictogram);

TextView cv_tv1b = inflatedCardviewLayout.findViewById(R.id.cardview_titleB);
cv_tv1b.setText(getString(R.string.titleB));
} else {
    //do something else
}
//end of CardView

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/my_cardview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/cardview_titleA"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/image_pictogram"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/cardview_titleB"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</android.support.v7.widget.CardView>

You should fix the NullPointerException since getting an inflater is a required use for your code. I mean fix by using LayoutInflator.from(parent context) instead of asking the system for one.

You should make a class so that you extend CardView, then use the context of when you create the view object to get the inflater. Also make sure to merge the CardView with the inflated layout!

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