lundi 1 novembre 2021

Intent with multiple if statements

I am learning the concept of Intents and the application I am working on crashes when I try to go from any other intent that's not "Arabica" intent, the intent object is fired on onItemSelectedListener on a spinner. I want to make it so that when the user selects the other options on the spinner it will execute that intent and go to the other activity which displays a code of text for my coffee application.

Below is the code:

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) {

        }
    });
}

}

Here is the 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" />

Here is also my manifest:

<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>

Finally here is the error log:

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) 

I didn't implement a setOnCLickListener for the button but i dont think that's the issue here is my onCreate though with all my Liberica code:

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

}

and my 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" />

Aucun commentaire:

Enregistrer un commentaire