简体   繁体   中英

Can not delete a record in sqlite

My application will display all the information in the database to the listview. When I click on a line in the listview, the application will notify you want to delete it from the database? but the error is when I click on OK, the application notice error.I do not understand why the error can not open databse. source code

public class Index extends Activity {

 private ArrayList<String> DateArray = new ArrayList<String>();
    private ArrayList<String> CostArray = new ArrayList<String>();
    private ArrayList<String> SalesArray = new ArrayList<String>();
    private ArrayList<String> ProfitArray = new ArrayList<String>();
    private ArrayList<String> IDArray = new ArrayList<String>();
    private DB_Adapter mDb = new DB_Adapter(this);
    ListView listview;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.index);
    listview = (ListView) ((Activity) this)
            .findViewById(R.id.listView1);
    workoffline();
}

 @Override
protected void onRestart() {
    // TODO Auto-generated method stub
     workoffline();
    super.onRestart();
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    workoffline();
    super.onResume();
}

public void clearArray()
    {
        DateArray.clear();
        CostArray.clear();
        SalesArray.clear();
        ProfitArray.clear();
        IDArray.clear();
    }

public void workoffline()
{
    clearArray();
    try {
        // mở kết nối đến databse sqlite
        mDb.openDB();
        // lấy thông tin thông qua IDDelivery
        Cursor mCursor = mDb.getAll();
        // Duyệt record từ đầu
        if (mCursor.moveToFirst()) {
            do {
                IDArray.add(mCursor.getString(0));
                DateArray.add(mCursor.getString(1));
                CostArray.add(mCursor.getString(2));
                SalesArray.add(mCursor.getString(3));
                ProfitArray.add(mCursor.getString(4));

            } while (mCursor.moveToNext());
            listview.setAdapter(new DataAdapter(this, DateArray
                    .toArray(new String[DateArray.size()]), CostArray
                    .toArray(new String[CostArray.size()]), SalesArray
                    .toArray(new String[SalesArray.size()]), ProfitArray
                    .toArray(new String[ProfitArray.size()])));
            listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    final int ID = Integer.valueOf(IDArray.get(position));
                        try {

                            Index.this.runOnUiThread(new Runnable() {
                                public void run() {

                                    AlertDialog.Builder builder = new AlertDialog.Builder(
                                            Index.this);
                                    builder.setTitle("Waring!");
                                    builder.setMessage("Are you delete!")
                                            .setCancelable(false)
                                            .setPositiveButton("Ok",
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(
                                                                DialogInterface dialog, int id) {
                                                                mDb.delete_byID(ID);
                                                        }
                                                    });
                                    builder.setNegativeButton("Không", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    });
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                }
                            });

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
            });

        }
        // Đóng database
        mDb.closeDB();
    } catch (Exception e) {
        e.printStackTrace();
    }

}
}

log cat error

01-15 16:06:50.940: E/AndroidRuntime(17932): FATAL EXCEPTION: main
01-15 16:06:50.940: E/AndroidRuntime(17932): java.lang.IllegalStateException: database not open
01-15 16:06:50.940: E/AndroidRuntime(17932):    at android.database.sqlite.SQLiteDatabase.delete(SQLiteDatabase.java:1619)
01-15 16:06:50.940: E/AndroidRuntime(17932):    at Data.DB_Adapter.delete_byID(DB_Adapter.java:94)
01-15 16:06:50.940: E/AndroidRuntime(17932):    at com.example.xitinshop.Index$1$1$1.onClick(Index.java:102)
01-15 16:06:50.940: E/AndroidRuntime(17932):    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
01-15 16:06:50.940: E/AndroidRuntime(17932):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-15 16:06:50.940: E/AndroidRuntime(17932):    at android.os.Looper.loop(Looper.java:130)
01-15 16:06:50.940: E/AndroidRuntime(17932):    at android.app.ActivityThread.main(ActivityThread.java:3683)
01-15 16:06:50.940: E/AndroidRuntime(17932):    at java.lang.reflect.Method.invokeNative(Native Method)
01-15 16:06:50.940: E/AndroidRuntime(17932):    at java.lang.reflect.Method.invoke(Method.java:507)
01-15 16:06:50.940: E/AndroidRuntime(17932):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
 -15 16:06:50.940: E/AndroidRuntime(17932):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
 01-15 16:06:50.940: E/AndroidRuntime(17932):   at dalvik.system.NativeStart.main(Native Method)

Try opening and closing the database within the button click, something like this:

.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {
        public void onClick(
                DialogInterface dialog, int id) {
                mDB.openDB();
                mDb.delete_byID(ID);
                myDB.closeDB();
        }
    });

You open the DB, query the data, then close the DB again. The onClick method is executed afterwards, so the DB is already closed at that time.

its always a better practice to open and close db in SQLiteOpenHelper class.

like,

public class FriendsDatatbaseHelper extends SQLiteOpenHelper {
public int deleteContact(String contact_id) {
    db = getWritableDatabase();
     int delete = db.delete(FRIENDS_TABLE_NAME, "contact_index=" + contact_id, null);
     db = getWritableDatabase();
     return delete;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM