Search code examples
androiddatabaseandroid-intentspinneronitemselectedlistener

How can I extract data from spinners to another layout?


I need help with my application. I put some spinners in one layout, and I need to retrieve the text in the SelectedItems to put them in another layout, maybe in a TextView.

I used:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String selecTipoCP = parent.getItemAtPosition(position).toString();
    String TipoCP = selecTipoCP;

    Intent intent1 = new Intent(CPOrder.this,Finalizar.class);
    intent1.putExtra("var_tipoCP", TipoCP);
    startActivity(intent1);
}

and it functions, but the activity starts immediately. I want to enter this layout, and I want to start the activity only when I press a button.


Solution

  • You just need to separate your code to add the functionality you want something like this.

    Create an event for your button.

     @Override
             public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
    
    
                          addCustomListenerOnSpinner();
             }
    
    
    
    
         private void addCustomListenerOnSpinner(){
    
             yourButton.setOnClickListener(new View.OnClickListener() {
              @Override
             public void onClick(View view) {
    
                String value=String.valueOf(yourSpinner.getSelectedItem());
                 Intent intent1 = new Intent(CPOrder.this,Finalizar.class);
                 intent1.putExtra("var_tipoCP", value);
                 startActivity(intent1);
              }
             });
    
         }
    

    Other way ...

        @Override
         public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
    
                      //only we pass the data
                      addCustomListenerOnSpinner(parent,position);
         }
    
    
    
    
     private void addCustomListenerOnSpinner(final AdapterView<?> parent,final int position){
    
         yourButton.setOnClickListener(new View.OnClickListener() {
          @Override
         public void onClick(View view) {
    
             String selecTipoCP =parent.getItemAtPosition(position).toString();
             Intent intent1 = new Intent(CPOrder.this,Finalizar.class);
             intent1.putExtra("var_tipoCP", selecTipoCP);
             startActivity(intent1);
          }
         });
    
     }