Accessing the TextView in a fragment throws a NullPointerException

I am new to android development.

I have TextView

in layout and when I try to access TextView

in class Fragment

a NullPointerException

. I am accessing the TextView like this:

TextView textView = (TextView) view.findViewById(R.id.quotes);

      

What am I doing wrong?

I've looked at other answers regarding this on SO but haven't found a solution ...

Corresponding code

quotes_details_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/quotes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/quotes_details"
        android:textSize="24sp" />

</RelativeLayout>

      

QuotesFragment.java

public class QuotesFragment extends Fragment {

    public QuotesFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.quotes_details_fragment, container, false);
        TextView textView = (TextView) view.findViewById(R.id.quotes); // NullPointerException
        return view;
    }

}

      

(The main activity class only calls the corresponding fragment using FragmentTransaction

)

Thank you for your help.

+3


source to share


1 answer


add this LayoutInflater to your onCreateView (..);

 LayoutInflater lf = getActivity().getLayoutInflater();   

      



Same:

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        LayoutInflater lf = getActivity().getLayoutInflater();   

        View view =  lf.inflate(R.layout.quotes_details_fragment, container, false);
        TextView textView = (TextView) view.findViewById(R.id.quotes); // 
        return view;
    }

      

+4


source







All Articles