简体   繁体   中英

Comparing the data from a database with the item selected on spinner- Android

I've tried the following method to do the task but it isn't working but doesn't show any errors at all. This is the comparing part:

Cursor res = myDb.showKharcha();
final String selected= parent.getItemAtPosition(position).toString();
while(res.moveToNext()) {
    if(selected == res.getString(1)) {
        int num = Integer.parseInt(editText.getText().toString());
        num = num + Integer.parseInt(res.getString(2));
        boolean isUpdated = myDb.updateData(res.getString(0),selected,num);
        if (isUpdated == true) {
            Toast.makeText(add_trans.this,"Kharcha updated to "+ selected,Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(add_trans.this, "Kharcha not added", Toast.LENGTH_LONG).show();
        }

This is the showKharcha function in DatabaseHelper class:

public Cursor showKharcha(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor tyt = db.rawQuery("select * from " + TABLE_NAME,null);
    return tyt;
}

The database Update code is:

public boolean updateData(String ID, String KharchaType, Integer Kharcha){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put(COL_1,ID);
    contentValues.put(COL_2,KharchaType);
    contentValues.put(COL_3,Kharcha);
    db.update(TABLE_NAME,contentValues, "ID = ?",new String[] { ID });
    return true;

}

You have talked about comparing the value of the selected value from the Spinner. Use this final String text = spinner.getSelectedItem().toString();

instead of

final String selected= parent.getItemAtPosition(position).toString(); .

It'd be better if you set an OnItemSelectedListener so that when the user selects, the comparison automatically happens:

parent.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
final String text = spinner.getSelectedItem().toString();
...rest of the code fro comparison...
}
});
  • Use final String text = spinner.getSelectedItem().toString(); to get selected item from Spinner

And

  • Try if(selected.equals(res.getString(1))) for comparison

Refer this for more details about == and equals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM