-2

Hi I'm learning android development with an Udacity course, i'm getting an error on trying to add a child view to an LinearLayout.
Following are the xml file and the class files for the activity
Please help
the error i get is

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference

numbers_activity.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:id="@+id/rootView"
            tools:context="com.example.android.miwok.NumbersActivity">


    </LinearLayout>

NumversActivity.java

    package com.example.android.miwok;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    import java.util.ArrayList;

    public class NumbersActivity extends AppCompatActivity {

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_phrases);

                    ArrayList<String> words = new ArrayList<String>();
                    words.add("one");
                    words.add("two");
                    words.add("three");
                    words.add("four");
                    words.add("five");
                    words.add("six");
                    words.add("seven");
                    words.add("eight");
                    words.add("nine");
                    words.add("ten");

                    LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);

                    TextView wordView = new TextView(this);
                    wordView.setText(words.get(1));
                    rootView.addView(wordView);

            }
    }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Bmax
  • 590
  • 4
  • 11
  • 24
  • post logcat error here. – Bruno Ferreira Aug 10 '17 at 17:17
  • it's not a duplicate question, as you can see from the answer by @Bob, the error was setting the wrong layout for the activity, in the line " setContentView(R.layout.activity_phrases);". I didn't notice this since i'm a beginner, Bobs answer helped and worked.. – Bmax Aug 10 '17 at 23:43

1 Answers1

2

You have to set the correct layout to the Activity.

Change the second line in your onCreate method to this:

setContentView(numbers_activity.xml);

Your layout file is numbers_activity.xml. But you are setting activity_phrases to your Activity.

Bob
  • 13,447
  • 7
  • 35
  • 45