Android, spinner not updating

93 views Asked by At

I have a spinner that works. But, when I try to change the selection, it does not update.

This is the app principle: you select a loction, Barcelona for example and you should see the price, 30 € for example.

But, as I explained, if you change the location to something else, the price does not change.

This is the code (some bits are in Spanish):

@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {


    if (pos == 0){
        priceAdulto = 34.00;
        priceNino = 28.00;

        setContentView(R.layout.activity_my);
        TextView textViewAdulto = (TextView) findViewById(R.id.textView3);
        textViewAdulto.setText(priceAdulto.toString());
        TextView textViewNino = (TextView) findViewById(R.id.textView4);
        textViewNino.setText(priceNino.toString());

        Toast.makeText(getApplicationContext(), "Updated",
                Toast.LENGTH_SHORT).show();
    }
    if (pos == 1){
        priceAdulto = 25.00;
        priceNino = 22.00;
        setContentView(R.layout.activity_my);
        TextView textViewAdulto = (TextView) findViewById(R.id.textView3);
        textViewAdulto.setText(priceAdulto.toString());

        setContentView(R.layout.activity_my);
        TextView textViewNino = (TextView) findViewById(R.id.textView4);
        textViewNino.setText(priceNino.toString());

        Toast.makeText(getApplicationContext(), "Updated",
                Toast.LENGTH_SHORT).show();

    }
    if (pos == 2) {
        priceAdulto = 43.50;
        priceNino = 39.00;
        setContentView(R.layout.activity_my);
        TextView textViewAdulto = (TextView) findViewById(R.id.textView3);
        textViewAdulto.setText(priceAdulto.toString());

        setContentView(R.layout.activity_my);
        TextView textViewNino = (TextView) findViewById(R.id.textView4);
        textViewNino.setText(priceNino.toString());

        Toast.makeText(getApplicationContext(), "Updated",
                Toast.LENGTH_SHORT).show();
    }
2

There are 2 answers

0
Phantômaxx On BEST ANSWER

Your error is in continously setting the ContentView.
This resets the Views to their initial state.

You should set the layout only once.
Possibly in the onCreate (if you are in an Activity) or in onCreateView (if you are in a Fragment).

Also, since you are working with numbers, a more elegant way of performing multiple condition checks would be using a switch(pos){...}

0
AndroidGeek On

Set the content view only once, doing it multiple times takes it back to the beginning. Use set content view in on create, and that's it. Hope it works.