简体   繁体   中英

How to call a method from a Spinner listener - Android

I would like to auto run a conversion method when a new unit is selected from the dropdown Spinner menu. The code works ok to update a TextView object with the newly selected option so the listener is working ok. When I add a method call it crashes and the app won't even start, any ideas why this might be?

spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String str = ((TextView) view).getText().toString();
            unitsInput.setText(str); 

            convert();
        }

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

        } 

    });

I think I have found the problem my initial value in the input space was a blank string "" and it was not happy about it on start up.

Log:

 06-25 10:36:47.340: E/AndroidRuntime(1312): java.lang.NumberFormatException: Invalid double: ""
06-25 10:36:47.340: E/AndroidRuntime(1312):     at java.lang.StringToReal.invalidReal(StringToReal.java:63)
06-25 10:36:47.340: E/AndroidRuntime(1312):     at java.lang.StringToReal.parseDouble(StringToReal.java:248)
06-25 10:36:47.340: E/AndroidRuntime(1312):     at java.lang.Double.parseDouble(Double.java:295)

Setting the initial value to 1 in the input EditText space has solved the problem and allowed the app to run again and run the convert() method upon selecting something from the drop down spinner.

However, if was to leave the initial input blank or empty "" then it still does not work. If i include an if statement clause like

 if(!"".equals(str)){
                convert();
            }

or

 if(!str.equals("")){
                convert();
            }

It crashes on launch.

Does anyone know how to implement the method call using a Spinner Listener and a blank String?

Try this..

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String str = ((TextView) view).getText().toString();
        unitsInput.setText(str); 

        if(!str.equals(""))
             convert();
    }

Just as an update I got this working as I wanted using the following code for anyone with a similiar problem

 spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String str = ((TextView) view).getText().toString();
            unitsInput.setText(str); 

            if(!"".equals(valueInput.getText().toString())){
                convert();
            }
        }

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