从SQLite数据库中删除的数据再次出现

时间:2017-08-22 12:14:37

标签: java android sqlite android-sqlite

我的代码中有一个错误。每当我从SQ Lite数据库中删除项目时,都会删除itens。虽然,当我插入新项目时,已删除的项目再次出现。你能帮助我吗?很抱歉打扰,但我不知道该怎么办。

这是我的MainActivity。

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) {
                SQLiteDatabase db = mHelper.getWritableDatabase();
                db.delete(InputContract.TaskEntry.TABLE, InputContract.TaskEntry._ID + " = ?", new String[] { String.valueOf(positionToRemove)});
                list.remove(positionToRemove);
                adapter.remove(String.valueOf(positionToRemove));
                adapter.notifyDataSetChanged();
            }});
        adb.show();
        }
    });
    }

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

1 个答案:

答案 0 :(得分:1)

通过这样做:

db.delete(InputContract.TaskEntry.TABLE,
    InputContract.TaskEntry._ID + " = ?", new String[] {
        String.valueOf(positionToRemove)
    }
);

你正在编写它以使用ListView项的位置作为表ID,当你创建一个新表时它可能适用于第一行,但是当你开始删除项时,所有的东西都会搞砸

您必须通过为ArrayAdapter创建自定义类或将行ID存储到数组/列表并使用positionToRemove从该列表中获取ID来存储ID,但是如果您搞乱ListView并且不更新列表数据,则可能导致意外行为。

检查此问题Custom Adapter for List View,了解如何创建自定义适配器并将行ID与文本一起保存到所有ListView项目。