SQLiteDatabase插入返回-1

时间:2014-08-29 10:37:31

标签: android sqlite

请帮助。我被卡住了。有人会告诉我为什么我在JUnit测试中有AssertionFailedError。我不知道为什么SQLiteDatabase db insert方法返回-1。

错误指向第50行:assertTrue(locationRowId!= -1);

public void testInsertReadDb() {
    // Test data we're going to insert into the DB to see if it works.
    String testLocationSetting = "99705";
    String testCityName = "North Pole";
    double testLatitude = 64.7488;
    double testLongitude = -147.353;

    // If there's an error in those massive SQL table creation Strings,
    // errors will be thrown here when you try to get a writable database.
    WeatherDbHelper dbHelper = new WeatherDbHelper(mContext);
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    // Create a new map of values, where column names are the keys
    ContentValues values = new ContentValues();
    values.put(LocationEntry.COLUMN_LOCATION_SETTING, testLocationSetting);
    values.put(LocationEntry.COLUMN_CITY_NAME, testCityName);
    values.put(LocationEntry.COLUMN_COORD_LAT, testLatitude);
    values.put(LocationEntry.COLUMN_COORD_LONG, testLongitude);

    //long locationRowId;
    long locationRowId = db.insert(LocationEntry.TABLE_NAME, null, values);

    // Verify we got a row back.
    assertTrue(locationRowId != -1);
    Log.d(LOG_TAG, "New row id: " + locationRowId);

这是错误:

Running tests
Test running started
junit.framework.AssertionFailedError
at com.example.krisemmanuel.sunshine.test.TestDb.testInsertReadDb(TestDb.java:50)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1729)

Finish

这是一个错误的屏幕: http://picpaste.com/debughelpplease-IuEAYaNu.png

Android Studio项目文件夹: http://krisg.net/java/Sunshine.rar

我不知道为什么SQLiteDatabase db的insert()方法返回-1。我试图测试插入到SQLite是否有效,但它在测试时失败。

1 个答案:

答案 0 :(得分:1)

SQLiteDatabase.insert()失败时,它只记录错误消息并返回-1。

要获取例外,请改用insertOrThrow