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

Importing int variable from another class crashes app


我正在尝试设计一个时间 table 测试应用程序,理论上是向用户呈现一个带有 12 个按钮的屏幕 select。
当他按下一个按钮时,它会打开一个新的 class 测试他选择的数字。
主要有4个文件:
  1. MainActivity.java
  2. activity_main.xml
  3. Times.java
  4. activity_times.java


当前用于测试用户的 class 视图 (activity_times.xml),仅包含三个文本视图:

  1. "HI" id=textView
  2. "" (empty to be edited in the java class) id=TextOut
  3. "Under development...." id=textView2

第一个和最后一个文本视图并不重要,稍后会删除它们。
MainActivity.javaclass我声明了一个共享变量

public int numberClicked;

然后告诉按钮将变量设置为某个数字:

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

            }
        });

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

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”。
但取而代之的是,应用程序在第二个 class 视图启动时崩溃 :(
为了防止它崩溃,我必须注释掉以下代码:

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

如果我只取消注释三行中的一行,它仍然会崩溃。 我查看了 logcat 并看到了一些有趣的东西:

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) 

从 logcat 出来的每一件事你都会发现 here

我的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:

<?xml version="1.0" encoding="utf-8"?>
<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:

<?xml version="1.0" encoding="utf-8"?>
<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>

您不能直接将数据从一个 activity 传递到另一个,您只需要通过 intent 或 bundle。我正在更新您的代码。

MainActivity.java

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

Times.java

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

您不应尝试从另一个 Activity 直接访问一个 Activity。在 Android 中,您将要与另一个 Activity 共享的数据添加到 Intent 中。您也不应该尝试在 Activity 生命周期之外获取视图。您的 findViewById() 应移至 Activity 的 onCreate()

在你的第一个 Activity 中 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);

你的第二个 Activity 应该看起来像这样:

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);
    }
}