从数据库中删除项目 - ListView - Android

时间:2012-05-21 11:38:10

标签: android database listview

public class DataViewActivity extends Activity{
SQLiteDatabase db;
SimpleCursorAdapter adapter;
String dbTable = "users";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_layout);
ListView listView = (ListView) findViewById(R.id.dbPop);

DBHelper dbhelper = new DBHelper(DataViewActivity.this);
db = dbhelper.getWritableDatabase();

Cursor cursor = db.query(dbTable, null, null, null, null, null, null);
startManagingCursor(cursor);

String[] from = new String[] { "name","_id"};
int[] to = new int[] { android.R.id.text1 };
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, from,
        to);

    listView.setAdapter(adapter);
  }
}

如何为此代码实现onClick侦听器以删除所选数据库行。我对Android知之甚少,所以对我来说这是一个学习曲线。

3 个答案:

答案 0 :(得分:7)

setOnItemClickListener设置为您的列表视图...

listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {

            database.remove(id);//create removemethod in database class

        }
    });

和删除方法

    public void remove(long id){
        String string =String.valueOf(id);
        database.execSQL("DELETE FROM favorite WHERE _id = '" + string + "'");
    }

答案 1 :(得分:3)

    listview.setOnItemClickListener(new OnItemClickListener(){

    public void onItemClick(AdapterView<?> arg0, View v, int pos,long id) {
            // TODO Auto-generated method stub
      {
             TextView tv=(TextView)v;
     String s1=tv.getText().toString();
            //delete row
            String delgrp="DELETE FROM (tablename) WHERE  (row)='"+s1+"'";
    sdb.execSQL(delgrp);
      }

答案 2 :(得分:1)

ListView.onListItemClick,因为第三个参数有positionPositionAdpater.getItem(int)返回的条目。因此,当您点击ListView的一行时,ListView.onListItemClick会被触发。在那里,您可以检索适配器条目并使用从数据库中删除条目所需的信息。

public void onListItemClick(ListView parent, View v, int position, long id) {
      // do something with the cursor
}