Search code examples
androidandroid-intentandroid-activity

How to pass data from a Spinner to other activity?


I'm working on an application that consists on a shopping cart, where the user selects which pizza and which drink he wants, using a spinner for each selection. I have been working for a week on how to send the data selected in the spinner to the next activity and display it on a textview, but I don't know how to do it.

My both spinners are working correctly.

Code for the spinner

    Spinner spinner = findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = 
    ArrayAdapter.createFromResource(this,
    R.array.numbers, android.R.layout.simple_spinner_item);      
    adapter.setDropDownViewResource  
    (android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);

    Spinner spinner2 = findViewById(R.id.spinner2);
    ArrayAdapter<CharSequence> adapter1 = 
    ArrayAdapter.createFromResource(this,
    R.array.drinks, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner2.setAdapter(adapter1);
    spinner2.setOnItemSelectedListener(this);



    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int 
    position, long l) {
    String text = parent.getItemAtPosition(position).toString();
    Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
    }

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

    }

Code for the intent

    Button enviar = findViewById(R.id.enviar);
    enviar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent resumenPedido = new Intent(MainActivity.this, Resumen.class);
            startActivityForResult(resumenPedido, 1);
        }
    });

Solution

  • you should use Intent.putExtra() method. Please check the following and use accordingly.

    This is how you can get the selected values from spinner:

    CharSequence spinner1SelectedData  = (CharSequence) spinner.getSelectedItem();
    CharSequence spinner2SelectedData  = (CharSequence) spinner2.getSelectedItem();
    

    And then onClick listener replace it with the following:

    Intent resumenPedido = new Intent(MainActivity.this, Resumen.class);
    resumePedido.putExtra("data_spinner_1", spinner1SelectedData.toString());  
    resumePedido.putExtra("data_spinner_2", spinner2SelectedData.toString());
    startActivity(mIntent);
    

    You don't have to use startActivityForResult unless you want callback to source activity.

    In the 2nd activity you can get the data as follows:

      if (getIntent() != null){
          String spinner1Value = getIntent().getStringExtra("data_spinner_1");
          String spinner2Value = getIntent().getStringExtra("data_spinner_2");
      }