Ed Briscoe
Ed Briscoe

Reputation: 117

Android - Selecting different spinner option doesn't update calculation in TextView, only working on 1st item in list

I have a simple spinner which has several number options. I want to just select a number and then it does some math to that number and outputs it in a text box. For some reason it's only doing math on the 1st entry in the list and if you change it doesn't update.

Any ideas?

package placeorder.com;

import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Spinner;
import android.widget.TextView;

public class Time extends Activity{ 

    double totalhours, cost;
    int price;
    TextView total, orderid;    

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.time);

        Spinner spinhours = (Spinner) findViewById(R.id.sp_hours);
        total = (TextView) findViewById(R.id.tv_total); 
        orderid = (TextView) findViewById(R.id.tv_orderid); 

        Random order = new Random();
        int randomorder = order.nextInt(9999);      
        order.nextInt(9999);                
        orderid.setText("Order ID: "+randomorder);      

        price = 5;                    
        String hours = spinhours.getSelectedItem().toString();
        totalhours = Integer.parseInt(hours);       
        cost = totalhours * price;              
        total.setText("£" + cost);              


    }



}

Upvotes: 0

Views: 421

Answers (1)

Samir Mangroliya
Samir Mangroliya

Reputation: 40416

You should add listener for spinner

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                 String str = (String) arg0.getSelectedItem();

                 outputTextview.setText(str);

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });

Upvotes: 1

Related Questions