java—从另一个类导入int变量会使应用程序崩溃

l3zydbqr  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(343)

我正在尝试设计一个时刻表测试应用程序,其原理是给用户提供一个有12个按钮可供选择的屏幕。
当他按下一个按钮,就会打开一个新的类,用他选择的数字来测试他。
有4个主要文件:
MainActivity.java activity_main.xml Times.java activity_times.java 当前用于测试用户的类视图( activity_times.xml ),仅包含三个文本视图: "HI" id=textView "" (empty to be edited in the java class) id=TextOut "Under development...." id=textView2 第一个和最后一个文本视图并不重要,稍后将删除它们。
MainActivity.java 类i声明了一个共享变量

public int numberClicked;

然后告诉按钮将变量设置为一个特定的数字:

button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                numberClicked = 2;
                openTestPage();

            }
        });

然后在 Times.java 类i告诉它导入它和空输出文本视图:

private MainActivity MA;
private int SubjectNumber = MA.numberClicked;
private final TextView OutputText = findViewById(R.id.TextOut);

然后将文本视图设置为导入的变量:

OutputText.setText("You chose the number " + SubjectNumber);

我想要的输出是屏幕上的 TextOut 文本视图显示,例如,如果用户按下带有数字“2”的按钮:“您选择了数字2”。
但是,当第二类视图启动时,应用程序会崩溃:(
为了防止崩溃,我必须注解掉以下代码:

private MainActivity MA;
private int SubjectNumber = MA.numberClicked;
private final TextView OutputText = findViewById(R.id.TextOut);

如果我只取消三行中的一行的注解,它仍然会崩溃。我看了一下航海日志,发现了一些有趣的东西:

2020-08-23 15:20:18.553 6537-6537/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ma, PID: 6537
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.ma/com.example.ma.Times}: java.lang.NullPointerException: Attempt to read from field 'int com.example.ma.MainActivity.numberClicked' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2844)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6680)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to read from field 'int com.example.ma.MainActivity.numberClicked' on a null object reference
        at com.example.ma.Times.<init>**(Times.java:13)**
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
        at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2832)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6680) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

你在这里能找到的所有东西。
我的 AndroidManefest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ma">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Times Practice"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".Times">
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />
    </application>

</manifest>

我的 MainActivity.java ```
package com.example.ma;

import androidx.appcompat.app.AppCompatActivity;

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

public class MainActivity extends AppCompatActivity {
public int numberClicked;
private Button button2;
private Button button3;
private Button button4;
private Button button5;
private Button button6;
private Button button7;
private Button button8;
private Button button9;
private Button button10;
private Button button11;
private Button button12;
private Button button13;

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

    button2 = findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 2;
            openTestPage();

        }
    });

    button3 = findViewById(R.id.button3);
    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 3;
            openTestPage();
        }
    });

    button4 = findViewById(R.id.button4);
    button4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 4;
            openTestPage();
        }
    });

    button5 = findViewById(R.id.button5);
    button5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 5;
            openTestPage();
        }
    });

    button6 = findViewById(R.id.button6);
    button6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 6;
            openTestPage();
        }
    });

    button7 = findViewById(R.id.button7);
    button7.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 7;
            openTestPage();
        }
    });

    button8 = findViewById(R.id.button8);
    button8.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 8;
            openTestPage();
        }
    });

    button9 = findViewById(R.id.button9);
    button9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 9;
            openTestPage();
        }
    });

    button10 = findViewById(R.id.button10);
    button10.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 10;
            openTestPage();
        }
    });

    button11 = findViewById(R.id.button11);
    button11.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 11;
            openTestPage();
        }
    });

    button12 = findViewById(R.id.button12);
    button12.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 12;
            openTestPage();
        }
    });

    button13 = findViewById(R.id.button13);
    button13.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            numberClicked = 13;
            openTestPage();
        }
    });

}
public void openTestPage() {
    Intent intent = new Intent(this, Times.class);
    startActivity(intent);
}

}

我的 `activity_main.xml` :

<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".MainActivity">

<TextView
    android:id="@+id/Instructions"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/acme"
    android:gravity="center"
    android:text="Choose the number you want to practice your times tables with....."
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    android:textSize="36sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.051" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/architects_daughter"
    android:text="2"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/button5"
    app:layout_constraintEnd_toStartOf="@+id/button3"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/Instructions" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/architects_daughter"
    android:text="3"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/button6"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.501"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/Instructions" />

<Button
    android:id="@+id/button4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/architects_daughter"
    android:text="4"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/button7"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.493"
    app:layout_constraintStart_toEndOf="@+id/button3"
    app:layout_constraintTop_toBottomOf="@+id/Instructions" />

<Button
    android:id="@+id/button5"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/architects_daughter"
    android:text="5"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/button6"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.499" />

<Button
    android:id="@+id/button6"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/architects_daughter"
    android:text="6"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.501"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.499" />

<Button
    android:id="@+id/button7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/architects_daughter"
    android:text="7"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.493"
    app:layout_constraintStart_toEndOf="@+id/button6"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button8"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/architects_daughter"
    android:text="8"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/button11"
    app:layout_constraintEnd_toStartOf="@+id/button9"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button5" />

<Button
    android:id="@+id/button9"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/architects_daughter"
    android:text="9"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/button12"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button6" />

<Button
    android:id="@+id/button10"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/architects_daughter"
    android:text="10"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/button13"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/button9"
    app:layout_constraintTop_toBottomOf="@+id/button7" />

<Button
    android:id="@+id/button11"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="80dp"
    android:fontFamily="@font/architects_daughter"
    android:text="11"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/button12"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/button12"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="80dp"
    android:fontFamily="@font/architects_daughter"
    android:text="12"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/button13"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="80dp"
    android:fontFamily="@font/architects_daughter"
    android:text="13"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/button12" />

</androidx.constraintlayout.widget.ConstraintLayout>

我的 `Times.java` :

package com.example.ma;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class Times extends AppCompatActivity {

private MainActivity MA;
private int SubjectNumber = MA.numberClicked;
private final TextView OutputText = findViewById(R.id.TextOut);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_times);
    OutputText.setText("You chose the number " + SubjectNumber);

}

}

我的 `activity_times.xml` :

<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".Times">

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Under development...."
    android:textSize="28sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.503"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.696" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="HI"
    android:textSize="100sp"
    app:layout_constraintBottom_toTopOf="@+id/TextOut"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.501"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/TextOut"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="316dp"
    android:textSize="30sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

kpbpu008

kpbpu0081#

您不应该尝试从另一个活动直接访问一个活动。在android中,您将要与另一个活动共享的数据添加到intent中。您也不应该尝试获取活动生命周期之外的视图。你的 findViewById() 应移至活动的 onCreate() .
在你的第一次活动中 openTestPage() :

Intent intent = new Intent(this, Times.class);

// Add the value you want to pass to the other Activity
// to the Intent
intent.putExtra("NUMBER_CLICKED", numberClicked);

startActivity(intent);

你的第二项活动应该是这样的:

public class Times extends AppCompatActivity {

    private int SubjectNumber;

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

        // Access your views here
        TextView OutputText = findViewById(R.id.TextOut);

        // Retrieve the value passed into the Intent
        // (The 0 is a default value to fallback on. You can use another value.)
        SubjectNumber = getIntent().getIntExtra("NUMBER_CLICKED", 0);

        OutputText.setText("You chose the number " + SubjectNumber);
    }
}
1cklez4t

1cklez4t2#

您不能直接将数据从一个活动传递到另一个活动,您只需要传递intent或bundle。我正在更新你的代码。
主活动.java

public void openTestPage(int numberClicked) {
        Intent intent = new Intent(this, Times.class);
        intent.putExtra("intVariableName", numberClicked);
        startActivity(intent);
    }

时代.java

Intent intent = getIntent();
    int intValue = intent.getIntExtra("intVariableName", 0);
    OutputText.setText("You chose the number " + intValue);

相关问题