使用列表处理数据库中的更新

时间:2015-05-23 10:21:33

标签: android sqlite sql-update

我在使用列表处理数据库更新时遇到问题,在编辑类中我有这个方法

private ArrayList<store> store_List = new ArrayList<store>();
list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        store store = store_List.get(position);
        Intent intent = new Intent(edit.this,Update.class);
        edit.this.finish();
        startActivity(intent);
    }
});

在Update类中,我有这个方法:

  btnUpdate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            DB db = new DB(getApplicationContext());
            try {
                    db.open();
                    db.updatestore(HERE WHAT SHOULD I PASS);
                    adapter.notifyDataSetChanged();
                } catch (SQLiteException se) {
                    Log.e(getClass().getSimpleName(),
                            "Could not create or Open the database");
                } finally {
                    if (db != null)
                        db.close();

                }
        }
    });

在DB中,方法更新如下:

   public int updatestore(store s) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, s.getName());
    values.put(KEY_CATEGORY, s.getCategory());
    return db.update(TABLE_store, values, KEY_ID + " = ?",
            new String[] { String.valueOf(s.getEid()) });
   }

1 个答案:

答案 0 :(得分:0)

您可以将从store_List中选择的商店项目传递到Update.class,如下所示:

list = (ListView) findViewById(R.id.list);
list.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        store store = store_List.get(position);
        Intent intent = new Intent(edit.this,Update.class);
        intent.putExtra("myStore", store);
        edit.this.finish();
        startActivity(intent);
    }
});

然后在你的Update.class中你可以获得这样的商店项目:

Store passedStore = getIntent().getSerializableExtra("myStore");

然后在你的onCLickListener中你将拥有以下内容:

btnUpdate.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        DB db = new DB(getApplicationContext());
        try {
                db.open();
                db.updatestore(passedStore);  //the store item you became as an extra from your intent
                adapter.notifyDataSetChanged();
            } catch (SQLiteException se) {
                Log.e(getClass().getSimpleName(),
                        "Could not create or Open the database");
            } finally {
                if (db != null)
                    db.close();

            }
    }
});