Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Null pointer error...

I am actually experiencing the same issue. My code has been written to match the instructor's.

I can show my code here:

---------------------------FunFactsActivity.java--------------------------------------------------------------

package com.megliosolutions.funfacts;

import android.content.DialogInterface;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.Random;


public class FunFactsActivity extends ActionBarActivity {

    private FactBook mFactBook;

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



        //Declare our View variables and assign them the views from the layout file
        final TextView factLabel = (TextView) findViewById(R.id.factTextView);
        Button showFactButton = (Button) findViewById(R.id.showFactButton);
        final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String fact = mFactBook.getFact();
                // Update the label with our dynamic fact
                factLabel.setText("");
                relativeLayout.setBackgroundColor(Color.RED);
            }
        };
        showFactButton.setOnClickListener(listener);

    }

}

--------------------------------------FactBook.java------------------------------------------------

package com.megliosolutions.funfacts;

import java.util.Random;

/**
 * Created by Wesley on 1/8/2015.
 */
public class FactBook {

    // Member variable (properties about the object)
    public String[] mFacts = {
            "Ants stretch when they wake up in the morning.",
            "Ostriches can run faster than horses.",
            "Olympic gold medals are actually made mostly of silver.",
            "You are born with 300 bones; by the time you are an adult you will have 206.",
            "It takes about 8 minutes for light from the Sun to reach Earth.",
            "Some bamboo plants can grow almost a meter in just one day.",
            "The state of Florida is bigger than England.",
            "Some penguins can leap 2-3 meters out of the water.",
            "On average, it takes 66 days to form a new habit.",
            "Mammoths still walked the earth when the Great Pyramid was being built.",
            "Treehouse is not actually in a tree."};
    // Method (abilities: these are things the object can do)
    public String getFact(){

        String fact = "";
        // Randomly select a fact
        Random randomGenerator = new Random(); //Construct a new Random number generator
        // Assigning an int or number value to choose between
        int randomNumber = randomGenerator.nextInt(mFacts.length);
        //fact is being made equal to randomNumber adding an empty
        fact = randomNumber + "";

        fact = mFacts[randomNumber];

        return fact;
    }

}

I am not sure where my issue is. with the Null pointer error.

Aaron Arkie
Aaron Arkie
5,345 Points

Okay I see the issue. Lets break it down

// Member variable (properties about the object)
public String[] mFacts = {
        "Ants stretch when they wake up in the morning.",
        "Ostriches can run faster than horses.",
        "Olympic gold medals are actually made mostly of silver.",
        "You are born with 300 bones; by the time you are an adult you will have 206.",
        "It takes about 8 minutes for light from the Sun to reach Earth.",
        "Some bamboo plants can grow almost a meter in just one day.",
        "The state of Florida is bigger than England.",
        "Some penguins can leap 2-3 meters out of the water.",
        "On average, it takes 66 days to form a new habit.",
        "Mammoths still walked the earth when the Great Pyramid was being built.",
        "Treehouse is not actually in a tree."};
// Method (abilities: these are things the object can do)

public String getFact(){ 

// Here you created a method, However you are already in a method which is the onClick method
// You cannot create a method within a method.
// delete the method but leave the following code. Dont forget to delete its closing curly brace.

    String fact = "";
    // Randomly select a fact
    Random randomGenerator = new Random(); //Construct a new Random number generator
   //Create a variable to store an int that will be used to hold a position in my mFacts Array object.
    int randomNumber = randomGenerator.nextInt(mFacts.length); // Grab a value and store it in our int variable.
    //fact is being made equal to randomNumber adding an empty
    fact = randomNumber + ""; // You do not need this. Look at your statement after this one.
    fact = mFacts[randomNumber]; 

/* This statement above allows you to get string from the array you created. Lets break it down.
 *  You created a String variable named Facts to store a string.
 *  You also created an Array object called mFacts which holds numerous Strings. 
 *  Now you must get a position in the array to grab a hold of one of the strings.
 * This is where the randomNumber variable comes into play.
 * instead of assigning the 11 strings to a variable such as 
 * String stringOne = mFacts[0];
 * String stringTwo = mFacts[1];
 * You are instead saying i want to use a string in my array mFacts but i want it to be random. 
 * So use the integer stored in randomNumber and assign it a position inside my array mFacts.
 * Store this string inside fact.
*/

    return fact; // Since our method  onClick() has a state of void it does not need to return a value. Delete it.
}

I really hope this helps you! I will leave my code for you to compare it too.

Aaron Arkie
Aaron Arkie
5,345 Points

My code is the following:

package com.arkman.funfacts;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;


public class FunFactsActivity extends Activity {

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

        //Declare our view variables and assign them the views from the layout files
        final TextView factLabel = (TextView) findViewById(R.id.factTextView);
        Button showFactButton = (Button) findViewById(R.id.showFactButton);

        View.OnClickListener listener = new View.OnClickListener() {

            public void onClick(View view) {
                String[] mFacts = {
                        "Ants stretch when they wake up in the morning.",
                        "Ostriches can run faster than horses.",
                        "Olympic gold medals are actually made mostly of silver.",
                        "You are born with 300 bones; by the time you are an adult you will have 206.",
                        "It takes about 8 minutes for light from the Sun to reach Earth.",
                        "Some bamboo plants can grow almost a meter in just one day.",
                        "The state of Florida is bigger than England.",
                        "Some penguins can leap 2-3 meters out of the water.",
                        "On average, it takes 66 days to form a new habit.",
                        "Mammoths still walked the earth when the Great Pyramid was being built." }; // my list of facts held in an Array object

                //randomly select a fact

                Random randomGenerator = new Random(); // create a reference variable to store the Random class
                int randomNumber = randomGenerator.nextInt(mFacts.length); // Create a variable that will be used to store a random int

                String fact = ""; // Create a variable that will be used to store a String from my array object named mFacts
                fact = mFacts[randomNumber]; // Use the integer stored in randomNumber to hold a position inside my Array Object

                //Update the label with our dynamic fact

                factLabel.setText(fact); // set my TextView object called factLabel to the String stored in fact

            }
        };
        showFactButton.setOnClickListener(listener); // wait for my Button to be pressed. Then update using the onClick method.

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_fun_facts, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
Ken Alger
Ken Alger
Treehouse Teacher

Edited original post for markup

13 Answers

Aaron Arkie
Aaron Arkie
5,345 Points

Yeah like Thomas Edison said "I have not failed. I've just found 10,000 ways that won't work." Keep at it and you're bound to come to a solvable solution. Plus it also helps others who may have questions or the same error and they can look at your steps and follow along to solve it. The Java Object projects are really interesting. If you are new to the language i highly recommend this part of the android track. Craig Dennis really gets into the language and shows you neat methods and programming styles to enhance your code. Moreover, since JAVA is OOP it's best to get the overall grasps of the use of objects as it makes it easier to take advantage of the language.

I FIGURED IT OUT!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Ok so apparently I missed one last crucial step. One thing is important when watching these videos everyone is don't do it when you could be possibly distracted! LOL. Missed these small tiny little things. Oh well, ok so onto the solutions. In making sure that the above mistakes that I made were fixed in your code, here is where I went wrong and got the NULL pointer error.

in the following code I will demonstrate the error that I didn't see until now.

private FactBook mFactBook;

when I should have paid a bit more attention and added this extra step:

private FactBook mFactBook = new FactBook();

fixed it and now I am onto the next step!!

Hope this helps, thank you everyone for your support! Love this site!! Definitely going to continue to learn knowing that I can get help when needed! Thanks!!!

I am still confused because I have an activity java file, and a class file. I have seperated the code for DRY, and to allow for there not to be so much code in one file when I can make a class to be pointed to.

I guess I am just confused because I have followed the video exactly or so I think. Which is why I posted my code. I guess I am still not understanding what is wrong.

Take that back! after looking through the video I missed a crucial step that we all let go over our heads! No worries we're a team! Here's where I messed up.

View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View v) { String fact = mFactBook.getFact(); // Update the label with our dynamic fact factLabel.setText(fact); // <------------------------- RIGHT HERE ---------------------- // I didn't make the "factLabel.setText(""); back to it's original "...setText(fact); relativeLayout.setBackgroundColor(Color.RED); } }; showFactButton.setOnClickListener(listener);

Ah dang, that didn't work. Well I am glad I am at least fixing some things! I will continue to see what I missed! I do these classes on my lunch break and get asked questions from co-workers while listening so I am assuming that is what happened. I just missed a few things!

Aaron Arkie
Aaron Arkie
5,345 Points

Hey Wesley! No worries! Once i spent two hours trying to figure out why my code kept returning an error and it was cause i closed an if statement to early. Once you solve it though you feel like a champ! On the other hand i think i had the same error that you were having. Check the exception error and see if it tells you were the error is located. i believe it has to do with the String fact label. If your code is just String fact; <--- at runtime the compiler sets it to null. If you would like to compare on this thread i will leave my code which is identical to the instructors. (of course with some of my own comments).

package com.arkman.funfacts;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;


public class FunFactsActivity extends Activity {

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

        //Declare our view variables and assign them the views from the layout files
        final TextView factLabel = (TextView) findViewById(R.id.factTextView);
        Button showFactButton = (Button) findViewById(R.id.showFactButton);

        View.OnClickListener listener = new View.OnClickListener() {

            public void onClick(View view) {
                String[] mFacts = {
                        "Ants stretch when they wake up in the morning.",
                        "Ostriches can run faster than horses.",
                        "Olympic gold medals are actually made mostly of silver.",
                        "You are born with 300 bones; by the time you are an adult you will have 206.",
                        "It takes about 8 minutes for light from the Sun to reach Earth.",
                        "Some bamboo plants can grow almost a meter in just one day.",
                        "The state of Florida is bigger than England.",
                        "Some penguins can leap 2-3 meters out of the water.",
                        "On average, it takes 66 days to form a new habit.",
                        "Mammoths still walked the earth when the Great Pyramid was being built." }; // my list of facts held in an Array object

                //randomly select a fact

                Random randomGenerator = new Random(); // create a reference variable to store the Random class
                int randomNumber = randomGenerator.nextInt(mFacts.length); // Create a variable that will be used to store a random int

                String fact = ""; // Create a variable that will be used to store a String from my array object named mFacts
                fact = mFacts[randomNumber]; // Use the integer stored in randomNumber to hold a position inside my Array Object

                //Update the label with our dynamic fact

                factLabel.setText(fact); // set my TextView object called factLabel to the String stored in fact

            }
        };
        showFactButton.setOnClickListener(listener); // wait for my Button to be pressed. Then update using the onClick method.

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_fun_facts, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Well your code shows everything in one file. I have separated my code into a java file and .class file. Also I think this step right here is what I am missing in my class file. But I am not sure. In the video step one of "Dynamically Changing the Background Color". This step is what I am referring to.

"Declare a member variable with the data type of RelativeLayout. The format is just like our other member variables but with this other data type and a different name. "

Aaron Arkie
Aaron Arkie
5,345 Points

Oh i see! I think you are ahead of me, i stopped to do the new updated section of Java objects for this track. Once i get here i will see what's going on and ill lay down some more input. Good luck and let me know if you figure it out!

No worries! I just can't stop and do something else. My brain just goes nuts haha. So I have to finish this. Once I am done I will do the objects lemme know if it helps better.

much appreciated definitely understand and agree. I will never quit. I will definitely find a good way to solve it. Just takes trial and error! I will post here if I find an answer!

Aaron Arkie
Aaron Arkie
5,345 Points

Ahh this problem was going through my head too. After much thought i figured you forgot to create a reference object to the class you created. I remember you saying you created a separate class to make it more efficient to read! Great job! told you you'd feel like a champ! Well done!

I thought my answer posted, I guess not.

You were correct Aaron, it was the declaration of the class variable.

I fixed it after staying up for a few extra hours! Much appreciated definitely remembering that for next time! Oh and btw TREEHOUSE I LOVE YOU!

having the ability to do these courses on any platform is amazing!