Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build a Simple Android App with Java Basic Android Programming Adding the OnClick Method

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points

App crashes when trying to run it on my phone at the end of this video

A message pops up on my phone saying "My Application has stopped" When I click "Restart app" another pop up appears saying "My Application keeps stopping" I am not using the emulator I am running it directly on my S8+ Unable to start activity ComponentInfo{com.georgesapps.myapplication/com.georgesapps.myapplication.FunFactsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference ^ I believe this to be the main cause of the issue

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points

A message in android studio appeared saying "Instant Run performed a full build and install since the installation on the device does not match the local build on disk"

I tried running it again so that I could post the Logcat error but I now have a new issue.

It appears to be an infinite loop of an error message in the Logcat. A permission window popped up on my phone when trying to get the Logcat error. I hit allow assuming it was related to the app and then this loop happened. It is as follows:

im=#20 ty=2226 fl=#1800148 pfl=0x50 fmt=-2 vsysui=0x2000 naviIconColor=0} 03-22 12:06:09.710 724-993/? I/qti_sensorhub_hal: AUTOROTATION_REPORT_IND 03-22 12:06:09.710 724-993/? D/qti_sensorhub_hal: AutoRotation 255 ts: 208641707 03-22 12:06:09.710 1171-1749/? D/SensorHubManager: onGetSensorHubDataLocked: library(4) = 1, 1, 7, -1 03-22 12:06:09.711 1171-1748/? D/CAE: onGetSensorHubData(SensorHubParserProvider.java:94) - onGetSensorHubData Event [event buffer len :4], AP_WAKEUP 03-22 12:06:09.711 1171-1748/? I/CAE: parse(SensorHubParserProvider.java:196) - buffer size = 4 03-22 12:06:09.711 1171-1748/? I/CAE: parse(SensorHubParserProvider.java:207) - 1, 1, 7, -1, 03-22 12:06:09.711 1171-1748/? D/CAE: display(ContextProvider.java:375) - ================= AUTO_ROTATION ================= 03-22 12:06:09.712 1171-1748/? I/CAE: display(ContextProvider.java:391) - Angle=[-1] 03-22 12:06:09.713 1171-1751/? D/SemContextService: updateContext() : event = Auto Rotation 03-22 12:06:09.713 1171-1171/? D/SemContextManager: onSemContextChanged() : event = Auto Rotation Angle : -1 03-22 12:06:09.713 1171-1171/? D/SContextManager: onSContextChanged() : event = Auto Rotation Angle : -1 03-22 12:06:09.713 1171-1171/? V/WindowOrientationListener: OrientationSensorJudge.onSContextChanged, Rotation: -1 03-22 12:06:09.715 5080-5080/? D/ViewRootImpl@eb8f18[CocktailBarService]: Relayout returned: oldFrame=[1013,605][1080,1060] newFrame=[1013,605][1080,1060] result=0x1 surface={isValid=true 547564653056} surfaceGenerationChanged=false 03-22 12:06:09.720 1171-3163/? D/WindowManager: finishDrawingWindow: Window{14bd4fad0 u0 com.samsung.android.app.cocktailbarservice/com.samsung.android.app.cocktailbarservice.CocktailBarService} mDrawState=DRAW_PENDING 03-22 12:06:09.732 1961-1961/? D/KeyguardWallpaperController: onLayoutChange() v: com.android.systemui.statusbar.BackDropView{684f50e I.E...... ......ID 0,0-1080,63 #7f1304c4 app:id/backdrop}, bottom : 63, oldBottom : 2220 03-22 12:06:09.732 1961-1961/? D/KeyguardWallpaperController: mShowing=false, mOccluded=false, mFadingAway=false, match_parent=false 03-22 12:06:09.745 1171-4192/? V/WindowManager: Relayout Window{e830b4ad0 u0 Bouncer}: viewVisibility=4 req=1080x0 WM.LayoutParams{(0,0)(fillx0) gr=#30 sim=#10 ty=2009 fl=#81000148 fmt=-3 or=5 vsysui=0x610 if=0x4 userActivityTimeout=3000 screenDimDuration=0 sfl=0x40000} 03-22 12:06:09.752 1961-1961/? D/ViewRootImpl@6f43096[Bouncer]: Relayout returned: oldFrame=[0,0][1080,0] newFrame=[0,0][1080,0] result=0x1 surface={isValid=false 0} surfaceGenerationChanged=false 03-22 12:06:09.768 5080-5080/? D/TrayStateTrigger: showTriggerView 03-22 12:06:09.850 2707-2707/? D/io_stats: !@ 8,0 r 226308 11184052 w 159982 2446716 d 10530 1171212 f 69348 70691 iot 196710 141451 th 369060 0 0 pt 0 inp 0 0 4174.166

Hi George,

The null pointer exception will do that, yes.

Can you paste all the Logcat error in here and also the code at the point the exception is being thrown, please. We can get you fixed, then!

Steve.

17 Answers

Aha!! We have an answer!

Change:

<Button
  android:id="@+id/ShowFactButton"

to:

<Button
  android:id="@+id/showFactButton"

Lower case S. So, your layout wasn't linking to your code because the names didn't match.

Let me know if that fixes it.

Steve.

Those don't look like the null pointer - can you find that part of the error output?

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points

This new error continues even without me running the app I dont think I can get the null pointer. As soon as I plugged my phone back in loop continues

I don't see any errors in your Logcat trace - those are just runtime messages. Android is very talkative! Does your app run now?

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points

As soon as I open android studio those messages start again, it is much more than what I pasted in my original comment. When I hit run the app still crashes immediately

If you have your device connected to the computer, it'll chat constantly in Logcat. They aren't errors, they're just notifications of what is going on.

If the app in crashing, you can filter the Logcat output to just show messages from your app. Give that a go and paste it in here.

Logcat doesn't just show errors, it talks constantly about the state of everything. You need to filter it down to the relevant messages. You can filter by message-type or by source-application.

If your app is crashing, there will be Logcat output to say why. That's what it does.

Steve.

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points

03-22 18:57:53.011 4968-4968/? E/Zygote: v2 03-22 18:57:53.012 4968-4968/? E/Zygote: accessInfo : 0 03-22 18:57:53.312 4968-4968/com.georgesapps.myapplication E/AndroidRuntime: FATAL EXCEPTION: main Process: com.georgesapps.myapplication, PID: 4968 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.georgesapps.myapplication/com.georgesapps.myapplication.FunFactsActivity}: 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:2984) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) at android.app.ActivityThread.-wrap14(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6776) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 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.georgesapps.myapplication.FunFactsActivity.onCreate(FunFactsActivity.java:29) at android.app.Activity.performCreate(Activity.java:6955) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)  at android.app.ActivityThread.-wrap14(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6776)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

That looks like it has the error. Now we just need the code around the exception. Midnight here now; I have a new contract meeting in the morning so I'm signing off. Post your code and I'll look tomorrow afternoon.

Steve.

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points

I think this is the code around the exception:

 final TextView factTextView = findViewById(R.id.factTextView);

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

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

            @Override

            public void onClick(View view) {

                // The button was clicked so update the fact TextView with a new fact

                String newFact = "Ostriches can run faster than horses";

                factTextView.setText(newFact);

            }
        };
        showFactButton.setOnClickListener(listener);

The exception is on line 29 of FunFactsActivity - which line is that?

I'm going to make a guess here. You have declared your TextView to be final. That makes it unmodifiable; i.e. a constant. Now, that might be OK, as you have assigned R.id.factTextView into it and that doesn't change. But I might be wrong - maybe you can't call setText() on a constant. I'd delete the final keyword - it isn't there in the video.

Secondly, have you redeclared both your factTextView and your showFactButton? You should have created these variables outside of onCreate; that's where your code is taken from. At the top of the class, you should have:

public class FunFacstActivity extends AppCompatActivity {
  private TextView factTextView;
  private Button showFactButton

The in onCreate you should have:

protected void onCreate(Bundle savedInstanceState){
  // call to super etc

  factTextView = (TextView) findViewById(R.id.factTextView);
  showFactButton = (Button) findViewById(R.id.showFactButton);

  // onClick
}

So, you don't repeat the TextView or Button keyword prefix - if you do, you change the scope of the variable, so maybe post the whole of your activity code so I can see what you have got. Also, note the type cast when returning the view by id - in older Android versions, you need to prefix the assignment with (TextView) and (Button) to make sure the returned view is changed to the correct type. I don't think this persists in newer Android versions, but maybe leave it in here if it isn't throwing errors.

So, best to post all your code in here so we can make sure we've caught everything.

Steve.

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points
public class FunFactsActivity extends AppCompatActivity {

    private TextView factTextView;
    private Button showFactButton;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fun_facts);
        // Assign the Views from the layout file to the corresponding variables

        TextView factTextView = findViewById(R.id.factTextView);
        Button showFactButton = findViewById(R.id.showFactButton);

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

            @Override

            public void onClick(View view) {
                // The button was clicked so update the fact TextView with a new fact
                String newFact = "Ostriches can run faster than horses";
                factTextView.setText(newFact);
            }
        };
        showFactButton.setOnClickListener(listener);
    }

}

Thanks - try changing this:

        TextView factTextView = findViewById(R.id.factTextView);
        Button showFactButton = findViewById(R.id.showFactButton);

to this:

        factTextView = findViewById(R.id.factTextView);
        showFactButton = findViewById(R.id.showFactButton);

You are redeclaring your variables which will cause scope issues which may generate a null pointer if access is attempted outside their existing scope.

Steve.

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points

I removed the Textview and Button prefixes and attempted to run the app and got this error:

Process: com.georgesapps.myapplication, PID: 13756 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.georgesapps.myapplication/com.georgesapps.myapplication.FunFactsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Can you find the error that references the line number in the activity?

Oops! I forgot the cast - add the data types to cast the returned views:

        factTextView = (TextView) findViewById(R.id.factTextView);
        showFactButton = (Button) findViewById(R.id.showFactButton);
George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points

I'm sorry I can't find where it says the line number where the error occured. I will copy the entire error message.

03-23 10:58:36.883 17260-17260/? E/Zygote: isWhitelistProcess - Process is Whitelisted 03-23 10:58:36.884 17260-17260/? E/libpersona: scanKnoxPersonas 03-23 10:58:36.884 17260-17260/? E/libpersona: Couldn't open the File - /data/system/users/0/personalist.xml - No such file or directory 03-23 10:58:37.266 17260-17260/com.georgesapps.myapplication E/AndroidRuntime: FATAL EXCEPTION: main Process: com.georgesapps.myapplication, PID: 17260 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.georgesapps.myapplication/com.georgesapps.myapplication.FunFactsActivity}: 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:2955) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) at android.os.Handler.dispatchMessage(Handler.java:105) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6938) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 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.georgesapps.myapplication.FunFactsActivity.onCreate(FunFactsActivity.java:32) at android.app.Activity.performCreate(Activity.java:7174) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)  at android.os.Handler.dispatchMessage(Handler.java:105)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6938)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

Line 32 - I'll highlight the message in your paste.

Highlighted in bold above so you know what to look for. :smile:

It's the showFactButton is containing nothing, is null, Try adding the cast as above. That might fix it.

Yes, add the cast:

showFactButton = (Button) findViewById(R.id.showFactButton);
              // ^^ that's the cast

See if that fixes the issue, or moves it.

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points

when I cast, the "(Button)" has a squiggly line under it saying casting to button is redundant. I'm not sure that the cast is the issue because I have a very recent version of android studio

Yes, that makes sense ... so... next ideas ...

Can you paste in your XML layout file, please?

George Brandt
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
George Brandt
Python Development Techdegree Graduate 9,649 Points
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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:background="#51b46d"

    android:padding = "50dp"

    tools:context="com.georgesapps.myapplication.FunFactsActivity">


    <TextView

        android:id="@+id/textView2"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Did you know?"

        android:textColor="#80ffffff"

        android:textSize="24sp" />


    <TextView

        android:id="@+id/factTextView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true"

        android:layout_centerVertical="true"

        android:text="Ants stretch when they wake up in the morning"

        android:textColor="@android:color/white"

        android:textSize="24sp" />


    <Button

        android:id="@+id/ShowFactButton"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_alignParentBottom="true"

        android:layout_centerHorizontal="true"

        android:background="@android:color/white"

        android:text="SHOW ANOTHER FUN FACT" />


</RelativeLayout>

Excellent! :smile: :dizzy: :sparkles: :+1: