数据库中的各个行都填充在自定义列表视图中。行的id也显示在列表视图中。我想要的只是通过单击相应的列表来删除特定的行。
以下是我用来显示数据库内容的代码:
class NoteAdapter extends CursorAdapter {
public NoteAdapter(Cursor c) {
super(Reccuring.this, c);
}
@Override
public void bindView(View row, Context ctxt, Cursor c) {
NoteHolder holder = (NoteHolder) row.getTag();
holder.populateFrom(c, helper);
}
@Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row1, parent, false);
NoteHolder holder = new NoteHolder(row);
row.setTag(holder);
return row;
}
}
static class NoteHolder {
private TextView name = null;
private TextView number = null;
private TextView idtext = null;
NoteHolder(View row) {
name = (TextView) row.findViewById(R.id.noteText);
number= (TextView) row.findViewById(R.id.noteText1);
idtext = (TextView) row.findViewById(R.id.noteText3);
}
void populateFrom(Cursor c, NoteHelper helper) {
name.setText(helper.getNote(c));
number.setText(helper.getNote1(c));
idtext.setText(helper.getNote2(c));
}
}
这是我的数据库:
public class NoteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Test.db";
private static final int SCHEMA_VERSION = 1;
public NoteHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Notes (_id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, num TEXT, sDate TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
public void insert(String note, String amt, String sDate) {
ContentValues cv = new ContentValues();
cv.put("note", note);
cv.put("num", num);
cv.put("sDate", sDate);
getWritableDatabase().insert("Notes", "notes", cv);
}
public String getNote(Cursor c) {
return (c.getString(1));
}
public String getNote1(Cursor c) {
return (c.getString(2));
}
public String getNote2(Cursor c) {
return (c.getString(0));
}
public Cursor getAll() {
return (getReadableDatabase().rawQuery(
"SELECT _id, note, num, sDate FROM Notes", null));
}
}
}
如何选择列表视图中的行并删除数据库中的相应行。
答案 0 :(得分:2)
首先获取列表视图的方法onItemClickListener()
所点击的位置的值:
@Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
LinearLayout linearLayout = (LinearLayout) view;// The main layout which contains your child views in which value is displayed
TextView name = (TextView)linearLayout.getChildAt(0);// get child textview 1
String nametext = name.getText().toString();// get String out of those textview
deleteOldData(nametext)
}
然后转到数据库类并编写此代码:
public void deleteOldData(String nametext) {
_sqliteDB.delete(tablename, " note = '" + nametext + "'", null);
}
这样您就可以删除表格特定的行。
如果你无法做到这一点或者数据库中的注释列相同,那么在listview的文本视图中使用唯一的Id进行设置,以此形式提取它,然后将该值传递给数据库代码然后删除它