开发者

Update Spinner items to the database.?

i have a开发者_如何学运维 spinner that loads items from the SQLite database. it works fine. then i have a edittext to get the selected spinner item to that edittext. its also woks. then i want to change the edit text value and update that spinner item to the database. so how to do that. please any help. thnx


You should make sql update query. As you already get spinner items from DB, you should know how to make queries. To make update query, you have to call db.update() method.


Lets say,you have populated Spinner spinner with data from database.And you have EditText editText and Button button to update spinner values.Then you can achieve this something like below:

...
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int position, long arg3) {

                //code to display the selected item in EditText
        }

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

        }
});
selectDate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                 DatabaseCreator dbcreator=new DatabaseCreator(context);
                 SQLiteDatabase sqdb=dbcreator.getWritableDatabase();   

                 ContentValues values=new ContentValues();

                 //Update respective fields in database 
                 values.put("field_1",newValue1);
                 values.put("field_2",newValue2);

                 long suceess=sqdb.update( "table_name", values, KEY_ID+"='"+id+"'", null);
                 // you can place any condition in place of KEY_ID+"='"+id+"'" as third argument in above statement

                 if(success!=0)
                 {
                      //repopulate spinner here
                 }  
        }
});
...

DatabaseCreator.class:

public class DatabaseCreator extends  SQLiteOpenHelper{

    private static final String DB_NAME="db_name";
    private static final int DB_VER=2;

    private static final String TABLE_1="create table table_1(...);"; //complete create query goes here

    public DatabaseCreator(Context context) {
        super(context,DB_NAME, null, DB_VER);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {

        database.execSQL(TABLE_1);      
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, int arg1, int arg2) {

            database.execSQL("DROP TABLE IF EXISTS db_name");
        onCreate(database);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜