Skip to content Skip to sidebar Skip to footer

How To Delete Message From Listview And Database

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 tr

Solution 1:

if you want to delete any data from listview and databse just perform this opreation

in your mainactivity class

 delete.setOnClickListener(newOnClickListener() {

    @OverridepublicvoidonClick(final View v) {
        // TODO Auto-generated method stubDatabaseHandlerdBHandler=newDatabaseHandler(
                    activity.getApplicationContext());
                dBHandler.Delete_Contact(user_id);
                Main_Screen.this.onResume();

            }
            });

and in your databasehandler class,use this

// Deleting single contactpublicvoidDelete_Contact(int id) {
    SQLiteDatabasedb=this.getWritableDatabase();
    db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
            newString[] { String.valueOf(id) });
    db.close();
}

Solution 2:

Try like this.

lv.setOnItemLongClickListener(newOnItemLongClickListener() {
        // setting onItemLongClickListener and passing the position to the function@OverridepublicbooleanonItemLongClick(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);
        }
    });

Where names2 is your List array.

and in your Datamanipulator class add following

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

Solution 3:

  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

publicclassDataBaseManagerextendsSQLiteOpenHelper {

            // The Android's default system path of your application database.@SuppressLint("SdCardPath")privatestaticStringDB_PATH="data/data/com.Salsoft.pharmapacks/";
            privatestaticStringDB_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
             */publicDataBaseManager(Context context) {
                super(context, DB_NAME, null, 1);
                this.myContext = context;
                BooleanisSDPresent= 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.
             * */publicvoidcreateDataBase()throws IOException {

                booleandbExist= checkDataBase();
                if (dbExist) {
                    // do nothing - database already exist
                } else {
                    Filedirectory=newFile(DB_PATH);
                    directory.mkdirs();
                    CopyFiles();
                }
            }

            privatevoidCopyFiles() {
                try {
                    InputStreamis= myContext.getAssets().open(DB_NAME);
                    Fileoutfile=newFile(DB_PATH, DB_NAME);
                    outfile.getParentFile().mkdirs();
                    outfile.createNewFile();

                    if (is == null) {
                        thrownewRuntimeException("stream is null");
                    } else {
                        FileOutputStreamout=newFileOutputStream(outfile);
                        byte buf[] = newbyte[128];
                        do {
                            intnumread= is.read(buf);
                            if (numread <= 0)
                                break;
                            out.write(buf, 0, numread);
                        } while (true);

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

                } catch (IOException e) {
                    thrownewRuntimeException(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
             */privatebooleancheckDataBase() {

                SQLiteDatabasecheckDB=null;

                try {
                    StringmyPath= 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;
            }

            publicvoidopenDataBase()throws SQLException {

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

            @Overridepublicsynchronizedvoidclose() {
                if (myDataBase != null)
                    myDataBase.close();
                super.close();
            }

            publicvoidinsert(String table, String num, ContentValues content) {
                StringmyPath= DB_PATH + DB_NAME;

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

            }

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

            }

            publicvoidDelete(String tablename, String productid) {
                StringmyPath= DB_PATH + DB_NAME;
                myData = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READWRITE);

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

            }

            @OverridepublicvoidonCreate(SQLiteDatabase db) {
            }

            @OverridepublicvoidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            }

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

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

        }

Post a Comment for "How To Delete Message From Listview And Database"