如何从Android中的SQ Lite数据库中删除项目?

时间:2017-08-21 21:33:39

标签: java android android-sqlite

抱歉我的英文。我是Android开发的新手。我有一个用户做笔记的应用程序。当用户做笔记时,笔记将保存在SQ Lite数据库中并显示在ListView中。当我想删除注释时,注释将从ListView中删除,但不会从数据库中删除。你能帮帮我吗?

MainActivity.java

    public class MainActivity extends Activity
{

    private InputDbHelper mHelper;
    private ListView mListView;
    private EditText mEditText;
    private Button mButton;
    ArrayList<String> list = new ArrayList<String>();
    ArrayAdapter<String> adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mButton = (Button) findViewById(R.id.button);
        mEditText = (EditText) findViewById(R.id.editText);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, list);
        mListView=(ListView)findViewById(R.id.listView);  
        mListView.setAdapter(adapter);
        mHelper = new InputDbHelper(this);
        updateUI();

        mButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String input = mEditText.getText().toString();

                if (input.length() > 0) {
                SQLiteDatabase db = mHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(InputContract.TaskEntry.COL_TASK_TITLE,   input);     
                db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);                                        
                db.close();
                updateUI();
                }
            }
        });

        mListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
        AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
        adb.setTitle("Delete?");
        adb.setMessage("Are you sure you want to delete this note?");
        final int positionToRemove = position;
        adb.setNegativeButton("Cancel", null);
        adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                list.remove(positionToRemove);
                adapter.notifyDataSetChanged();
            }});

        deleteTask();
        adb.show();
        }
    });
    }

    public void deleteTask() {
    SQLiteDatabase db = mHelper.getWritableDatabase();
    db.delete(InputContract.TaskEntry.TABLE,
        InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
        new String[]{});
    db.close();
    updateUI();
    }

    private void updateUI() {

    ArrayList<String> taskList = new ArrayList<String>();
    SQLiteDatabase db = mHelper.getReadableDatabase();
    Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
        new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
        null, null, null, null, null);
    while (cursor.moveToNext()) {
        int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
        taskList.add(cursor.getString(idx));
    }

    if (adapter== null) {
        adapter= new ArrayAdapter<String>(this,  android.R.layout.simple_expandable_list_item_1,
            taskList);
        mListView.setAdapter(adapter);
    } else {
        adapter.clear();
        adapter.addAll(taskList);
        adapter.notifyDataSetChanged();
    }

    cursor.close();
    db.close();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

InputContract.java

    public class InputContract {
public static final String DB_NAME = "com.example.db";
public static final int DB_VERSION = 1;

public class TaskEntry implements BaseColumns {
    public static final String TABLE = "tasks";

    public static final String COL_TASK_TITLE = "title";
    }
}

InputDbHelper.java

    public class InputDbHelper extends SQLiteOpenHelper {

public InputDbHelper(Context context) {
    super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + "    ( " +
            InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
    db.execSQL(createTable);
}

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

2 个答案:

答案 0 :(得分:1)

您没有删除数据库中的行。您可以执行此操作

mListView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
    AlertDialog.Builder adb=new AlertDialog.Builder(MainActivity.this);
    adb.setTitle("Delete?");
    adb.setMessage("Are you sure you want to delete this note?");
    final int positionToRemove = position;
    adb.setNegativeButton("Cancel", null);
    adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            db.delete(InputContract.TaskEntry.TABLE, InputContract.TaskEntry._ID + " = ?", new String[] { String.valueOf(positionToRemove)});
            list.remove(positionToRemove);
            adapter.notifyDataSetChanged();
        }});

    deleteTask();
    adb.show();
    }
});

答案 1 :(得分:0)

尝试类似:

db.execSQL("DELETE FROM myTable WHERE noteID = 7")

或更一般地说:

`int idToDelete = 7; //for example
 db.execSQL(
    "DELETE FROM "+ InputContract.TaskEntry.TABLE +
    " WHERE "+  InputContract.TaskEntry._ID +" = " + idToDelete
 )`
相关问题