neo108
neo108

Reputation: 5246

Access TextView in Fragment throws NullPointerException

I am quite new to Android development.

I have a TextView in the layout and when I try to access the TextView in the Fragment class a NullPointerException is thrown. I am accessing the TextView as follows...

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

What am I doing wrong?

I have looked at other answers regarding this on SO but have not found a solution...

Relevant 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 is only calling the relevant fragment using FragmentTransaction)

Thank you for all your help.

Upvotes: 3

Views: 4825

Answers (1)

Dixit Patel
Dixit Patel

Reputation: 3192

add this LayoutInflater in your onCreateView(..);

 LayoutInflater lf = getActivity().getLayoutInflater();   

Like this way:

 @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;
    }

Upvotes: 4

Related Questions