单击按钮删除项目

时间:2018-12-23 08:32:35

标签: android-studio sql-delete

在我的MainActivity中,我希望按钮删除视图列表中的所有项目。不幸的是,我在这里找到的所有解决方案都帮不了我。如果单击“全部清除”按钮,它将删除列表中的每个项目,但这些项目仍保存在数据库中。

我对Android Studio完全陌生,所以我不知道如何编写代码以使其能按我想要的方式工作。

这是我的MainActivity:

package com.vorlesung.iubh.todo;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    DatabaseHepler myDB;
    ArrayList<String> list;
    ListView myToDoList;
    ArrayAdapter<String> arrayAdapter;
    SparseBooleanArray selectedItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button addToDo = (Button) findViewById(R.id.addToDo);
        Button clearAll = (Button) findViewById(R.id.clearALL);
        Button editSelected = (Button) findViewById(R.id.editSelected);
        Button clearDone = (Button) findViewById(R.id.clearDone);

        myToDoList = (ListView) findViewById(R.id.myToDoList);
        myDB = new DatabaseHepler(this);

        list = new ArrayList<>();
        Cursor data = myDB.getListContents();

        if (data.getCount() == 0)
            Toast.makeText(this, "The Database was empty",         Toast.LENGTH_LONG).show();
        else {
            while (data.moveToNext()) {
                list.add(data.getString(1));
                arrayAdapter = new ArrayAdapter<>(this,     android.R.layout.simple_list_item_multiple_choice, list);
                myToDoList.setAdapter(arrayAdapter);
            }
        }
    }

    public void onClickaddToDo(View button) {
        Intent newToDo = new Intent(this, AddToDo.class);
        startActivity(newToDo);
    }

    // With this onClick I want to delete all Items from my List.
    public void onClickaclearALL(View button) {
        list.clear();
        arrayAdapter.notifyDataSetChanged();
    }
}

这是我的数据库:

package com.vorlesung.iubh.todo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHepler extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "myList.db";
    public static final String TABLE_NAME = "myList_Data";
    public static final String COL1 = "ID";
    public static final String COL2 = "ITEM1";

    public DatabaseHepler(Context context){super(context, DATABASE_NAME, null, 1);}

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "ITEM1 TEXT)";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
    }

    public boolean addData(String item1) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, item1);

        long result = db.insert(TABLE_NAME, null, contentValues);

        if(result == -1) {
            return false;
        } else {
            return true;
        }
    }

    public Cursor getListContents() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
        return data;
    }

    public void deleteRow() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_NAME+ " WHERE "+ COL2, null);
        db.close();
    }

}

编辑

我的日志文件中显示了错误:

2018-12-23 10:16:05.627 21957-21973/com.vorlesung.iubh.todo E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2018-12-23 10:16:05.627 21957-21973/com.vorlesung.iubh.todo E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
2018-12-23 10:16:05.628 21957-21973/com.vorlesung.iubh.todo E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
2018-12-23 10:17:26.766 21957-21957/com.vorlesung.iubh.todo E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.vorlesung.iubh.todo, PID: 21957
java.lang.IllegalStateException: Could not execute method for android:onClick
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
    at android.view.View.performClick(View.java:5610)
    at android.view.View$PerformClick.run(View.java:22265)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
    at android.view.View.performClick(View.java:5610) 
    at android.view.View$PerformClick.run(View.java:22265) 
    at android.os.Handler.handleCallback(Handler.java:751) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6077) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
 Caused by: java.lang.IllegalArgumentException: Empty bindArgs
    at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1656)
    at com.vorlesung.iubh.todo.DatabaseHepler.deleteAllRow(DatabaseHepler.java:51)
    at com.vorlesung.iubh.todo.MainActivity.onClickaclearALL(MainActivity.java:59)
    at java.lang.reflect.Method.invoke(Native Method) 
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) 
    at android.view.View.performClick(View.java:5610) 
    at android.view.View$PerformClick.run(View.java:22265) 
    at android.os.Handler.handleCallback(Handler.java:751) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6077) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

2 个答案:

答案 0 :(得分:1)

  1. 您应该先从数据库中删除,然后再更新列表。
  2. 不要在主线程中执行数据库操作并使用AsyncTask。

在您的代码中,您应该有两个AsyncTask:一个用于检索此列表,另一个用于清除列表。

例如,您可以在MainActivity中拥有它

private class DeleteItemsAsyncTask extends AsyncTask<Void, Void, Void> {
        private Context mContext;

        DeleteItemsAsyncTask(Context context) {
            mContext = context;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            myDB.deleteRow();
            return null;
        }

        @Override
        protected void onPostExecute(Void void) {
            list.clear();
            arrayAdapter.notifyDataSetChanged();
        }
    }

那么您的onclick应该是

// With this onClick I want to delete all Items from my List.
public void onClickaclearALL(View button) {
    new DeleteItemsAsyncTask(this).execute();
}

类似地,您应该对列出数据进行相同的操作。

答案 1 :(得分:1)

您需要在 DatabaseHepler 中创建一个函数,以删除表中的所有元素。

在DatabaseHepler类中,需要编写此函数。

double

在您的主要活动中,需要编写以下代码:

public void deleteAllRow() {
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("delete from "+ TABLE_NAME);
    db.close();
}

这将为您提供帮助。