Insert selected SPINNER item in SQLITE

0

How to identify the selected item in SPINNER and insert it into the SQLITE database.

I can do the insert in Sqlite using the data provided in EditText, but I am not able to create a way to do something similar with SPINNER.

Code:

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

    marca = (EditText) findViewById(R.id.ed_marca);
    modelo = (EditText) findViewById(R.id.ed_modelo);
    constante = (EditText) findViewById(R.id.ed_constante);
    data_fabricacao = (EditText) findViewById(R.id.ed_fabricacao);
    salvar = (Button) findViewById(R.id.btn_salvar);

    myDb = new DatabaseHelper(this);
    AddData();

    spiner_constante = (Spinner) findViewById(R.id.sp_constante);
    spiner_constante.setOnItemSelectedListener(this);

    loadSpinnerData();

    private void loadSpinnerData() {
    DatabaseHelper db = new DatabaseHelper(getApplicationContext());

    List<Integer> constante = db.GetAllConstante();

    ArrayAdapter<Integer> dataAdapter3 = new ArrayAdapter<Integer> (this,android.R.layout.simple_spinner_item,constante);

    spiner_constante.setAdapter(dataAdapter3);
    dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}


public void AddData() { // AQUI É FEITO O INSERT DOS DADOS DOS EDITTEXT, NO SQLITE

    salvar.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isInserted = myDb.insertData(marca.getText().toString(), modelo.getText().toString(), constante.getText().toString(), data_fabricacao.getText().toString());


}

}

    
asked by anonymous 17.04.2015 / 13:56

2 answers

1

Once you have the list of Spinner items with this code snippet:

List<Integer> constante = db.GetAllConstante();

Just use it to get the selected item:

constante.get(spinner.getSelectedItemPosition())

And then, this value will be inserted into the database along with its other values. This discards the use of OnItemSelectedListener , since you do not intend to do this when you select a Spinner item, but rather the Save button (unless you are using for another action).

    
17.04.2015 / 15:02
1

You did not copy the method you had to implement, onItemSelected .

You should implement the following in this method:

@Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        //Ele irá retornar o objeto selecionado no Spinner conforme o tipo que você utilizou para preencher o ArrayAdapter, no seu caso.
        objeto = parent.getItemAtPosition(position);
        // Após pegar o objeto selecionado é só fazer a inserção na base de dados
        myDb.insertData(objeto);
    }

I hope I have helped! Good luck!

    
17.04.2015 / 14:57