下面是一个代码,我想你可以使用它来满足你的要求。在下面的代码中,我将获取保存在我的数据库中的联系人并将其显示在listView
. 如果用户想从数据库中删除一个联系人,那么他应该长按该项目,并使用出现的对话框,他可以删除该联系人。下面是代码:
public class viewContacts extends ListActivity {
private static final String TAG = "MYRECORDER";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.showcontacts);
//Creating a List View
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
ListView mylist=(ListView) findViewById(android.R.id.list);
mylist.setAdapter(adapter);
//Creating or opening an eisting database
SQLiteDatabase db=openOrCreateDatabase("MYDB", Context.MODE_PRIVATE, null);
//Getting a cursor to fetch data from the database
Cursor c=db.rawQuery("SELECT Number,Name FROM myTbl", null);
Log.d(TAG, "Cursor reference obtained...");
c.moveToFirst();
Log.d(TAG, "Cursor Moved to First Number....");
if(c!=null){
//If there are contents in the database, then c!=null, so using do-while loop access data // in database
do{
String num=c.getString(c.getColumnIndex("Number"));
String name=c.getString(c.getColumnIndex("Name"));
String Name_num=name+" : "+num;
listItems.add(Name_num);
c.moveToNext();
}while(!c.isAfterLast());
//update the list
adapter.notifyDataSetChanged();
//closing the database after use
db.close();
//Below is the code to delete items in data base
mylist.setOnItemClickListener(new OnItemClickListener() {
String str=null;
public void onItemClick(AdapterView<?> arg0, View view,
int arg2, long arg3) {
// TODO Auto-generated method stub
String item = ((TextView)view).getText().toString();
str=item.substring(item.lastIndexOf('+'));
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
//Creating an Alert Dialog
AlertDialog .Builder builder=new AlertDialog.Builder(viewContacts.this);
builder.setMessage("Are you sure you want to delete the contact "+str+" ?");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
SQLiteDatabase db=openOrCreateDatabase("MYDB", MODE_PRIVATE, null);
Toast.makeText(getBaseContext(), "The contact: "+str+" was successfully deleted", Toast.LENGTH_LONG).show();
String table="myTbl";
String whereClause = "Number = ?";
String[] whereArgs = new String[] { str };
db.delete(table, whereClause, whereArgs);
db.close();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
} );
AlertDialog alert=builder.create();
alert.show();
}
});
}
}
}