Tomer Amir
Tomer Amir

Reputation: 1585

findViewById doesn't find my view

This is my java:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_starting_point);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

        counter = 0;
        add = (Button) findViewById(R.id.add_butt);
        sub = (Button) findViewById(R.id.sub_butt);
        display = (TextView) findViewById(R.id.tv_text);

        add.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                counter++;
                display.setText("Your Total is " + counter);
            }
        });

and this is my xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    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.example.myfirstapp.StartingPoint$PlaceholderFragment" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your Total is 0"
        android:textSize="40sp"
        android:layout_gravity="center"
        android:id="@+id/tv_text" />

    <Button 
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:text="Add 1"
        android:layout_gravity="center"
        android:id="@+id/add_butt" />

    <Button 
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:text="Sub 1"
        android:layout_gravity="center"
        android:id="@+id/sub_butt" />


</LinearLayout>

I get a NullPointerExeption error when I try to add the listeners, because the findViewById method returns null on all the views... I think that everything is in place. All the views are in the XML and they have the proper ID's, so what did i do wrong?

Upvotes: 0

Views: 526

Answers (1)

Ion Aalbers
Ion Aalbers

Reputation: 8030

You are trying to findViewById of views that are located in the Fragment.

Try moving this code to your PlaceholderFragment class (OnCreateView)

Upvotes: 3

Related Questions