0

When I try to delete an item in list view ,it removes it from list view but when I add a new item or run the application again the items is still there.I can't delete it from database.

I am using this code:

...
SqlHandler sqlHandler;
ListView myListView;
myAdapter adapter;
ArrayList<myItems> items;
 ...
 myListView = (ListView) findViewById(R.id.myListView);
 sqlHandler = new SqlHandler(this);
 items = getItemsFromDatabase();

adapter = new myAdapter(this, items);
myListView.setAdapter(adapter);
myListView.setOnItemLongClickListener(this);
 ...
public boolean onItemLongClick(AdapterView<?> adapterView, View view,
        int position, long id) {

    final myItems selectedItem = items.get(position);

    if (selectedItem != null) {
        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
        alt_bld.setMessage("Do you want to delete this item?")
                .setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int id) {

                                sqlHandler=new SqlHandler(getApplicationContext());
                                sqlHandler.deleteRecord(id);
                                items.remove(selectedItem);
                                adapter.notifyDataSetChanged();

For the database I use :

public class SqlHandler {
    public static final String DATABASE_NAME = "MY_DATABASE";
    public static final String DATABASE_TABLE = "MEM";
    public static final String KEY_ROWID = "_id";

        public static final int DATABASE_VERSION = 1;
            Context context;
            SQLiteDatabase sqlDatabase;
            SqlDbHelper dbHelper;

            public SqlHandler(Context context) {

                 dbHelper = new SqlDbHelper(context, DATABASE_NAME, null,
                   DATABASE_VERSION);
                 sqlDatabase = dbHelper.getWritableDatabase();
                }

    public void executeQuery(String query) {
     try {

      if (sqlDatabase.isOpen()) {
       sqlDatabase.close();
      }

      sqlDatabase = dbHelper.getWritableDatabase();
      sqlDatabase.execSQL(query);

     } catch (Exception e) {

      System.out.println("DATABASE ERROR " + e);
     }

}

        public Cursor selectQuery(String query) {
         Cursor c1 = null;
         try {

          if (sqlDatabase.isOpen()) {
           sqlDatabase.close();

          }
          sqlDatabase = dbHelper.getWritableDatabase();
          c1 = sqlDatabase.rawQuery(query, null);

         } catch (Exception e) {

          System.out.println("DATABASE ERROR " + e);

         }
         return c1;

}
        public SqlHandler open() throws SQLException
        {
            sqlDatabase = dbHelper.getWritableDatabase();
        return this;
        }

        public void Close(){
            dbHelper.close();

        }
        public void  deleteRecord(long rowId){
            try {
             sqlDatabase.delete(DATABASE_TABLE,KEY_ROWID + "="+rowId,null);
            }
            catch (Exception e)
            {
                Log.e("DB ERROR", e.toString());
                e.printStackTrace();
            }
        }

and

public class SqlDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_TABLE = "MEM";



public static final String TAG="DbHandler";

 public static final String KEY_ROWID = "_id";
 ...


 private static final String SCRIPT_CREATE_DATABASE = "create table "
   + DATABASE_TABLE + " (" + KEY_ROWID
   + " integer primary key autoincrement, " + ....);";

 public SqlDbHelper(Context context, String name, CursorFactory factory,
   int version) {
  super(context, name, factory, version);
  // TODO Auto-generated constructor stub

 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  // TODO Auto-generated method stub
  db.execSQL(SCRIPT_CREATE_DATABASE);

 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  // TODO Auto-generated method stub
     Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
             + newVersion + ", which will destroy all old data");
  db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
  onCreate(db);
 }

----------UPDATE---------------------

It should be sth like:

myItems theItems =(myItems)adapterView.getItemAtPosition(button_id);
String _id = theItems.getID();
String delQuery = "DELETE FROM MEM WHERE _id='"+_id+"' ";
sqlHandler.executeQuery(delQuery);

but I have a problem with the (myItems)adapterView.. I am not sure how to handle this.

4

2 回答 2

1

你遇到的问题是你的方法删除的调用,它应该是这样的:

public long deleteItem(myItems itemToDelete) {
    try {
             return sqlDatabase.delete(DATABASE_TABLE,COLUMN_ID + " = ?",new String[]{itemToDelete.getID()});
            }
            catch (Exception e)
            {
                Log.e("DB ERROR", e.toString());
                e.printStackTrace();
                return -1;
            }
}

当您按YES ButtonofAlertDialog确认删除时,您应该从数据库中删除该项目,然后从数据库中重新加载项目并通知您的列表适配器以使用新数据刷新它:

myItems selectedItem = adapter.getItem(position);
long rows = sqlHandler.deleteItem(selectedItem);
if(rows>0) {
    //get new items from database 
    adapter.setItems(getItemsFromDatabase());
    adapter.notifyDataSetChanged();
}

该项目将从数据库中删除,并将listView用新数据刷新

于 2013-04-12T11:16:45.923 回答
1

我相信错误在这里:

    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) { //<--- rename this to buttonId
          sqlHandler=new SqlHandler(getApplicationContext());
          sqlHandler.deleteRecord(id);  //<---- This "id" is the button that was clicked, not your item ID

我想你想使用另一个 id变量,但即使那样,我也不确定那是你真正想要的那个(它可能是)。从您的代码中,我无法快速分辨出真实 ID 在哪里。

于 2013-04-11T13:36:58.713 回答