Skip to content Skip to sidebar Skip to footer

How Can I Set My Enum With The Value The User Enter In A Edittext?

I have a editText where the users enter a number between 0 and 10. Depending on their entered number the enum (knowledge) will set. Here's my code so far: public int fromUserInput(

Solution 1:

The else condition shouldn't be in that class.

You want something like:

public Wissenstand Bestätigung(View v) {
    TextViewuWissen= (TextView) findViewById(R.id.textView_Wissen_Titel);
    TextViewpWarung= (TextView) findViewById(R.id.textView_Wissen);
    TextVieweWissen= (TextView) findViewById(R.id.editText_eingabeWissentsstand);

    knowledge = Wissenstand.fromUserInput( Integer.parseInt( eWissen.getText().toString() );

    if(knowledge == null){
         uWissen.setText("Fehler gefunden!");
         uWissen.getResources().getColor(android.R.color.holo_red_dark);
         pWarung.setText("Gib eine Zahl von 0 bis 10 ein!\n0,5-er Schritte sind nicht erlaubt!\nWeitere Informationen kannst du der Legende entnehmen!");
         pWarung.getResources().getColor(android.R.color.holo_red_light);
    }
}

Solution 2:

findViewById is not a "magical method" that looks for your views. It's actually a method of View or Activity

Inside your enum class you shouldn't use that kind of stuff. Just check the int value and if it's out of range throw an IllegalArgumentException:

static Wissenstand fromUserInput(finalint input){
        if (input >= 10) {
            return GRANDMASTER;
        } elseif (input >= 7) {
            return PRO;
        } elseif (input >= 4) {
            return FORTGESCHRITTENER;
        } elseif (input >= 0) {
            return BEGINNER;
        } else {
            thrownewIllegalArgumentException("Invalid value");    
        }
    }

When calling fromUserInput you should add the corresponding try-catch

Post a Comment for "How Can I Set My Enum With The Value The User Enter In A Edittext?"