Tsangares
Tsangares

Reputation: 825

Having trouble with Android 's findViewById

I'm using some pre-generated android code and it isn't working.

Here is the onCreateView function for a Fragment:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tabmain, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }

Here is the xml for this fragment:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.startandselect.agora.tabmain$PlaceholderFragment">

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

But when I run the problem I get an error on the textView.setText line because textView is null. textView is null because the line before it failed to find the text view. The findViewById failed to find it but I do not know why.

I debugged and found that the real textView has an id: 2131492994 and the R.id.section_label has an id of 2131492997.

Upvotes: 4

Views: 673

Answers (3)

Berat Cevik
Berat Cevik

Reputation: 1958

Try to use the following:

TextView textView = (TextView) findViewById(R.id.section_label);

instead of:

TextView textView = (TextView) rootView.findViewById(R.id.section_label);

Upvotes: 5

Tsangares
Tsangares

Reputation: 825

Karakuri suggested in the comment to clean and rebuild. It was the first thing I attempted and that was all it took, thank you.

Solution: Clean and rebuild project.

Upvotes: 1

Nanoid
Nanoid

Reputation: 21

You have the same android:id of TextView on another activity layout.

Upvotes: 2

Related Questions