我在Android应用中使用SQLite。一切都很棒但是当我在我的天气应用程序中添加一个位置然后将其滑开时,它不会从TABLE中删除该位置。
在这里,我获取位置,添加位置并将其删除。
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)
游标是临时对象,不应该长时间保留。
无论如何,光标中的位置不一定与列表中的位置相同,尤其是在您进行更改后,或者您正在进行排序/过滤时。 将ID存储在列表中,然后使用它来访问该行。