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

Miles Torres
Miles Torres
2,316 Points

My FunFacts App is not working

when i click on it it says "Unfortunately, FunFacts has stopped." how do i fix this?

Harry James
Harry James
14,780 Points

Hey Miles!

Could you please provide your code files and also a Logcat of the error from within Android Studio here?

This will help us to see what is causing the issue.


Speak to you soon! :)

Miles Torres
Miles Torres
2,316 Points
01-18 13:10:54.766 5447-5447/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                 Process: com.example.milespc.funfacts, PID: 5447
                                                 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.milespc.funfacts/com.example.milespc.funfacts.ActivityFunFacts}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2393)
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:135)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5356)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at java.lang.reflect.Method.invoke(Method.java:372)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                     at com.example.milespc.funfacts.ActivityFunFacts.onCreate(ActivityFunFacts.java:48)
                                                     at android.app.Activity.performCreate(Activity.java:6020)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2284)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2393) 
                                                     at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309) 
                                                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                     at android.os.Looper.loop(Looper.java:135) 
                                                     at android.app.ActivityThread.main(ActivityThread.java:5356) 
                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                     at java.lang.reflect.Method.invoke(Method.java:372) 
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908) 
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

also what is a code file?

Seth Kroger
Seth Kroger
56,413 Points

The relevant .java and .xml files. In this case, we should take a look at ActivityFunFacts.java.

Miles Torres
Miles Torres
2,316 Points

this is the xml file

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingLeft="50dp" android:paddingRight="50dp" android:paddingTop="50dp" android:paddingBottom="50dp" android:background="#51b46d" android:id="@+id/relativelayout" >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#51b46d"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    >

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Another FunFact"
        android:id="@+id/showFactButton"
        android:layout_centerHorizontal="true"
        android:background="@android:color/white"
        android:textColor="#ff51b46d"
        android:layout_alignParentBottom="true"
        android:textSize="25sp" />

</RelativeLayout>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Did You Know?"
    android:id="@+id/textView"
    android:layout_alignParentTop="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/textView2"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:textSize="24sp"
    android:textColor="@android:color/white" />

</RelativeLayout>

14 Answers

Harry James
Harry James
14,780 Points

Hey again Miles!

We're getting a NullPointerException here because there's an issue with this line of code:

final Button showFactButton = (Button) findViewById(R.id.showFactButton);

We're trying to refer to an XML Element with the name showFactButton, however that doesn't exist! This means when you get to the point of setting an onClickListener() on this button, we're in fact trying to set an onClickListener() on something that doesn't exist, thus giving us the NullPointerException.

Not to worry though, it's an easy enough fix! Also, there's two different ways to fix the issue, pick ONE from below:


Update the name in XML

To do this, open up your activity_funfacts.xml file (The name may slightly differ) and update the ID to showFactButton:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
        ... >

    <RelativeLayout
        ... >

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Show Another FunFact"
            android:id="@+id/showFactButton" <------------ CHANGE THIS LINE
            android:layout_centerHorizontal="true"
            android:background="@android:color/white"
            android:textColor="#ff51b46d"
            android:layout_alignParentBottom="true"
            android:textSize="25sp" />

...

OR Update the name in Java

To do this, open up your ActivityFunFacts.java file and update the findViewById() reference to use R.id.button:

package com.example.milespc.funfacts;

import ...;

public class ActivityFunFacts extends Activity {

    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

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

        ...

That's it! After doing ONE of these fixes, your issue should go away and your app should then run! If you run into any more issues, please let us know and attach a new logcat.

Rock on! :)

Miles Torres
Miles Torres
2,316 Points

OK thank you now my app is coming up but now when i click the button it has the message again.

Harry James
Harry James
14,780 Points

Hey again Miles,

I've noticed a few further issues with the ID's that will be causing further crashes.

  • Your RelativeLayout does not have an android:id field in the XML file. You should add it and set it to the ID you are referring to in your Java program. In this case, it should be android:id="@+id/relativelayout".
  • Your factLabel is called textView2 in the XML code. Use the same steps as in my answer above and make sure that the ID you are referring to is the same in BOTH the XML and Java files.

Hopefully this should fix the rest of the errors but again, if you run into any more then please let me know and provide another Logcat here :)

Miles Torres
Miles Torres
2,316 Points

Ok in the answer above how do I fix both things?

Eleni Minadaki
Eleni Minadaki
3,687 Points

Hi Miles,please write your code from each file separate, to help you.

Miles Torres
Miles Torres
2,316 Points

package FactBook;

    import java.util.Random;

/**

  • Created by MilesPC on 12/11/2015. */ public class FactBook {

    // Member variable (properties about the object) 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: things the object can do) 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 = randomNumber + "";
    
    fact = mFacts[randomNumber];
    
    return fact;
    

    } }

Miles Torres
Miles Torres
2,316 Points

this is colorwheel

package com.example.milespc.funfacts;

import android.graphics.Color;

import java.util.Random;

/**

  • Created by MilesPC on 1/8/2016. */ public class ColorWheel {

    // Member variable (properties about the object) String[] mColors = { "#39add1", // light blue "#3079ab", // dark blue "#c25975", // mauve "#e15258", // red "#f9845b", // orange "#838cc7", // lavender "#7d669e", // purple "#53bbb4", // aqua "#51b46d", // green "#e0ab18", // mustard "#637a91", // dark gray "#f092b0", // pink "#b7c0c7" // light gray };

    // Method (abilities: things the object can do) public int getColor() {

    String color = "";
    // Randomly select a fact
    Random randomGenerator = new Random();  //Construct a new random number generator
    int randomNumber = randomGenerator.nextInt(mColors.length);
    color = randomNumber + "";
    
    color = mColors[randomNumber];
    int colorAsInt = Color.parseColor(color);
    
    return colorAsInt;
    

    } }

Miles Torres
Miles Torres
2,316 Points

and activityfunfacts.java:

package com.example.milespc.funfacts;

import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast;

import FactBook.FactBook;

public class ActivityFunFacts extends Activity { public static final String TAG = ActivityFunFacts.class.getSimpleName();

private FactBook mFactBook = new FactBook();
private ColorWheel mColorWheel = new ColorWheel();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_fun_facts);

    // Declare our View variables and assign them the views from the layout file
    final TextView factLabel = (TextView) findViewById(R.id.factTextView);
    final Button showFactButton = (Button) findViewById(R.id.button);
    final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativelayout);
    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);

            int color = mColorWheel.getColor();
            relativeLayout.setBackgroundColor(color);
            showFactButton.setTextColor(color);
        }
    };
    showFactButton.setOnClickListener(listener);
    //Toast.makeText(this, "Yay! Our Activity was created!", Toast.LENGTH_LONG).show();
    Log.d(TAG, "We're logging from the onCreate() method!");



}

private class TextView2 {
}

}

Miles Torres
Miles Torres
2,316 Points

Well where exactly do I put android:id="@+id/relativelayout and what is the exact code for fixing the factlable TextView2?

Eleni Minadaki
Eleni Minadaki
3,687 Points

The first line from your relative layout is missing. Try this: RelativeLayout android:id="@+id/relativelayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#51b46d" android:layout_alignParentTop="true" android:layout_alignParentStart="true" >

Eleni Minadaki
Eleni Minadaki
3,687 Points

Read again what Harry has answer, he explain pretty well. Let me know for anything else could help.

Eleni Minadaki
Eleni Minadaki
3,687 Points

Could you write to me the error from the logCat?

Miles Torres
Miles Torres
2,316 Points

I think this is it: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Miles Torres
Miles Torres
2,316 Points

this is everything in red: 01-20 12:28:54.309 23410-23410/com.example.milespc.funfacts E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.milespc.funfacts, PID: 23410 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.milespc.funfacts/com.example.milespc.funfacts.ActivityFunFacts}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2393) at android.app.ActivityThread.access$800(ActivityThread.java:151) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5356) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.milespc.funfacts.ActivityFunFacts.onCreate(ActivityFunFacts.java:47) at android.app.Activity.performCreate(Activity.java:6020) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2284) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2393)  at android.app.ActivityThread.access$800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1309)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5356)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

Eleni Minadaki
Eleni Minadaki
3,687 Points

I am not in my pc, I am answering you from my iPad so I don't have a clear view from your code but here I think is your solution. http://stackoverflow.com/questions/28193552/null-pointer-exception-on-setonclicklistener If you need further help send me back and I am going to answer you in some hours again. Good Luck.

Mazen Halawi
Mazen Halawi
7,806 Points

Can you point out the line that is causing the error in your java file? from the logcat its saying 47 so if you look in the gutter for that number and just state it here that should help. or you count from the first line in the java file till you get to 47.

Did you change the id of your showFactButton to "@+id/button" or is it still "@+id/showFactButton"?

Miles Torres
Miles Torres
2,316 Points

this is the line: showFactButton.setOnClickListener(listener); and no i didn't change the showFactButton to "@+id/button" should I?

Mazen Halawi
Mazen Halawi
7,806 Points

yes you SHOULD. in java you are referencing the button to id R.id.button as shown below:

final Button showFactButton = (Button) findViewById(R.id.button);

in xml you are stating:

android:id="@+id/showFactButton"

so in java it will never find that button. go to xml and change it to:

--> android:id="@+id/button" and try again.

Miles Torres
Miles Torres
2,316 Points

Ok now my app is coming up but when i press the button it says "Unfortunately, FunFacts has stopped" do you need my new logcat because it is different.

Harry James
Harry James
14,780 Points

Hey Miles,

Could you please make sure that where you have an ID like this in your activity_main.xml file:

        <...
            android:id="@+id/exampleID" <------------
            ... />

That where you refer to this specific element in Java, you use the SAME ID as referenced in your XML, like this:

final ExampleElement exampleElement = (ExampleElement) findViewById(R.id.exampleID); <------

The findViewById() method is a Java method that gets a reference to an XML element, so that you can use it in your Java code. Inside the brackets, we tell Java the ID, which is always R.id. followed by the ID you set (exampleID in this example).

Miles Torres
Miles Torres
2,316 Points

01-22 13:39:50.037 9641-9641/? I/art: Late-enabling -Xcheck:jni 01-22 13:39:50.144 9641-9641/com.example.milespc.funfacts W/ActivityThread: Application com.example.milespc.funfacts can be debugged on port 8100... 01-22 13:39:50.182 9641-9641/com.example.milespc.funfacts D/ContextHelper: convertTheme. context->name=com.example.milespc.funfacts themeResourceId=2131296304 01-22 13:39:50.199 9641-9641/com.example.milespc.funfacts I/PhoneWindow: [generateLayout] setColorNavigationBar => color=0x ff000001 01-22 13:39:50.205 9641-9641/com.example.milespc.funfacts D/PhoneWindowEx: [PWEx][generateLayout] setNavigationBarColor2 : colors=0xfff5f5f5 01-22 13:39:50.205 9641-9641/com.example.milespc.funfacts I/PhoneWindow: [setNavigationBarColor2] color=0x fff5f5f5 01-22 13:39:50.219 9641-9641/com.example.milespc.funfacts D/ActivityFunFacts: We're logging from the onCreate() method! 01-22 13:39:50.234 9641-9686/com.example.milespc.funfacts D/OpenGLRenderer: Render dirty regions requested: true 01-22 13:39:50.236 9641-9686/com.example.milespc.funfacts I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.00.042.005_msm8226_LA.BF.1.1.1_RB1__release_AU () OpenGL ES Shader Compiler Version: E031.25.03.00 Build Date: 12/29/14 Mon Local Branch: Remote Branch: quic/LA.BF.1.1.1_rb1.3 Local Patches: NONE Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.00.042.005 + NOTHING 01-22 13:39:50.240 9641-9686/com.example.milespc.funfacts I/OpenGLRenderer: Initialized EGL, version 1.4 01-22 13:39:50.294 9641-9686/com.example.milespc.funfacts D/OpenGLRenderer: Enabling debug mode 0 01-22 13:39:50.312 9641-9641/com.example.milespc.funfacts D/Atlas: Validating map... 01-22 13:39:50.416 9641-9641/com.example.milespc.funfacts I/art: Thread[1,tid=9641,WaitingForJniOnLoad,Thread*=0xb82e95a0,peer=0x76222ea8,"main"] recursive attempt to load library "/system/lib/libhook_jni.so" 01-22 13:39:50.434 9641-9641/com.example.milespc.funfacts E/MediaProfilesEx-JNI: register_com_lge_media_MediaProfilesEx 01-22 13:39:50.435 9641-9641/com.example.milespc.funfacts E/MediaRecorderEx-JNI: register_com_lge_media_MediaRecorderEx 01-22 13:39:50.436 9641-9641/com.example.milespc.funfacts D/AudioSystemEx: register_com_lge_media_LGAudioSystem 01-22 13:39:50.436 9641-9641/com.example.milespc.funfacts E/SurfaceControlEx: register_com_lge_view_SurfaceControlEx 01-22 13:39:50.437 9641-9641/com.example.milespc.funfacts I/art: Thread[1,tid=9641,WaitingForJniOnLoad,Thread*=0xb82e95a0,peer=0x76222ea8,"main"] recursive attempt to load library "/system/lib/libhook_jni.so" 01-22 13:39:50.438 9641-9641/com.example.milespc.funfacts D/LGMtpDatabaseJNI: register_android_mtp_LGMtpDatabase 01-22 13:39:50.440 9641-9641/com.example.milespc.funfacts I/art: Thread[1,tid=9641,WaitingForJniOnLoad,Thread*=0xb82e95a0,peer=0x76222ea8,"main"] recursive attempt to load library "/system/lib/libhook_jni.so" 01-22 13:39:50.443 9641-9641/com.example.milespc.funfacts D/LGMtpServerJNI: register_android_mtp_LGMtpServer 01-22 13:39:50.445 9641-9641/com.example.milespc.funfacts I/art: Thread[1,tid=9641,WaitingForJniOnLoad,Thread*=0xb82e95a0,peer=0x76222ea8,"main"] recursive attempt to load library "/system/lib/libhook_jni.so" 01-22 13:39:50.445 9641-9641/com.example.milespc.funfacts E/MediaPlayerEx-jni: register_com_lge_view_MediaPlayerEx 01-22 13:39:50.448 9641-9641/com.example.milespc.funfacts I/art: Thread[1,tid=9641,WaitingForJniOnLoad,Thread*=0xb82e95a0,peer=0x76222ea8,"main"] recursive attempt to load library "/system/lib/libhook_jni.so" 01-22 13:39:50.539 9641-9641/com.example.milespc.funfacts I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@1c08c9df time:22960293

Mazen Halawi
Mazen Halawi
7,806 Points

those logs are meaningless, cant find the exact error here. you should look for something like this:

01-20 12:28:54.309 23410-23410/com.example.milespc.funfacts E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.milespc.funfacts, PID: 23410 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.milespc.funfacts/com.example.milespc.funfacts.ActivityFunFacts}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331) at

by the way, did you give your app permission to log into the internet in the manifest file? <uses-permission permission="android.permission.INTERNET"/>

Miles Torres
Miles Torres
2,316 Points

01-22 14:29:11.847 22909-22909/com.example.milespc.funfacts E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.milespc.funfacts, PID: 22909 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.milespc.funfacts.ActivityFunFacts$1.onClick(ActivityFunFacts.java:42) the code in java now is: factLabel.setText(fact);

Miles Torres
Miles Torres
2,316 Points

also to your second thing i don't know how would i find that out.

Mazen Halawi
Mazen Halawi
7,806 Points

you are still referencing objects wrong. whatever you give your object an ID in XML you should refer to it with same name in JAVA. your textview here has ID R.id.factTextView when your xml shows @+id/textView and @+id/textView2 so i dont really know if thats what you are trying to reference. if it is you need to change the code in java to the correct textview you are trying to reference.

I advise you to study more the chapter about referencing view in java.

Miles Torres
Miles Torres
2,316 Points

Ok now I am able to click the button, but when i do, the outside color changes while the inside stays green and the fact doesn't change.

Harry James
Harry James
14,780 Points

Hey Miles,

Can you please supply your updated code files so that we can take a look?

Thanks in advance.

Miles Torres
Miles Torres
2,316 Points
activity_funfacts.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="50dp"
    android:paddingRight="50dp"
    android:paddingTop="50dp"
    android:paddingBottom="50dp"
    android:background="#51b46d"
    android:id="@+id/relativelayout"
    >

    <RelativeLayout
        android:id="@+id/relativelayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#51b46d"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        >

    </RelativeLayout>

    <TextView
        android:text="Did You Know?"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        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:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textSize="24sp"
        android:textColor="@android:color/white" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Show Another FunFact"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:background="@android:color/white" />

    </RelativeLayout>
activityfunfacts.java
package com.example.milespc.funfacts;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import FactBook.FactBook;

public class ActivityFunFacts extends Activity {
    public static final String TAG = ActivityFunFacts.class.getSimpleName();

    private FactBook mFactBook = new FactBook();
    private ColorWheel mColorWheel = new ColorWheel();

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

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

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String fact = mFactBook.getFact();
                // Update the label with our dynamic factlabel.setText(fact);

                int color = mColorWheel.getColor();
                relativeLayout.setBackgroundColor(color);
                showFactButton.setTextColor(color);

            }
        };
        showFactButton.setOnClickListener(listener);

        Toast.makeText(this, "Yay! Our Activity was created!", Toast.LENGTH_LONG).show();



    }

}
factbook.java
package FactBook;

        import java.util.Random;

/**
 * Created by MilesPC on 12/11/2015.
 */
public class FactBook {

    // Member variable (properties about the object)
    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: things the object can do)
    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 = randomNumber + "";

        fact = mFacts[randomNumber];

        return fact;
    }
}
colorwheel.java
package com.example.milespc.funfacts;

import android.graphics.Color;

import java.util.Random;

public class ColorWheel {

    // Member variable (properties about the object)
    String[] mColors = {
            "#39add1", // light blue
            "#3079ab", // dark blue
            "#c25975", // mauve
            "#e15258", // red
            "#f9845b", // orange
            "#838cc7", // lavender
            "#7d669e", // purple
            "#53bbb4", // aqua
            "#51b46d", // green
            "#e0ab18", // mustard
            "#f092b0" // pink
    };

    // Method (abilities: things the object can do)
    public int getColor() {

        String color = "";
        // Randomly select a color
        Random randomGenerator = new Random();  //Construct a new random number generator
        int randomNumber = randomGenerator.nextInt(mColors.length);
        color = randomNumber + "";

        color = mColors[randomNumber];
        int ColorAsInt = Color.parseColor(color);

        return ColorAsInt;
    }
}
Harry James
Harry James
14,780 Points

Hey Miles,

For the issue with the fact not changing, take a look at the comment you wrote:

// Update the label with our dynamic factlabel.setText(fact);

You've got this comment but you're not actually setting the factLabel to use the new text - this should be done every time the button is tapped and after we get the new fact.

So, all you need to do is add this line factLabel.setText(fact), I recommend placing it just below your comment. Watch the capitalization though! In your comment, you should have a capital for Label!


As for the issue with the color on the inside staying green, could you please expand on this? What do you mean by "the inside"?


Speak again soon :)

Seth Kroger
Seth Kroger
56,413 Points

I notice you have an empty RelativeLayout inside the root one that has the same id. Why don't you try removing the empty one and see if that corrects the color issue.

Miles Torres
Miles Torres
2,316 Points

okay, so after i put the fact label and took out the empty relative layout, i ran it, and funfacts stopped and this error came up in logcat: 02-01 13:24:55.618 10646-10646/com.example.milespc.funfacts E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.milespc.funfacts, PID: 10646 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.milespc.funfacts.ActivityFunFacts$1.onClick(ActivityFunFacts.java:44) at android.view.View.performClick(View.java:4764) at android.view.View$PerformClick.run(View.java:19844) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5356) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

What I mean by color on the iside is that the border of the screen changes color but the rectangle inside doesn't change.

Miles Torres
Miles Torres
2,316 Points

I figured out the color problem! now for the text. ;)