我是Android开发的新手,我在may app中有一个Listview,Listview中填充了来自Sqlite数据库的数据。我想在这个listview&上使用复选框。删除所选项目。 我想从Sqlite Db确实清除选定的数据行。 任何有用的帮助将不胜感激。
首先,我在我的应用程序中检索了SMS,如下所示:` if(bundle!= null){
//—retrieve the SMS message received—
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
timestamp = smsMessage[n].getTimestampMillis();
number = smsMessage[n].getOriginatingAddress();
body += smsMessage[n].getDisplayMessageBody();
abortBroadcast();
blockMessage(context);
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
private void blockMessage(Context context) {
// instantiate DbMNager object to insert sms in database
//formating receiving time:
//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d HH:mm:ss a");
String formatedTime = formatter.format(timestamp);
DBmanager= new DbManager(context);
DBmanager.open();
DBmanager.Insert_sms_data(formatedTime ,number,body);
DBmanager.close();`
然后按如下方式存储在SQlite DB中:
public void Insert_sms_data(String formatedTime, String number, String body){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(SMS_Time, formatedTime);
cv.put(PHONE_NUMBER, number);
cv.put(MESSAGE_BODY, body);
DB.insert(TABLE_SMS, null, cv);
DB.close();
}
catch(Exception ex)
{
Log.e("ERROR in insertion", ex.toString());
}
}
public Cursor Return_All(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM "+"SMS_TABLE", null);
return cur;
}
// Clear all messaged
public void ClearAll(){
SQLiteDatabase db = this .getWritableDatabase();
db.delete(TABLE_SMS, null, null);
db.close();
}
之后在我的listview Activity中成功检索到了。
public class MainActivity extends Activity {
ListView listViewSMS;
Context context;
DbManager manager;
Button btn_clearall;
Cursor cursor;
SimpleCursorAdapter adapter;
//array from is the column name in your cursor where you're getting the data
String[] from = new String[]{"Phone_number","Message_body","Time"};
//array toIDs contains the id of textViews
int[] toIDs = new int[]{R.id.textViewSMSSender,R.id.textViewMessageBody,R.id.textViewMSMStime};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_activity_main);
context=this;
//get the ListView Reference
try{
listViewSMS=(ListView)findViewById(R.id.listViewSMS);
listViewSMS.setChoiceMode(listViewSMS.CHOICE_MODE_MULTIPLE);
manager = new DbManager(context);
cursor = manager.Return_All();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview_each_item, cursor, from, toIDs);
listViewSMS.setAdapter(adapter);
adapter.notifyDataSetChanged();
//refreshCursor();
listViewSMS.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
int itemId = Integer.valueOf(String.valueOf(position));
cursor.moveToPosition(itemId);
int messageId = cursor.getInt(0);
deleteMessage(messageId);
Toast.makeText(getApplicationContext(), "current position"+itemId, Toast.LENGTH_LONG).show();
TextView tv_SMSSenderNumber=(TextView)v.findViewById(R.id.textViewSMSSender);
TextView tv_SMSBody=(TextView)v.findViewById(R.id.textViewMessageBody);
TextView tv_SMSTime=(TextView)v.findViewById(R.id.textViewMSMStime);
String smsSender=tv_SMSSenderNumber.getText().toString();
String smsBody= tv_SMSBody.getText().toString();
String smsTime= tv_SMSTime.getText().toString();
}
});
}
catch(Exception ex){
Log.e("ERROR!!", ex.toString());
}
btn_clearall = (Button)findViewById(R.id.btn_Delall);
btn_clearall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearMessages();
//refreshCursor();
// adapter.notifyDataSetChanged();
}
});
CheckBox cb_sms_lv = (CheckBox)findViewById(R.id.cb_smslist);
}
protected void clearMessages() {
new AlertDialog.Builder(MainActivity.this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle(R.string.delete)
.setMessage(getString(R.string.clear_message_confirm))
.setPositiveButton(R.string.delete,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int i) {
manager = new DbManager(
context);
manager.open();
manager.ClearAll();
manager.close();
refreshCursor();
}
}).setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int i) {
}
}).show();
}
private void deleteMessage(final int messageId){
new AlertDialog.Builder(MainActivity.this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle(R.string.delete)
.setMessage(getString(R.string.delete_message_confirm))
.setPositiveButton(R.string.delete,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int i) {
manager = new DbManager(
context);
manager.open();
manager.deleteMessage(messageId);
manager.close();
refreshCursor();
}
}).setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int i) {
}
}).show();
}
public void refreshCursor() {
manager = new DbManager(context);
manager.open();
cursor = manager.Return_All();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview_each_item, cursor, from, toIDs);
listViewSMS.setAdapter(adapter);
manager.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
我可以成功删除整个帖子,但现在我想使用复选框从listview中删除一些短信 有什么有用的教程吗?
答案 0 :(得分:3)
试试这个
从列表视图中删除项目的代码
int index = Integer.parseInt(position+"");
ArrayList.remove(index);
notifyDataSetChanged();
然后使用Query从Sqite数据库中删除数据
答案 1 :(得分:1)
小小的提示可以提供帮助。由于您拥有数据,因此请记录标记的项目。存放他们的ID。一旦用户点击完成或您拥有的任何按钮,运行一个SQL查询,删除带有ID的记录。然后调用列表视图的notifyDataSetChanged
。由于它的光标存在notifyDataSetChanged
可能无法正常工作的变化,因此再次重新填充光标。
答案 2 :(得分:1)
如果你在问题中成功删除了数据库中的数据,而不是使用listview的notifydatasetchanged方法用新数据重新加载listview。
答案 3 :(得分:1)
对于自定义适配器,请将列表项行xml用作:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/data"
android:padding="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/data"
android:checked="false" />
</RelativeLayout>
并在自定义适配器java类
中public class CustomAdapter extends BaseAdapter{
ArrayList<String> mlistdata;
private LayoutInflater layoutinflater;
private Context mContext;
public CustomAdapter(Context context,ArrayList<String> elements)
{
mlistdata = elements;
layoutinflater=LayoutInflater.from(context);
mContext=context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mlistdata.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int arg0, View convertview, ViewGroup arg2) {
// TODO Auto-generated method stub
final ViewHolder holder;
if(convertview==null)
{
holder = new ViewHolder();
convertview = layoutinflater.inflate(R.layout.gallery_items, null);
holder.txt=(TextView)convertview.findViewById(R.id.data);
holder.cb=(CheckBox)convertview.findViewById(R.id.checkbox);
convertview.setTag(holder);
}
else{
holder=(ViewHolder)convertview.getTag();
}
holder.txt.setText((mlistdata.get(arg0)).toString());
holder.cb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(holder.cb.isChecked())
{
//database related operation
}
else
{
//database related operation
}
}
});
return convertview;
}
static class ViewHolder
{
TextView txt;
CheckBox cb;
}
答案 4 :(得分:0)
COM / nhaarman / ListViewAnimations。非常实用..你可以在https://play.google.com/store/apps/details?id=com.haarman.listviewanimations
看到演示答案 5 :(得分:0)
尝试此解决方案here
在EmployeeAdapter.java中,您将检查并取消选中dataList,并在此文件中编写一个方法getDataList();
。
示例:
public List<employeemodel> getDataList(){
return employeeData;
}
使用yourAdapter.getDataList();
获取datalist后执行删除操作并将新dataList设置为适配器并调用yourListView.notifyDatasetChange();
。
答案 6 :(得分:0)
自定义适配器和 notifyDataSetChanged()