Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
EditText value is not appearing while changing the spinner items.

Example : Edit text should show "9045" if Spinner value is Boat, Also it should be vice versa I mean if it is Edit Text value is 9045 then my spinner value should be Boat.

Tried with below code but still i am unable to bring the edit text value while selecting spinner

What I have tried:

Main Activity code is
JavaScript
<pre>package com.bar.example.myapplication;
public class MainActivity extends AppCompatActivity {
  public static final String BARCODE_KEY = "BARCODE";
  EditText date;
  DatePickerDialog datePickerDialog;
  Spinner s1, s2, s3;
  Button btnAdd;
  Button send;
  Button ok;
  Button ok1;
  private TextView result1;
  Button btn_send_mail;
  private Button button3;

  private Button btnexport;
  EditText inputLabel, bResult;
  TextView tex, tex1;
  DatabaseHandler dbhndlr;

  Cursor spinner1csr, spinner2csr, spinner3csr, spinner4csr;
  SimpleCursorAdapter sca, sca2, sca3, sca4;
  long spinner1_selected = 0;
  CheckBox ck1, ck2, ck3, ck4, ck5, ck6, ck7, ck8;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    s1 = (Spinner) findViewById(R.id.spinner1);
    s2 = (Spinner) findViewById(R.id.spinner2);
    s3 = (Spinner) findViewById(R.id.spinner5);
    bResult = (EditText) findViewById(R.id.barcodeResult);
    btnAdd = (Button) findViewById(R.id.btn_add);
    inputLabel = (EditText) findViewById(R.id.input_label);
    dbhndlr = new DatabaseHandler(this);

           if (DatabaseUtils.queryNumEntries(
        dbhndlr.getWritableDatabase(),
        DatabaseHandler.TABLE_LABELS) < 1) {
      dbhndlr.insertlabel("Ships", "12344", "9133");
      dbhndlr.insertlabel("Boat", "93993", "9045");
    }

    
    spinner1csr = dbhndlr.getAllLabelsAsCursor();
   
    sca = new SimpleCursorAdapter(this,
      android.R.layout.simple_list_item_1, spinner1csr,
      new String[] {
        DatabaseHandler.KEY_ID
      },
      new int[] {
        android.R.id.text1
      },
      0
    );

    s1.setAdapter(sca);
    // Set Spinner1 OnSelectedItemListener
    s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
      @Override
      public void onItemSelected(AdapterView << ? > parent, View view, int position, long id) {
        //  bResult.setText(s1.getSelectedItem().toString());
        spinner1_selected = id;
        spinner2csr = dbhndlr.getByRowid(spinner1_selected);
        spinner3csr = dbhndlr.getByRowid(spinner1_selected);
        spinner4csr = dbhndlr.getByRowid(spinner1_selected);

        sca2.swapCursor(spinner2csr);
        sca3.swapCursor(spinner3csr);
        sca4.swapCursor(spinner4csr);

      }

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


    spinner2csr = dbhndlr.getByRowid(spinner1_selected);
    sca2 = new SimpleCursorAdapter(this,
      android.R.layout.simple_list_item_1,
      spinner2csr,
      new String[] {
        DatabaseHandler.KEY_NAME
      },
      new int[] {
        android.R.id.text1
      },
      0
    );
    s2.setAdapter(sca2);
          spinner3csr = dbhndlr.getByRowid(spinner1_selected);
    sca3 = new SimpleCursorAdapter(this,
      android.R.layout.simple_list_item_1,
      spinner3csr,
      new String[] {
        DatabaseHandler.KEY_ID1
      },
      new int[] {
        android.R.id.text1
      },
      0
    );
    s3.setAdapter(sca3);

    spinner4csr = dbhndlr.getByRowid(spinner1_selected);
    sca4 = new SimpleCursorAdapter(this,
      android.R.layout.simple_list_item_1,
      spinner4csr,
      new String[] {
        DatabaseHandler.KEY_ID1
      },

      new int[] {
        android.R.id.text1
      },

      0

    );
    bResult.setAdapter(sca4);
         btnAdd.setOnClickListener(new View.OnClickListener() {

      @Override
      public void onClick(View arg0) {
        String label = inputLabel.getText().toString();

        if (label.trim().length() > 0) {
                
          inputLabel.setText("");
          bResult.setText("");
        
          InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
          imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
         
          spinner1csr = dbhndlr.getAllLabelsAsCursor();
          spinner2csr = dbhndlr.getByRowid(spinner1_selected);
          spinner3csr = dbhndlr.getByRowid(spinner1_selected);
          spinner4csr = dbhndlr.getByRowid(spinner1_selected);
          sca.swapCursor(spinner1csr);
          sca2.swapCursor(spinner2csr);
          sca3.swapCursor(spinner3csr);
          sca4.swapCursor(spinner4csr);
        } else {
          Toast.makeText(getApplicationContext(), "Please enter label name",
            Toast.LENGTH_SHORT).show();
        }
      }
    });
  }

  @Override
  public void onDestroy() {
    spinner1csr.close();
    spinner2csr.close();
    spinner3csr.close();
    spinner4csr.close();
    super.onDestroy();
  }
}


Databasehandler code is
JavaScript
<pre>package com.bar.example.myapplication;

public class DatabaseHandler extends SQLiteOpenHelper {
  private static final int DATABASE_VERSION = 1;
  private static final String DATABASE_NAME = "spinnerExample";

  public static final String TABLE_LABELS = "labels";

  public static final String KEY_ID = "id";
  public static final String KEY_NAME = "name";
  public static final String KEY_ID1 = "barcode";

  public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    // Category table create query
    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "(" +
      KEY_ID + " TEXT," + KEY_NAME + " TEXT," + KEY_ID1 + " TEXT)";
    db.execSQL(CREATE_CATEGORIES_TABLE);
  }


  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);

    onCreate(db);
  }

  public void insertlabel(String id, String label, String label1) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(KEY_ID, id);
    cv.put(KEY_NAME, label);
    cv.put(KEY_ID1, label1);
    db.insert(TABLE_LABELS, null, cv);
    db.close();
  }

  public List < String > getAllLabels() {
    List < String > labels = new ArrayList < String > ();


    String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
      do {
        labels.add(cursor.getString(0));
      } while (cursor.moveToNext());
    }

    // closing connection
    cursor.close();
    db.close();

    return labels;
  }

  public Cursor getAllLabelsAsCursor() {
    String[] columns = new String[] {
      "rowid AS _id, *"
    };
    return this.getWritableDatabase().query(TABLE_LABELS, columns, null, null, null, null, null);
  }

  public Cursor getAllLabelsExceptedSelected(long selected) {
    String[] columns = new String[] {
      "rowid AS _id, *"
    };
    String whereclause = "rowid <> ?";
    String[] whereargs = new String[] {
      String.valueOf(selected)
    };
    return this.getWritableDatabase().query(TABLE_LABELS,
      columns,
      whereclause,
      whereargs,

      null,
      null,
      null

    );
  }

  public Cursor getByRowid(long id) {
    String[] columns = new String[] {
      "rowid AS _id, *"
    };
    return this.getWritableDatabase().query(
      TABLE_LABELS,
      columns,
      "rowid=?",
      new String[] {
        String.valueOf(id)
      },
      null, null, null
    );

  }

}
Posted
Updated 18-Mar-18 23:14pm
v2
Comments
Richard MacCutchan 19-Mar-18 4:52am    
"Tried in many ways but its keep failing."
Please edit your question and explain what that is supposed to mean.
David Crow 19-Mar-18 10:26am    
In your onItemSelected() handler for s1, there is no code that calls setText(). Are you setting the text for the EditText control in some other fashion?
David Crow 19-Mar-18 23:13pm    
The smallest example I could think of looks something like:

public class MainActivity extends AppCompatActivity
{
    EditText edit = null;
    Spinner spinner = null;

    //================================================================

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit = (EditText) findViewById(R.id.edit);
        spinner = (Spinner) findViewById(R.id.spinner);

        String[] months = new DateFormatSymbols().getMonths();
        ArrayAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, months);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                edit.setText(String.valueOf(position + 1));
            }
        });

        edit.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void afterTextChanged(Editable s)
            {
                try
                {
                    int nPosition = Integer.parseInt(s.toString());
                    if (nPosition >= 1 && nPosition <= 12)
                        spinner.setSelection(nPosition - 1);
                }
                catch(NumberFormatException nfe)
                {
                }
            }
        });
    }
}

It really just differs in how the spinner control is populated: your code is populating it from a database whereas mine is populating it from an array. Once populated, however, it behaves identically.
Maybeok 20-Mar-18 13:50pm    
David thanks for your different direction. I tried with following with success. "bResult.setText( spinner1csr.getString( spinner1csr.getColumnIndex(DatabaseHandler.KEY_ID1) ) );" But challenge here is i am unable to change spinner value based on textview changing.. what could be your suggestion ???
David Crow 20-Mar-18 14:02pm    
"...i am unable to change spinner value..."

This does not mean much. In your code, I do not see a call to setSelection(). How else are you trying to change the spinner control's value?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900