如何从listview和数据库中删除消息

时间:2014-02-21 10:38:56

标签: android android-listview

下面是我的代码我想添加删除listview消息,当用户点击长按选择的消息将从列表视图中删除,并且数据库帮助我如何做到这一点我的代码,所以如何删除选定的消息表单列表视图和数据库有什么想法?

public class MsgActivity extends BackBaseActivity{
     ImageView back;
     Button writemsg;
     ListView msglist;
     List<MessageModel> msgarray;
     MessageAdapter msgadapter;
     ImageView scroll_down;
ImageView scroll_up;
 int x = 1;
public static Activity msgactivity;;
 Handler handle = new Handler() {
     public void handleMessage(android.os.Message msg) {
        super.handleMessage(msg);
        CommonObjects.hideProgress();

            msgadapter = new MessageAdapter(MsgActivity.this,  
            msgarray);


        msglist.setAdapter(msgadapter);
            }catch (Exception e) {
                // TODO: handle exception
            }
         }
        if(msg.what == 1){
            Toast.makeText(MsgActivity.this, "No Messages", 
                  Toast.LENGTH_SHORT).show();
         }

    }

};
 @Override
protected void onRestart() {
    if(CommonObjects.getLogoutreject().equals("1") && CommonObjects.logout){

         finish();

    }
    super.onRestart();
 }

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.msgactivity);
    back  = (ImageView)findViewById(R.id.magback);
     msglist = (ListView)findViewById(R.id.msglist);        
    msgactivity = this;
    CommonObjects.showProgress(MsgActivity.this, "Loading messages");        
     new Thread() {
        public void run() {
            Looper.prepare();
            try{    
                DatabaseHandler db = new   
                        DatabaseHandler(MsgActivity.this);
            msgarray = db.getAllmesages();

            android.os.Message alertMessage = new android.os.Message();
            alertMessage.what = 2;
            handle.sendMessage(alertMessage);
            }catch (Exception e) {
                e.getStackTrace();
                android.os.Message alertMessage = new  
                      android.os.Message();
                alertMessage.what = 1;
                handle.sendMessage(alertMessage);
            }
        }
    }.start();
  }

3 个答案:

答案 0 :(得分:0)

试试这样。

lv.setOnItemLongClickListener(new OnItemLongClickListener() {
        // setting onItemLongClickListener and passing the position to the function
                  @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {

              String[] delete = names2.get(i);
              String idString = delete[0];
              long idLong = Long.valueOf(idString);
              Log.d("Deleting...", idLong   + "");
              dataManipulator.delete(idLong);
              names2.remove(i);
        }
    });

其中names2是您的List数组。

并在Datamanipulator类中添加以下

public boolean delete(long rowId) {
        /** this method deletes by id, the first column in your database */
        return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
    }

答案 1 :(得分:0)

如果要删除listview和数据库中的任何数据,只需执行此操作

在你的主要活动课

 delete.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(final View v) {
        // TODO Auto-generated method stub


                DatabaseHandler dBHandler = new DatabaseHandler(
                    activity.getApplicationContext());
                dBHandler.Delete_Contact(user_id);
                Main_Screen.this.onResume();

            }
            });

并在您的数据库处理程序类中,使用此

 // Deleting single contact
public void Delete_Contact(int id) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            new String[] { String.valueOf(id) });
    db.close();
}

答案 2 :(得分:0)

  DataBaseManager  data = new DataBaseManager(context.getApplicationContext());

                 String QUERY = "SELECT * FROM Cart Where id= "your id";

                    Cursor  cursor = data.selectQuery(QUERY);
    int count = cursor.getCount();
                   if (count <= 0) {

                }
             else {
                data.Delete("YOUR DATABASE NAME", "YOUR ID");
                list.remove(position);
                notifyDataSetChanged();
                }

DatabaseMangerClass

        public class DataBaseManager extends SQLiteOpenHelper {

            // The Android's default system path of your application database.

            @SuppressLint("SdCardPath")
            private static String DB_PATH = "data/data/com.Salsoft.pharmapacks/";
            private static String DB_NAME = "Cart.sqlite";
            private SQLiteDatabase myDataBase;
            private SQLiteDatabase myData;
            private Context myContext;

            // /data/data/com.salsoft.savingdata/db/SavingData.sqlite

            /**
             * Constructor Takes and keeps a reference of the passed context in order to
             * access to the application assets and resources.
             * 
             * @param context
             */
            public DataBaseManager(Context context) {
                super(context, DB_NAME, null, 1);
                this.myContext = context;
                Boolean isSDPresent = android.os.Environment.getExternalStorageState()
                        .equals(android.os.Environment.MEDIA_MOUNTED);

                if (isSDPresent) {
                    // yes SD-card is present
                } else {
                    // Sorry
                }
            }

            /**
             * Creates a empty database on the system and rewrites it with your own
             * database.
             * */
            public void createDataBase() throws IOException {

                boolean dbExist = checkDataBase();
                if (dbExist) {
                    // do nothing - database already exist
                } else {
                    File directory = new File(DB_PATH);
                    directory.mkdirs();
                    CopyFiles();
                }
            }

            private void CopyFiles() {
                try {
                    InputStream is = myContext.getAssets().open(DB_NAME);
                    File outfile = new File(DB_PATH, DB_NAME);
                    outfile.getParentFile().mkdirs();
                    outfile.createNewFile();

                    if (is == null) {
                        throw new RuntimeException("stream is null");
                    } else {
                        FileOutputStream out = new FileOutputStream(outfile);
                        byte buf[] = new byte[128];
                        do {
                            int numread = is.read(buf);
                            if (numread <= 0)
                                break;
                            out.write(buf, 0, numread);
                        } while (true);

                        is.close();
                        out.close();
                    }

                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

            }

            /**
             * Check if the database already exist to avoid re-copying the file each
             * time you open the application.
             * 
             * @return true if it exists, false if it doesn't
             */
            private boolean checkDataBase() {

                SQLiteDatabase checkDB = null;

                try {
                    String myPath = DB_PATH + DB_NAME;
                    checkDB = SQLiteDatabase.openDatabase(myPath, null,
                            SQLiteDatabase.OPEN_READWRITE);

                } catch (SQLiteException e) {

                }

                if (checkDB != null) {
                    checkDB.close();
                }

                return checkDB != null ? true : false;
            }

            public void openDataBase() throws SQLException {

                // Open the database
                String myPath = DB_PATH + DB_NAME;
                myDataBase = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READWRITE);
            }

            @Override
            public synchronized void close() {
                if (myDataBase != null)
                    myDataBase.close();
                super.close();
            }

            public void insert(String table, String num, ContentValues content) {
                String myPath = DB_PATH + DB_NAME;

                myData = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READWRITE);
                myData.insert(table, num, content);

            }

            public void update(String tablename, ContentValues content, String productid) {
                String myPath = DB_PATH + DB_NAME;
                myData = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READWRITE);
                myData.update(tablename, content, "productid = ?",
                        new String[] { productid });

            }

            public void Delete(String tablename, String productid) {
                String myPath = DB_PATH + DB_NAME;
                myData = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READWRITE);

                myData.delete(tablename, "productid = ?", new String[] { productid });

            }

            @Override
            public void onCreate(SQLiteDatabase db) {
            }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            }

            // ---retrieve records---
            public Cursor selectQuery(String query) throws SQLException {
                String myPath = DB_PATH + DB_NAME;
                myData = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READONLY);
                Cursor mCursor = myData.rawQuery(query, null);
                mCursor.moveToFirst();
                myData.close();
                return mCursor;
            }

            // //////// For Insert And Update Data ////////
            public void insert_update(String query) throws SQLException {
                String myPath = DB_PATH + DB_NAME;
                myData = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READWRITE);
                myData.execSQL(query);
                myData.close();
            }

        }