已解决-程序不会在while循环中到达

时间:2019-07-10 17:35:00

标签: android android-sqlite

我有一个SQlite数据库和一个由新闻文章填充的列表视图。我可以将文章添加到收藏夹中。当我尝试删除它时,它不起作用。

我正在遵循CodingWithMitch上的教程,并确保我的SQl语句相同,但是我的程序无法正常工作。

收藏夹活动

//Deleting favorites
favoritesList.setOnItemLongClickListener(new 
AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, 
int position, long id) {

    //final ArrayList<ListViewDetails> details = new ArrayList<>();
    //Cursor takes in a ListViewDetails object for a specific new article
    final Cursor cursor = databaseHelper.getID(details.get(position));

    //This is to test if the correct list view object is retrieved - Works
    Log.i("Test", details.get(position).link);

    //So the code won't reach this point and therefore nothing is executed
    int favoriteId = -1;  
    while (cursor.moveToNext()) {
        favoriteId = cursor.getInt(0);       
    }
        if (favoriteId > -1) {
            if (databaseHelper.delete(favoriteId) > 0) {

            Toast.makeText(getApplicationContext(), "Deleted", Toast.LENGTH_SHORT).show();
            Log.i("Delete", "It works!");
            adapter.remove(details.get(position));
            adapter.notifyDataSetChanged();     

            }
         }

DatabaseHelper类

public static final String COL0 = "ID";
public static final String COL1 = "TITLE";
public static final String COL2 = "PHOTO_URL";

@Override
public void onCreate(SQLiteDatabase db) {
    String sql = "CREATE TABLE " + TABLE_NAME + " ( " +
            COL0 + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
...

public Cursor getID(ListViewDetails listViewDetails){
    SQLiteDatabase db = this.getWritableDatabase();
    String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " +
            COL1 + " = '" + listViewDetails.getLink() + "'" +
            " AND " + COL2 + " = '" + listViewDetails.getTitle() + "'";       
    return db.rawQuery(sql,null);
}

public Integer delete(int id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, "ID = ?", new String[] {String.valueOf(id)});
}

只是想找出为什么代码无法到达while循环。

更新 SQL语法造成的粗心错误。解决方案已被接受。

1 个答案:

答案 0 :(得分:1)

如果没有提取任何行,则while循环将结束而不会进入主体。

这是最可能的情况。

查看为什么光标可能为空。我相信您没有将列与 DatabaseHelper 类的 getID 方法中的值匹配。

那是:-

 String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " +
        COL1 + " = '" + listViewDetails.getLink() + "'" +
        " AND " + COL2 + " = '" + listViewDetails.getTitle() + "'";

应该是:-

 String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " +
        COL1 + " = '" + listViewDetails.getTitle() + "'" +
        " AND " + COL2 + " = '" + listViewDetails.getLink() + "'";

即COL1是标题,COL2是链接

  • 我建议不要使用COL1 COl2等,而应使用描述性名称,例如COL_TITLE和COL_LINK(这种错误发生的可能性较小)。