0

Im trying to get the TextViews shown in my faq_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/question_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textAlignment="center"
        android:text="Title 1"/>

    <TextView
        android:id="@+id/answer_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textAlignment="center"
        android:text="Description 1"
        android:textColor="#33000000"
        android:layout_marginTop="5dp"/>

</LinearLayout>

In my Fragment class

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ((TextView)container.findViewById(R.id.question_text)).setText(title);
    ((TextView)container.findViewById(R.id.answer_text)).setText(description);

    return inflater.inflate(R.layout.faq_fragment, container, false);
}

App is crashing and Im getting error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Arbitur
  • 38,684
  • 22
  • 91
  • 128

2 Answers2

5

You need to inflate the view before using it.

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.faq_fragment, container, false);
    ((TextView)view .findViewById(R.id.question_text)).setText(title);
    ((TextView)view .findViewById(R.id.answer_text)).setText(description);

    return view;
}
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
  • I see, sorry Im very new to android. :) I can accept in 12 min – Arbitur Oct 22 '15 at 12:08
  • Is it possible to get the textviews in onCreate() ? – Arbitur Oct 22 '15 at 12:13
  • I think I found a correct answer to this question [here](http://stackoverflow.com/questions/28929637/difference-and-uses-of-oncreate-oncreateview-and-onactivitycreated-in-fra). So use `onCreateView()` ;) – ThomasThiebaud Oct 22 '15 at 12:26
2

You should use the inflated view:

Change it to:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.faq_fragment, container, false);
    ((TextView)view.findViewById(R.id.question_text)).setText(title);
    ((TextView)view.findViewById(R.id.answer_text)).setText(description);
    return view;
}
Roel
  • 3,089
  • 2
  • 30
  • 34