Android中的SQLite不更新或删除内容

时间:2014-09-11 22:17:00

标签: android database sqlite

我正在开发一个使用SQLite的应用程序。到目前为止一直没有问题,我已经能够插入行和所有内容,但是当涉及更新或删除时,数据不会改变。

我一开始并没有使用beginTransaction()endTransaction()因为插入语句完成了它的工作并且不需要它,但是研究&试图找到我留在那里的解决方案,我认为这就像提交一样。

也许问题是我在WHERE子句中没有使用ID,我使用纬度和经度(这也很独特,让我的事情变得更容易),但我不知道,我应该能够在WHERE子句中使用我喜欢的任何条件。

下一段代码在我的SQLite处理程序/帮助程序

public void updateMarker(String title, String description, double latitude, double longitude, String color){
          ContentValues valores = new ContentValues();
          valores.put("title",title);
          valores.put("description",description);
          valores.put("lat",latitude);
          valores.put("long",longitude);
          valores.put("color",color);

          this.getWritableDatabase().beginTransaction();
          // Not updating (deleting is pretty much the same code)
          this.getWritableDatabase().update("markers", valores, "lat='"+latitude+"' AND long='"+longitude+"';", null);

          this.getWritableDatabase().setTransactionSuccessful();
          this.getWritableDatabase().endTransaction();
          this.getWritableDatabase().close();
      }

这个方法就像这样调用; addMarker是Marker,color是一个字符串。我确信没有空指针。

handler.updateMarker(addMarker.getTitle(), addMarker.getSnippet(), addMarker.getPosition().latitude, addMarker.getPosition().longitude, color);

预期的结果是,当我加载标记时,它应该使用新信息加载更新的标记,并且不加载已删除的标记,但它只是没有。

解决方案:我所做的是创建一个带有对象标记和int ID的新类,现在一切都运行良好。

1 个答案:

答案 0 :(得分:1)

您正在比较浮点值是否相等。这很可能是导致问题的原因。我现在不确定是否有消息。

至于其他一些建议:

  1. 由于您只执行单个查询,因此不需要该事务。事务通常用于批量处理多个查询以提高效率。

  2. 由于字符串连接,您的代码容易受到SQL注入的影响。您应该使用参数化的WHERE子句:

    String where = "lat=? AND long=?"
    String[] whereArgs = {Double.toString(latitude), Double.toString(longitude)};
    this.getWritableDatabase().update("markers", valores, where, whereArgs);
    
  3. 您可以通过调用getWriteableDatabase()一次并将DB对象分配给引用来节省一些开销。

  4. 您可以直接传递addMarker并调用getters来创建ContentValues对象,从而减少方法的参数数量。

    1. 我觉得创建一个getContentValues()方法很方便,它接受一个模型对象(在你的情况下为Marker,也许?)并返回一个ContentValues。这整齐地封装了转换,以便在整个应用程序中使用。