多个 if 语句的意图

Intent with multiple if statements

我正在学习 Intents 的概念,当我尝试从不是“Arabica”意图的任何其他意图出发时,我正在处理的应用程序崩溃了,意图对象在微调器上的 onItemSelectedListener 上触发。我想这样做,以便当用户在微调器上选择其他选项时,它将执行该意图并转到另一个 activity,它显示我的咖啡应用程序的文本代码。

代码如下:

public class MainActivity extends AppCompatActivity {

private Spinner spinner;

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

    spinner = findViewById(R.id.List);

    List<String> categories = new ArrayList<>();
    categories.add(0, "Choose Category");
    categories.add("Arabica");
    categories.add("Liberica");
    categories.add("Robusta");
    categories.add("Excelsa");

    ArrayAdapter<String> dataAdapter;
    dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, categories);

    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spinner.setAdapter(dataAdapter);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            if (parent.getItemAtPosition(position).equals("Choose Category"))
            {

            }
            else
            {
                String item = parent.getItemAtPosition(position).toString();

                Toast.makeText(parent.getContext(), "Selected: " +item, Toast.LENGTH_SHORT).show();

                if (parent.getItemAtPosition(position).equals("Arabica")) {
                    Intent intent = new Intent(MainActivity.this, Arabica.class);
                    startActivity(intent);
                } else if (parent.getItemAtPosition(position).equals("Liberica")) {
                    Intent intent = new Intent(MainActivity.this, Liberica.class);
                    startActivity(intent);
                } else if (parent.getItemAtPosition(position).equals("Robusta")) {
                    Intent intent = new Intent(MainActivity.this, Robusta.class);
                    startActivity(intent);
                } else if (parent.getItemAtPosition(position).equals("Excelsa")) {
                    Intent intent = new Intent(MainActivity.this, Excelsa.class);
                    startActivity(intent);
                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

}

这里是 xml:

<TextView
    android:id="@+id/MainTitle"
    android:layout_width="199dp"
    android:layout_height="143dp"
    android:layout_marginStart="16dp"
    android:text="Selecciona un nombre cientifico para ver su descripcion"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    android:textSize="24sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.047"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.022" />

<Spinner
    android:id="@+id/List"
    android:layout_width="268dp"
    android:layout_height="48dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.559"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.499" />

<Button
    android:id="@+id/Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="60dp"
    android:text="Caracteristicas del Cafe"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/List" />

这也是我的清单:

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.CoffeeAssessor">
    <activity
        android:name=".Excelsa"
        android:exported="false" />
    <activity
        android:name=".Liberica"
        android:exported="false" />
    <activity
        android:name=".Robusta"
        android:exported="false" />
    <activity
        android:name=".Arabica"
        android:exported="false" />
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

最后是错误日志:

2021-11-01 12:52:48.840 10365-10365/com.revolution.coffeeassessor E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.revolution.coffeeassessor, PID: 10365
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.revolution.coffeeassessor/com.revolution.coffeeassessor.Liberica}: 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:2416)
    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 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
    at com.revolution.coffeeassessor.Liberica.onCreate(Liberica.java:21)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    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) 

我没有为按钮实现 setOnCLickListener,但我不认为这是我的 onCreate 的问题,尽管我使用了所有 Liberica 代码:

public class Liberica extends AppCompatActivity {

Button back2;

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

    back2 = findViewById(R.id.back);

    back2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Liberica.this, MainActivity.class);
            startActivity(intent);
        }
    });
}

}

和我的 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="com.revolution.coffeeassessor.Liberica">

<TextView
    android:id="@+id/LibericaTitle"
    android:layout_width="219dp"
    android:layout_height="74dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:text="Libérica (Coffea Libérica)"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    android:textSize="24sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/LibericaDescription"
    android:layout_width="321dp"
    android:layout_height="533dp"
    android:text=" Esta variedad es originaria de Monrovia (Liberia), de donde toma su nombre. El aroma y sabor de este grano de café es muy peculiar, por lo que su consumo está muy poco extendido, se centra principalmente en los países Escandinavos. "
    android:textAppearance="@style/TextAppearance.AppCompat.Body1"
    android:textSize="24sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/back2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginBottom="16dp"
    android:text="Back"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

原因是打错了。在 Liberica Class 中更改此行:

back2 = findViewById(R.id.back);

为此:

back2 = findViewById(R.id.back2);

因为按钮的实际 id 是 back2 而不是 back 如您所见:

<Button
    android:id="@+id/back2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginBottom="16dp"
    android:text="Back"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

还要确保 setContentView(R.layout.activity_main); 在 Liberica 中 Class 指向 Liberica XML 布局文件,例如如果它被调用 activity_liberica.xml 将其设置为:

setContentView(R.layout.activity_liberica);