应用在首次运行时加载数据库时崩溃

时间:2018-10-22 07:36:57

标签: java android json database sqlite

在我的应用中,我正在使用一项服务来从JSON获取数据,然后将其保存在数据库中。

当我在新设备上运行该应用程序时,它崩溃没有任何错误

但是当我注释掉要加载到TextViews中的代码时,它可以完美运行。在那之后,即使我带回代码来输入TextView,它也能正常工作。

更新: 在我注释掉用于馈送TextViews的代码之前,用于馈送数据库的服务不会运行。

用于馈送TextViews的代码:

//this service contains JSON to DB code
Intent intent = new Intent(MainActivity.this, GetdataService.class);
startService(intent);

cursor = DBOps.Ops.getTheOne();
cursor.moveToNext();

//app crashes at this line    
wordText.setText(cursor.getString(cursor.getColumnIndex(DBContracts.Word.TITLE)));
phonetic = cursor.getString(cursor.getColumnIndex(DBContracts.Word.PHONETIC));
meaningText.setText(cursor.getString(cursor.getColumnIndex(DBContracts.Word.MEANING)));
exampleText.setText(cursor.getString(cursor.getColumnIndex(DBContracts.Word.EXAMPLE)));

获取商品的方法:

public static Cursor getTheOne(){
    return db.query(DBContracts.Word.TABLE_NAME,
            null,
            null,
            null,
            null,
            null,
            DBContracts.Word._ID + " DESC LIMIT 1"
    );
}

1 个答案:

答案 0 :(得分:0)

在发生崩溃时,请考虑检查堆栈跟踪。

但是从您的描述来看:第一次运行时崩溃,在以后的运行中起作用-这表明第一次运行时没有数据,但在以后的运行中,查询返回了一些数据。

cursor.moveToNext()返回一个布尔值,如果移动成功,即有一些数据,则返回true。您应该始终检查游标moveTo...()的返回值。崩溃本身是由于无效行上的Cursor#getString()

相关问题