【问题标题】:Saving the Latitude and Longitude on map click to SQLite database not working在地图上保存纬度和经度点击到 SQLite 数据库不起作用
【发布时间】:2021-12-14 12:09:48
【问题描述】:

我正在尝试将纬度和经度保存到我的 SQLite 数据库中。但是它没有保存它,也没有收到任何错误消息。

这是我到目前为止的代码:

dbHandler = new DBHandler(MapsActivity.this);
    googleMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

        @Override
        public void onMapLongClick(LatLng latLng) {

            String latLong = latLng.latitude + " : " + latLng.longitude;

            dbHandler.addNewLocation(latLong);

            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title(latLng.latitude + " : " + latLng.longitude);
            googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            googleMap.addMarker(markerOptions);
            Toast.makeText(MapsActivity.this, "Location has been added.", Toast.LENGTH_SHORT).show();
        }
    });

然后是 DBHandler 类:

public class DBHandler extends SQLiteOpenHelper {

private static final String DB_NAME = "locationsdb";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "mylocations";
private static final String ID_COL = "id";
private static final String NAME_LAT = "lat";

public DBHandler(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_NAME + " ("
            + ID_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + NAME_LAT + " TEXT)";

    db.execSQL(query);
}

public void addNewLocation(String latLong) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(NAME_LAT, latLong);
    db.insert(TABLE_NAME, null, values);
    db.close();
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // this method is called to check if the table exists already.
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}
}

那么当我检查数据库时,里面没有保存任何东西?

有人可以告诉我我在这里做错了什么吗?

谢谢

【问题讨论】:

  • 查看db.insert(TABLE_NAME, null, values)的返回值。如果不是 -1,则该行被添加到表中。
  • 或使用insertOrThrow() 来获取异常,详细说明它可能失败的原因。

标签: java android sqlite android-sqlite


【解决方案1】:

在调用getWritableDatabase() 后尝试db.beginTransaction() 并在addNewLocation(...) 中使用db.endTransaction() 而不是db.close()

【讨论】:

    猜你喜欢
    • 2011-08-04
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多