Dream
Dream

Reputation: 19

How can I select a string spinner and convert it into an Integer

I was making a android app, I want the user to click to spinner to select the category that has "General", "Important", and "Urgent". Then, I want to convert their choice into an integer something like

IF (category=="General"){
    choice=1;
}

but turns out my app keep on crashing when i run it, heres my code.

package com.example.to_do_app;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.lang.reflect.Array;

public class DialogActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private int catechoice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog);

        Spinner category= findViewById(R.id.taskcate);
        ArrayAdapter<CharSequence> cateadapter = ArrayAdapter.createFromResource(this,R.array.category, R.layout.spinner_item);
                cateadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                category.setAdapter(cateadapter);
                category.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String text= parent.getItemAtPosition(position).toString();
        if (text == "General"){
            catechoice=0;
        }
        else if (text=="Important"){
            catechoice=1;
        }
        else if (text=="Urgent"){
            catechoice=2;
        }
        Toast.makeText(parent.getContext(),catechoice,Toast.LENGTH_SHORT).show();
    }

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

    }
}


Upvotes: 0

Views: 98

Answers (1)

amir aghataher
amir aghataher

Reputation: 61

change this code

Toast.makeText(parent.getContext(), catechoice, Toast.LENGTH_SHORT).show();

with this code

Toast.makeText(parent.getContext(), String.valueOf(catechoice), Toast.LENGTH_SHORT).show();

for check string use equal . change this text == "General" to text.equal( "General") and I prefer you create enum and use switch like this

public enum Category {

General, Important,Urgent

}

and use this method

  private int categoryChecker(String text) {

    switch (Category.valueOf(text)) {

        case General:
            return 0;

        case Important:
            return 1;

        case Urgent:
            return 2;

        default:
            throw new IllegalStateException("Unexpected value: " + text);
    }

}

Upvotes: 2

Related Questions