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

Can anyone see what this code is missing?

Hey guys.

So recently I have been working on the Android track and it has all been going great up until this point. I am trying to get the background color to change every time the button is clicked but my App will no longer run because it 'cannot find symbol class RelativeLayout'.

I have scanned through my code and I cannot seem to find the error. If any of you guys could help me out that would be awesome!

XML File

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".FabulousFactsActivity"
    android:background="@android:color/holo_blue_bright"
    android:id="@+id/relativeLayout">

    <TextView
        android:text="Did you know?"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textSize="24sp"
        android:textColor="#80ffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ants stretch when they wake up in the morning."
        android:id="@+id/factTextView"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textSize="24sp"
        android:textColor="#ffffffff" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show me a fact!"
        android:id="@+id/showFactButton"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:background="@android:color/white" />

</RelativeLayout>

FabulousFactsActivity.java

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import java.util.Random;


public class FabulousFactsActivity extends Activity {
    private FactBook mFactBook;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        public final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fabulous_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);

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

FactBook.java

import java.util.Random;

public class FactBook {
    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 7 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."
    };
    public String getFact() {

        String fact = "";
        // Randomly select a fact.
        Random randomGenerator = new Random(); //Construct a new random number generator.
        int randomNumber = randomGenerator.nextInt(mFacts.length);
        fact = mFacts[randomNumber];
        return fact;
    }
}

4 Answers

Okay, the main issue you are having it seems has nothing to do with bad code. Your code looks great, you just need to import the classes you are using. For example, you called the RelativeLayout class, well your program has no idea what that is, since its an outside class. That's what you import the class so your program knows where to look to find the class you are trying to use.

The easiest way to fix this is to organize your imports. Android Studio and Eclipse has this handy button that will automatically import all of the classes you need and delete any of the ones you do not. In Android Studio it is called Optimize Imports, but either way just press CTRL + ALT + O (the letter not the number).

If that doesn't work for some odd reason, you can add the import manually:

import android.graphics.Color;

I done what you suggested and my app now opens fine which is great!

However, now when I press the button to show a new fact and change the background color my app instantly crashes. Any ideas?

Thanks for all the great help thus far.

Getting closer! Woo!

What is the error that comes up in your Log?

Have you tried to clean and rebuild the project?

EDIT: Isn't it dimens.xml not dimen.xml? Don't know if that will solve your issue but that doesn't seem right..

Yeah I have tried a few times but I still get an error.

It is dimens.xml but I think it is referred to in this circumstance as dimen.

Hmm, odd.

I would add:

import android.widget.RelativeLayout;

EDIT: Add it to your funfactactivity.java

That has solved one of my errors but now I get the error 'cannot find symbol variable Color'.

We are indeed, thanks once again for all the great help so far!

09-19 16:26:03.250      553-553/lukeglazebrook.fabulousfacts E/AndroidRuntime FATAL EXCEPTION: main
    java.lang.NullPointerException
            at lukeglazebrook.fabulousfacts.FabulousFactsActivity$1.onClick(FabulousFactsActivity.java:27)
            at android.view.View.performClick(View.java:3511)
            at android.view.View$PerformClick.run(View.java:14105)
            at android.os.Handler.handleCallback(Handler.java:605)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4424)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
            at dalvik.system.NativeStart.main(Native Method)
09-19 16:26:04.590      553-559/lukeglazebrook.fabulousfacts I/dalvikvm threadid=3: reacting to signal 3
09-19 16:26:04.610      553-559/lukeglazebrook.fabulousfacts I/dalvikvm Wrote stack traces to '/data/anr/traces.txt'
09-19 16:26:05.690      553-553/lukeglazebrook.fabulousfacts I/Process Sending signal. PID: 553 SIG: 9

So if you look at the top of your Log, you see that you are getting a NullPointerException, this means that you are trying to get a value from a variable that does not exist.

If you look at how we declare new classes (ie: RandomGenerator random = new RandomGenerator();) we have to call the class' constructor, usually in our case the default constructor. When you defined FactBook in your FabulousFactsActivity.java, it never actually created an instance of the class.

If you change

private FactBook mFactBook;

to:

private FactBook mFactBook = new FactBook();

it should work.

Changed this then cleaned and rebuilt my project but I'm still having issues!

This is the error:

09-19 17:24:39.084      552-552/lukeglazebrook.fabulousfacts E/AndroidRuntime FATAL EXCEPTION: main
    java.lang.NullPointerException
            at lukeglazebrook.fabulousfacts.FabulousFactsActivity$1.onClick(FabulousFactsActivity.java:30)
            at android.view.View.performClick(View.java:3511)
            at android.view.View$PerformClick.run(View.java:14105)
            at android.os.Handler.handleCallback(Handler.java:605)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4424)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
            at dalvik.system.NativeStart.main(Native Method)
09-19 17:24:39.754      552-557/lukeglazebrook.fabulousfacts I/dalvikvm threadid=3: reacting to signal 3
09-19 17:24:39.774      552-557/lukeglazebrook.fabulousfacts I/dalvikvm Wrote stack traces to '/data/anr/traces.txt'

Bizarre, what is on Line 30 of your FabulousFactsActivity?

Line 30:

relativeLayout.setBackgroundColor(Color.GREEN);

Okay I think this time we got this! Move your Relative Layout declaration down to where you declare the button and textview, aka after the super.OnCreate(wordsfdjslaj);

Yay, it worked! Please could you explain why it didn't work before? I didn't notice this fix when I was scanning through my code.

Thank you for all the help though I really appreciate it, have a great day.

-Luke

Nevemind Solved it Thanks :)