简体   繁体   中英

Android Button throws IllegalStateException

So I'm trying to build the base of a simple app where I can switch activities with a button click. I have this working fine for my main activity to my second activity; however, I can't get it to work going back to the main activity.

Currently I am getting this error when I click the button: java.lang.IllegalStateException : Could not find method NewBack(View) in a parent or ancestor Context for android:onClick attribute defined on view class com.google.android.material.button.MaterialButton with id 'back'

Heres the code in the second activity:

package com.example.homework4;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class CreateQuestion extends AppCompatActivity {

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

    public void NewBack(View v){
        setContentView(R.layout.activity_main);
    }

}

Here is the code for the button in my xml file:

<Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="153dp"
        android:onClick="NewBack"
        android:text="GO BACK"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/submit" />

I have also tried setting an onClickListener with the same results. I'm sure this is an easy fix, I just can't seem to figure it out!

If You want to navigate between activities you need to replace

public void NewBack(View v){
    setContentView(R.layout.activity_main);
}

with

public void newBack(View v){
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);

}

PS don't use Upercase in function name. So if the function is called newBack

change it also in XML file like:

<Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="153dp"
        android:onClick="newBack"
        android:text="GO BACK"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/submit" />

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