数据库拒绝删除项目

时间:2017-12-09 11:17:21

标签: java android listview android-sqlite

我正在开发一个用户将通过editText输入文本的应用程序,它将存储到listView和DataBase中。

但是当我运行代码时,项目拒绝删除。

InputContract.java

public class InputContract {
public static final String DB_NAME = "com.dobleu.peek.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);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

ListView list;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
ConstraintLayout l1;
ConstraintLayout l2;
TextView displayText;
TextView amt;
TextView itms;
private static int TIME = 1000;
private InputDbHelper mHelper;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams. FLAG_FULLSCREEN);

    setContentView(R.layout.activity_main);
    init();
    mHelper = new InputDbHelper(this);
    updateUI();
    int no = list.getAdapter().getCount();
    amt.setText("" + no);
    setupListViewListener();
}
private void setupListViewListener() {
    list.setOnItemLongClickListener(
            new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapter,
                                               View item, int pos, long id) {
                    // Remove the item within array at position
                    items.remove(pos);
                    // Refresh the adapter
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    db.delete(InputContract.TaskEntry.TABLE,
                            InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
                            new String[]{"Name of entry you want deleted"});
                    db.close();
                    updateUI();
                    itemsAdapter.notifyDataSetChanged();
                    // Return true consumes the long click event (marks it handled)
                    return true;
                }

            });
}

public void init(){
    ActionBar ab = getSupportActionBar();
    assert ab != null;
    ab.hide();

    list = (ListView)findViewById(R.id.list);

    displayText = (TextView)findViewById(R.id.displayText);
    amt = (TextView)findViewById(R.id.amt);
    itms = (TextView)findViewById(R.id.itms);

    items = new ArrayList<String>();
    itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
    list.setAdapter(itemsAdapter);

    l1 = (ConstraintLayout)findViewById(R.id.one);
    l2 = (ConstraintLayout)findViewById(R.id.two);



    Typeface regular = Typeface.createFromAsset(getAssets(),  "fonts/regular.ttf");
    Typeface bold = Typeface.createFromAsset(getAssets(),  "fonts/bold.ttf");

    amt.setTypeface(bold);
    itms.setTypeface(regular);
    displayText.setTypeface(regular);

}

public void add(View v){
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    LayoutInflater inflater = this.getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.dialog, null);
    dialogBuilder.setView(dialogView);

    final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);

    dialogBuilder.setTitle("Add Item");
    dialogBuilder.setMessage("Enter text below");
    dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String txt = edt.getText().toString();
            items.add(txt);
            SQLiteDatabase db = mHelper.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(InputContract.TaskEntry.COL_TASK_TITLE,   txt);
            db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
            db.close();
            updateUI();
            int no = list.getAdapter().getCount();
            amt.setText("" + no);
        }
    });
    dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            //pass
        }
    });
    AlertDialog b = dialogBuilder.create();
    b.show();

}


public void play(View v){
    Animation fadeOut = AnimationUtils.loadAnimation(this, abc_fade_out);
    Animation fadeIn = AnimationUtils.loadAnimation(this, abc_fade_in);

    l1.startAnimation(fadeOut);
    l1.setVisibility(View.GONE);
    l2.setVisibility(View.VISIBLE);
    l2.startAnimation(fadeIn);

    String[] array = new String[items.size()];
    final String[] mStringArray = items.toArray(array);

    final android.os.Handler handler = new android.os.Handler();
    handler.post(new Runnable() {

        int i = 0;

        @Override
        public void run() {
            displayText.setText(mStringArray[i]);
            i++;

            if (i == mStringArray.length) {
                handler.removeCallbacks(this);
            } else {
                handler.postDelayed(this, TIME);
            }
        }
    });



}
public void one(View v){TIME = 1000;}
public void three(View v){TIME = 3000;}
public void five(View v){TIME = 5000;}
public void seven(View v){TIME = 7000;}
public void ten(View v){TIME = 10000;}


private void updateUI() {

    ArrayList<String> taskList = new ArrayList<>();
    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 (itemsAdapter== null) {
        itemsAdapter= new ArrayAdapter<>(this,  android.R.layout.simple_list_item_1,
                taskList);
        list.setAdapter(itemsAdapter);
    } else {
        itemsAdapter.clear();
        itemsAdapter.addAll(taskList);
        itemsAdapter.notifyDataSetChanged();
    }

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

}

在MainActivity.java中,特别是在setupListViewListener()中,当持有listView时,它应该删除正在持有的项目。但该列表只会振动并保持不变。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我怀疑您的问题是您已将TASK_TITLE硬编码为 "Name of entry you want deleted" ,而不是从该项目中获取TASK_TITLE长时间点击。

所以尝试使用: -

    private void setupListViewListener() {
        list.setOnItemLongClickListener(
            new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapter,
                                               View item, int pos, long id) {

                    String title_of_row_to_delete = list.getItemAtPosition(i).toString(); //<<<<<<<<
                    // Remove the item within array at position
                    items.remove(pos);
                    // Refresh the adapter
                    SQLiteDatabase db = mHelper.getWritableDatabase();
                    db.delete(InputContract.TaskEntry.TABLE,
                            InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
                            new String[]{title_of_row_to_delete}); //<<<<<<<<
                    db.close();
                    updateUI();
                    itemsAdapter.notifyDataSetChanged();
                    // Return true consumes the long click event (marks it handled)
                    return true;
                }

            });
    }

这将从列表中提取TASK_TITLE,然后使用它作为参数来查找要删除的行。

//&LT;&LT;&LT;&LT;&LT;&LT;&LT;&LT;表示已更改的行。