2017-02-09 86 views
0

我在我的Android應用程序中使用SQLite。所有的都很棒,但是當我在我的天氣應用程序中添加一個位置然後將它滑開時,它不會從TABLE中刪除位置。Android上的SQLite不刪除行

在這裏我得到的位置,添加位置並將其刪除。

public TreeMap<String, LatLng> getSQLLocations() { 
    TreeMap<String, LatLng> locations = new TreeMap<>(); 
    for (int i =0; i < mCursor.getCount(); i++) { 
     mCursor.moveToPosition(i); 
     String name = mCursor.getString(mCursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_LOCATION_NAME)); 
     double lat = mCursor.getDouble(mCursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_LAT)); 
     double lon = mCursor.getDouble(mCursor.getColumnIndex(WeatherContract.WeatherEntry.COLUMN_LONG)); 
     LatLng latLng = new LatLng(lat, lon); 
     locations.put(name, latLng); 

    } 
    return locations; 
} 

public boolean removeSQLLocation(int position) { 
    mCursor.moveToPosition(position); 
    long id = mCursor.getLong(mCursor.getColumnIndex(WeatherContract.WeatherEntry._ID)); 

    boolean deleted = mDb.delete(WeatherContract.WeatherEntry.TABLE_NAME, WeatherContract.WeatherEntry._ID + "=" 
      + id, null) > 0; 
    return deleted; 
} 

public long addSQLLocation(String name, LatLng latLng) { 
    double lat = latLng.latitude; 
    double lon = latLng.longitude; 
    ContentValues cv = new ContentValues(); 
    cv.put(WeatherContract.WeatherEntry.COLUMN_LOCATION_NAME, name); 
    cv.put(WeatherContract.WeatherEntry.COLUMN_LAT, lat); 
    cv.put(WeatherContract.WeatherEntry.COLUMN_LONG, lon); 
    long ret = mDb.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, cv); 
    refreshLocationNames(); 
    return ret; 

} 

編輯1:所以這是問題所在。我嘗試刪除該行,但是當我直接從數據庫重新加載數據時,它不刷新。所以當我將數據添加到數據庫並嘗試重新加載時,它也不會刷新。問題在於它不會刷新數據庫更改,但它會在重新啓動應用程序時刷新。

這裏是我的github上的數據庫文件鏈接:

https://github.com/tsmadm/Stormy-WeatherApp/tree/SQL/app/src/main/java/com/tsm/stormy/SQL

+0

你的數據庫類中有刪除行方法嗎? –

+0

不知道亞當。你能檢查一下嗎,我是SQL新手,非常感謝! – TSM

回答

0

遊標是臨時對象,並且不應該長一段時間保持左右。

無論如何,遊標中的位置不一定與列表中的位置相同,尤其是在進行了更改或進行排序/過濾之後。 將ID存儲在列表中,並用它稍後訪問該行。

+0

非常感謝,但經過一些重構後,它無法工作。我添加了一個自定義對象,它保存了SQL的名稱,位置和標識,但是當我刪除它時,它仍然不起作用。你可以看看我的SQL和MainActivity類 - 方法「removeSQLLocation」。在我的github https://github.com/tsmadm/Stormy-WeatherApp/tree/SQL/app/src/main/java/com/tsm/stormy/SQL – TSM

+0

此外,當我重新啓動應用程序,它將刪除位置.. 。 – TSM