Android SQLite插入不起作用

6
我有一个GPS位置插入代码,但是它不能插入数据库:
db.setVersion(1);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);

final String gps = "CREATE TABLE IF NOT EXISTS GPS_Values ("
                + "id INTEGER PRIMARY KEY AUTOINCREMENT, Latitude float(10, 6), Longitude float(10, 6), cur_timestamp TIMESTAMP);";
db.execSQL(gps);

还有插入行:

// GPS
public class MyLocationListener implements LocationListener {
    public void onLocationChanged(Location loc) {
        loc.getLatitude();
        loc.getLongitude();

        ContentValues gps_values = new ContentValues();

        gps_values.put("Latitude", loc.getLatitude());
        gps_values.put("Longitutde", loc.getLongitude());


        try {
            db.beginTransaction();
            db.insert("GPS_Values", null, gps_values);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }

        String Text = "My current location is: " + "Latitude = "
                + loc.getLatitude() + "\nLongitude = " + loc.getLongitude();

        Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT)
                .show();

    }

    public void onProviderDisabled(String provider) {
        Toast.makeText(getApplicationContext(), "Gps Disabled",
                Toast.LENGTH_SHORT).show();
    }

    public void onProviderEnabled(String provider) {
        Toast.makeText(getApplicationContext(), "Gps Enabled",
                Toast.LENGTH_SHORT).show();
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

}// gps vége

当尝试获取位置时,一切都正常,但插入操作出现问题。我有类似的代码使用了加速度计,那个可以正常工作。请帮助我。
3个回答

15
尝试使用insertOrThrow代替,如果您的数据库约束不允许特定插入,则会引发异常,然后您将能够弄清楚原因。

2
救了我的一天!insertOrThrow抛出了一个错误,我知道出了什么问题。 - Jenny

9

您正在添加的列中有一个错别字:

    gps_values.put("Longitutde", loc.getLongitude());

应该是

    gps_values.put("Longitude", loc.getLongitude());

insert() 调用返回-1表示发生错误,但您没有检查返回值。通常更容易使用 insertOrThrow,它在错误时会抛出异常。


这是因为没有插入任何东西。 - David
是的,如果您尝试插入到不存在的列,则会生成错误。 - Graham Borland
好的...现在它可以工作了 :) 谢谢!!! 但是这只是我不知道如何称呼它,所以这里有一个例子:41.2211 <- 只有41.后面的4。:) - David

0

你试图插入“Longitutde”,但你创建了一个名为“Longitude”的字段


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接