如何从ListView和数据库中删除的消息 [英] how to delete message from listview and database

查看:104
本文介绍了如何从ListView和数据库中删除的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的codeI要添加删除列表视图消息时选择的消息长preSS用户点击将从列表视图中删除,并数据库帮我该怎么做IM usign踏在我的code等等如何删除选定mesage形式ListView和数据库的任何想法?

 公共类MsgActivity扩展BackBaseActivity {
     ImageView的背;
     按钮writemsg;
     ListView的msglist;
     清单< MessageModel> msgarray;
     MessageAdapter msgadapter;
     ImageView的SCROLL_DOWN;
ImageView的scroll_up;
 INT X = 1;
公共静态活动msgactivity ;;
 处理程序句柄=新的处理程序(){
     公共无效的handleMessage(android.os.Message MSG){
        super.handleMessage(MSG);
        CommonObjects.hideProgress();            msgadapter =新MessageAdapter(MsgActivity.this,
            msgarray);
        msglist.setAdapter(msgadapter);
            }赶上(例外五){
                // TODO:处理异常
            }
         }
        如果(msg.what == 1){
            Toast.makeText(MsgActivity.this,没有消息,
                  Toast.LENGTH_SHORT).show();
         }    }};
 @覆盖
保护无效onRestart(){
    如果(CommonObjects.getLogoutreject()等于(1)及&放大器; CommonObjects.logout){         完();    }
    super.onRestart();
 }@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    // TODO自动生成方法存根
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.msgactivity);
    回到=(ImageView的)findViewById(R.id.magback);
     msglist =(ListView控件)findViewById(R.id.msglist);
    msgactivity =这一点;
    CommonObjects.showProgress(MsgActivity.this加载信息);
     新的Thread(){
        公共无效的run(){
            尺蠖prepare()。
            尝试{
                数据库处理器DB =新
                        数据库处理器(MsgActivity.this);
            msgarray = db.getAllmesages();            android.os.Message alertMessage =新android.os.Message();
            alertMessage.what = 2;
            handle.sendMessage(alertMessage);
            }赶上(例外五){
                e.getStackTrace();
                android.os.Message alertMessage =新
                      android.os.Message();
                alertMessage.what = 1;
                handle.sendMessage(alertMessage);
            }
        }
    }。开始();
  }


解决方案

 的DatabaseManager数据=新的DatabaseManager(context.getApplicationContext());                 查询字符串=SELECT * FROM车其中id =你的身份证                    光标光标= data.selectQuery(查询);
    诠释计数= cursor.getCount();
                   如果(计数< = 0){                }
             其他{
                data.Delete(数据库名称,你的ID);
                list.remove(位置);
                notifyDataSetChanged();
                }

DatabaseMangerClass

 公共类的DatabaseManager扩展SQLiteOpenHelper {            //你的应用程序数据库的Andr​​oid的默认系统路径。            @燮pressLint(SdCardPath)
            私人静态字符串DB_PATH =数据/数据​​/ com.Salsoft.pharmapacks /;
            私人静态字符串DB_NAME =Cart.sqlite;
            私人SQLiteDatabase MYDATABASE;
            私人SQLiteDatabase MYDATA的;
            私人语境myContext;            // /data/data/com.salsoft.savingdata/db/SavingData.sqlite            / **
             *构造函数和不断传递的上下文中的一个参考,以
             *访问应用程序的资产和资源。
             *
             * @参数方面
             * /
            公众的DatabaseManager(上下文的背景下){
                超级(上下文,DB_NAME,空,1);
                this.myContext =背景;
                布尔ISSD present = android.os.Environment.getExternalStorageState()
                        .equals(android.os.Environment.MEDIA_MOUNTED);                如果(ISSD present){
                    //是SD卡为present
                }其他{
                    //对不起
                }
            }            / **
             *在系统上创建一个空数据库,然后用自己的重写它
             *数据库。
             * * /
            公共无效的CreateDatabase()抛出IOException                布尔dbExist = checkDataBase();
                如果(dbExist){
                    //什么也不做 - 已存在于数据库
                }其他{
                    文件目录=新的文件(DB_PATH);
                    directory.mkdirs();
                    CopyFiles();
                }
            }            私人无效CopyFiles(){
                尝试{
                    InputStream为= myContext.getAssets()开(DB_NAME)。
                    文件OUTFILE =新的文件(DB_PATH,DB_NAME);
                    outfile.getParentFile()mkdirs()。
                    outfile.createNewFile();                    如果(是== NULL){
                        抛出新的RuntimeException(流为空);
                    }其他{
                        FileOutputStream中出=新的FileOutputStream(OUTFILE);
                        中byte buf [] =新的字节[128];
                        做{
                            INT numread = is.​​read(BUF);
                            如果(numread&下; = 0)
                                打破;
                            out.write(BUF,0,numread);
                        }而(真);                        is.close();
                        out.close();
                    }                }赶上(IOException异常五){
                    抛出新的RuntimeException(E);
                }            }            / **
             *检查是否已存在于数据库,以避免重新复制每个文件
             *一次打开应用程序。
             *
             *如果存在返回:真的,假的,如果它不
             * /
            私人布尔checkDataBase(){                SQLiteDatabase CHECKDB = NULL;                尝试{
                    字符串mypath中= DB_PATH + DB_NAME;
                    CHECKDB = SQLiteDatabase.openDatabase(mypath中,空,
                            SQLiteDatabase.OPEN_READWRITE);                }赶上(SQLiteException E){                }                如果(CHECKDB!= NULL){
                    checkDB.close();
                }                返回CHECKDB!= NULL?真假;
            }            公共无效的openDatabase()抛出的SQLException {                //打开数据库
                字符串mypath中= DB_PATH + DB_NAME;
                MYDATABASE = SQLiteDatabase.openDatabase(mypath中,空,
                        SQLiteDatabase.OPEN_READWRITE);
            }            @覆盖
            公共同步无效的close(){
                如果(MYDATABASE!= NULL)
                    myDataBase.close();
                super.close();
            }            公共无效插入(字符串表,字符串NUM,ContentValues​​内容){
                字符串mypath中= DB_PATH + DB_NAME;                MYDATA的= SQLiteDatabase.openDatabase(mypath中,空,
                        SQLiteDatabase.OPEN_READWRITE);
                myData.insert(表,NUM,内容);            }            公共无效更新(字符串表名,ContentValues​​内容,字符串的productid){
                字符串mypath中= DB_PATH + DB_NAME;
                MYDATA的= SQLiteDatabase.openDatabase(mypath中,空,
                        SQLiteDatabase.OPEN_READWRITE);
                myData.update(表名,内容的productid =?,
                        新的String [] {}产品ID);            }            公共无效删除(字符串表名,弦乐的productid){
                字符串mypath中= DB_PATH + DB_NAME;
                MYDATA的= SQLiteDatabase.openDatabase(mypath中,空,
                        SQLiteDatabase.OPEN_READWRITE);                myData.delete(表名的productid =?,新的String [] {}产品ID);            }            @覆盖
            公共无效的onCreate(SQLiteDatabase DB){
            }            @覆盖
            公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
            }            // ---检索记录---
            公共光标selectQuery(查询字符串)抛出的SQLException {
                字符串mypath中= DB_PATH + DB_NAME;
                MYDATA的= SQLiteDatabase.openDatabase(mypath中,空,
                        SQLiteDatabase.OPEN_READONLY);
                光标mCursor = myData.rawQuery(查询,NULL);
                mCursor.moveToFirst();
                myData.close();
                返回mCursor;
            }            // ////////对于插入和更新数据////////
            公共无效INSERT_UPDATE(查询字符串)抛出的SQLException {
                字符串mypath中= DB_PATH + DB_NAME;
                MYDATA的= SQLiteDatabase.openDatabase(mypath中,空,
                        SQLiteDatabase.OPEN_READWRITE);
                myData.execSQL(查询);
                myData.close();
            }        }

below is my code i want to add delete listview message when user click on long press selected message will delete from listview and also database help me how to do that im usign tread in my code so how to delete selected mesage form listview and database any idea?

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

解决方案

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

        }

这篇关于如何从ListView和数据库中删除的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆