我正在编写一个应用程序,它将从远程服务器上的xml文件中读取数据,然后将其放入手机/选项卡上的SQLite数据库中。我知道它成功地从xml中读取数据并将其放入SQLite .db文件中。但是,问题是我的应用程序的其余部分就好像SQLite .db文件为空。它不会访问数据,直到我退出应用程序并再次运行它。我做错了什么?
以下是我获取数据的方式:
// Get Instrument data from XML
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
// Get the name of the tag (eg data or datum)
String strName = instruments.getName();
if (strName.equals("datum")) {
bFoundInstruments = true;
String datumDate = instruments.getAttributeValue(null, "date");
Float datumWtioil = Float.parseFloat(instruments.getAttributeValue(null, "wtioil"));
Float datumHh = Float.parseFloat(instruments.getAttributeValue(null, "hh"));
Float datumPlat = Float.parseFloat(instruments.getAttributeValue(null, "plat"));
publishProgress(datumDate, Float.toString(datumWtioil), Float.toString(datumHh), Float.toString(datumPlat));
// add data to SQLite database
datasource.createInstrument(datumDate, Float.toString(datumWtioil), Float.toString(datumHh), Float.toString(datumPlat));
}
}
现在我在这里使用createInstrument()方法将它放入SQLite .db文件中:
public Instrument createInstrument(String instrumentDate, String instrumentWtioil, String instrumentHh,
String instrumentPlat) {
ContentValues values = new ContentValues();
//Log.d("instrumentalityWtioil",instrumentWtioil);
values.put(ForecastSQLiteHelper.COLUMN_DATE, instrumentDate);
values.put(ForecastSQLiteHelper.COLUMN_DATA1, instrumentWtioil);
values.put(ForecastSQLiteHelper.COLUMN_DATA2, instrumentHh);
values.put(ForecastSQLiteHelper.COLUMN_DATA3, instrumentPlat);
long insertId = database.insert(ForecastSQLiteHelper.TABLE_DATA, null,
values);
Cursor cursor = database.query(ForecastSQLiteHelper.TABLE_DATA,
allColumns, ForecastSQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Instrument newInstrument = cursorToInstrument(cursor);
cursor.close();
return newInstrument;
}
为什么该应用程序无法立即获得该数据?为什么我必须关闭应用程序并在它可见之前重新启动它?
非常感谢任何建议。
答案 0 :(得分:3)
首先删除从此函数获取db值的查询,因为您尝试将一个工具插入db然后再读回。这样做:
a)从xml文件中读取并将它们添加到db和
b)创建一个函数,进行查询并返回db中的所有仪器。
public List< Instrument > getAllInstruments() {
// create a list
List<Instrument> list = new ArrayList< Instrument>();
Cursor cursor = database.query(ForecastSQLiteHelper.TABLE_DATA,
allColumns, null, null, null, null, null);
// check if cursor has columns
if (cursor.getColumnCount() > 0) {
// read all cursor values
while (cursor.moveToNext()) {
Instrument newInstrument = new Instrument();
// now you have to get the values from the cursor and add them to your object
// like this
String instrumentName= cursor.getString(cursor.getColumnIndex(COLUMN_NAME));
// COLUMN_NAME is the name of the column in your database that you want the value of
// now add the values to the Instrument object
newInstrument.setName(instrumentName);
// now add the object to the list
list.add(newInstrument);
}
}
cursor.close();
return list; //finally return the list
}