【问题标题】:Deleting data from Listview从 Listview 中删除数据
【发布时间】:2014-01-28 22:44:18
【问题描述】:

我是 Android 开发的新手,我在可能的应用程序中有一个 Listview,Listview 填充了来自 Sqlite 数据库的数据。我想在此列表视图上使用复选框并删除所选项目。 我确实想从 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();
}

之后在我的列表视图活动中成功检索。

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;
}

我可以成功删除整个线程,但现在我想使用复选框从列表视图中删除几条短信 请问有什么有用的教程吗?

【问题讨论】:

  • 对列表视图使用自定义适配器
  • 那么我们一些代码你做了什么?
  • 请显示一些你已经完成的代码

标签: android android-listview delete-row


【解决方案1】:

试试这个

从列表视图中删除项目的代码

int index = Integer.parseInt(position+"");
                ArrayList.remove(index);
                notifyDataSetChanged();

然后使用查询从 Sqite 数据库中删除数据

【讨论】:

    【解决方案2】:

    一点提示可能会有所帮助。由于您有数据,请跟踪标记的项目。存储他们的 ID。一旦用户单击完成或您拥有的任何按钮,运行一个 sql 查询来删除带有 id 的记录。然后调用列表视图的notifyDataSetChanged。由于它是一个光标,因此 notifyDataSetChanged 可能无法正常运行,然后再次重新填充光标。

    请参阅Refresh ListViewthis

    【讨论】:

      【解决方案3】:

      如果您按照您在问题中所说的那样成功地从数据库中删除数据,而不是使用 listview 的 notifydatasetchanged 方法重新加载新数据的 listview。

      【讨论】:

        【解决方案4】:

        对于自定义适配器,使用列表项行 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;
        }
        

        【讨论】:

          【解决方案5】:

          com/nhaarman/ListViewAnimations。非常有用..你可以在https://play.google.com/store/apps/details?id=com.haarman.listviewanimations看到演示

          【讨论】:

            【解决方案6】:

            试试这个解决方案here

            在 EmployeeAdapter.java 中,您将选中和取消选中 dataList,并在此文件中写入方法 getDataList();

            例子:

            public List<employeemodel> getDataList(){
                return employeeData;
            }
            

            在你的活动中使用这个方法yourAdapter.getDataList();

            在获取 datalist 后执行删除操作并将新的 dataList 设置为您的适配器并调用yourListView.notifyDatasetChange();

            【讨论】:

              【解决方案7】:

              自定义适配器和 notifyDataSetChanged()

              【讨论】:

                猜你喜欢
                • 2015-08-10
                • 1970-01-01
                • 1970-01-01
                • 2023-03-22
                • 1970-01-01
                • 2015-08-18
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多