简体   繁体   中英

Android Studio - button that opens activity - another button in it that opens new activity

This is my first post on this site so I'll be short!

I'm new in Android Studio, and trying to make an app.. Problem occures here: I create a button an code it so it redirectes to new activity when pressed. That work's fine on emulator. Then in that new activity I create another button that redirects to another acrivity and code it on the same way as previous button (ofc I change names and all of that) but when running app on emulator first button works just fine and then I press on second button. It gives me a app force close error.. I don't get it, why, Android Studio does not report any error in code, but that new button just wont work.

I created those buttons with this tutorial: http://developer.android.com/training/basics/firstapp/starting-activity.html

Anyone knows solution?

content_my.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="horizontal"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.dario.mojaaplikacija.MyActivity"
    tools:showIn="@layout/activity_my">

    <Button
        android:id="@+id/button_vjezbe"
        android:text="@string/button_vjezbe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="vjezbe" />

</LinearLayout>


MyActivity.java

    public class MyActivity extends AppCompatActivity {
    public final static  String EXTRA_MESSAGE ="com.example.dario.mojaaplikacija";
    public void vjezbe(View view){
        Intent intent = new Intent(this, BenchPress.class);
       // String varijabla = editText.getText().toString();
        //intent.putExtra(EXTRA_MESSAGE, varijabla);
        startActivity(intent);



content_bench_press.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:id="@+id/content"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.dario.mojaaplikacija.BenchPress"
    tools:showIn="@layout/activity_bench_press">

    <Button
        android:text="@string/button_o_benchu"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:onClick="benchA"/>

</LinearLayout>





BenchPress.java

public class BenchPress extends AppCompatActivity {
    public final static String EXTRA_MESSAGE = "com.example.dario.mojaaplikacija";

     public void benchA (View view){
        Intent intent = new Intent(this, BenchA.class);
        startActivity(intent);



content_bench.xml

    <?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:id="@+id/conten"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.dario.mojaaplikacija.BenchA"
    tools:showIn="@layout/activity_bencha">

</RelativeLayout>



BenchA.java

    Intent intent = getIntent();
    String message = intent.getStringExtra(BenchPress.EXTRA_MESSAGE);


strings.xml

    <resources>
    <string name="app_name">MojaAplikacija</string>
    <string name="action_settings">Settings</string>
    <string name="button_vjezbe">Vježbe</string>
    <string name="title_activity_display_message">MyMessage</string>
    <string name="title_activity_bench_press">BenchPress</string>
    <string name="button_o_benchu">Bench</string>
    <string name="title_activity_bench">BenchA</string>
</resources>

RED code I get when clicking on that second button:

01-09 22:27:23.091 2431-2431/com.example.dario.mojaaplikacija E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.dario.mojaaplikacija, PID: 2431
                                                                                java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.dario.mojaaplikacija/com.example.dario.mojaaplikacija.BenchA}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
                                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
                                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                                    at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                    at android.os.Looper.loop(Looper.java:148)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                                 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
                                                                                    at com.example.dario.mojaaplikacija.BenchA.<init>(BenchA.java:30)
                                                                                    at java.lang.Class.newInstance(Native Method)
                                                                                    at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
                                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
                                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                                    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                    at android.os.Looper.loop(Looper.java:148) 
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                                    at java.lang.reflect.Method.invoke(Native Method) 
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

BenchA.java

package com.example.dario.mojaaplikacija;

import android.content.Intent;
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.view.View;

public class BenchA extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bencha);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

        Intent intent = getIntent();
        String message = intent.getStringExtra(BenchPress.EXTRA_MESSAGE)

;

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
                                                                                    at com.example.dario.mojaaplikacija.BenchA.<init>(BenchA.java:30)

This tells you to check line 30 in BenchA

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.dario.mojaaplikacija/com.example.dario.mojaaplikacija.BenchA}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference

This tells you that you have a null pointer exception. You can read about it on stackoverflow some more but it basically means you tried to call getStringExtra on intent, but the intent object is null.

Intent intent = getIntent(); returns null. It couldn't find it. That's why the subsequent line crashes. Wrap the following line in if (intent != null) to avoid NullPointerException

To solve the problem, I don't want to recommend you stray too far from the tutorial but one option is to pass in a Bundle and in your new activity's onCreate, you can to get the bundle.

Another thing: in the BenchPress class you never passed it any String extras. So you are trying to get a string that was never on the intent to begin with. String message will return null;

EDIT: Now that you've posted your class, it appears that getIntent is floating in as an attribute of the ActivityClass. Sure, Java is ok with that since you are merely defining this in those two lines. But if you were to write an instruction, for instance, print out your message or show text, it cannot compile. Drop the two lines Intent intent... and String message... into your onCreate. I strongly believe this is the reason getIntent() returned null. The class didn't have access to getIntent(), but when you override the oncreate method, you do have access to getIntent()

EDIT:

Here's what you should do instead, this is what you intended to grab:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bencha);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Intent intent = getIntent();
    String message = intent.getStringExtra(BenchPress.EXTRA_MESSAGE)

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

Make this two methods:

The onClick method for the first button:

public void onClickFirstButton(View view){
    //your code go here...   
    Intent intent = new Intent(this, the_name_class_of_new_activity.class);
    startActivity(intent);//you can start the new activity at any time with this line
}

For the second button is the same method(change the name of method and put the name of your second new activity.

public void onClickSecondButton(View view){
        //your code go here...
        Intent intent = new Intent(this, the_name_class_of_second_new_activity.class);
        startActivity(intent);//you can start the new activity at any time with this line
}

I can't believe this! I solved it!!

My BenchA.java now looks like this:

package com.example.dario.mojaaplikacija;

import android.content.Intent;
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.view.View;

public class BenchA extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bencha);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                Intent intent = getIntent();

                if (intent !=null) {
                    String message = intent.getStringExtra(BenchPress.EXTRA_MESSAGE);
                }    }
        });
    }

}

just putted that if statement inside the class and the button works!

Still getting some red code:

01-10 00:03:56.469 2567-2584/com.example.dario.mojaaplikacija E/Surface: getSlotFromBufferLocked: unknown buffer: 0xabef7ee0

01-10 00:03:58.755 2567-2584/com.example.dario.mojaaplikacija E/Surface: getSlotFromBufferLocked: unknown buffer: 0xabef9290

Don't know what that means, but the main thing is that it's working!!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM