简体   繁体   中英

Android spinner showing error to user if they select first item from the options Android studio

how can I show error / not let the user proceed forward if they have selected the first item from the dropdown?

I have these options

<string-array name="planets_array">
        <item>Choise a planet</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
        <item>Jupiter</item>
        <item>Saturn</item>
        <item>Uranus</item>
        <item>Neptune</item>
    </string-array>

However, as shown in the item lists, my first option is "Choose a planet" which is show just as default option to guide/show to user what the dropdown is about. However, when user selects this I don't want them to proceed and show them an error stating something 'please choose a planet'.

I have created an if statement how it doesn't seem to work;

    if (parent.getItemAtPosition(position).toString() == "Choose a planet") {
        Toast.makeText(getActivity(), "Pleae choose a valid planet", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getActivity(), categoryChosen + " is a valid planet", Toast.LENGTH_LONG).show();
    }

btw, I am working with fragment, that is why I have 'getActivity()', instead of 'this'.

You are comparing String not object. So use .equals()

if (parent.getItemAtPosition(position).toString().equals("Choose a planet"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM