我正在从网站下载数据库。下载的数据库名为db.php
它将存储在名为FishingMatey.db
的data / data / my.package.name / files下。数据库位于DDMS的文件系统中,我可以在SQLite Studio的PC上打开它。我的数据库中填充了正确的表格和正确的数据。这是我下载SQLite数据库的代码:
public boolean downloadDatabase() {
try {
// Log.d(TAG, "downloading database");
URL url = new URL("http://myurl.com/db.php");
// Open a connection to that URL */
URLConnection ucon = url.openConnection();
// Define InputStreams to read from the URLConnection
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
// Read bytes to the Buffer until there is nothing more to read(-1)
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
// Convert the Bytes read to a String
FileOutputStream fos = null;
// Select storage location
fos = this.context.openFileOutput(DATABASE_NAME, Context.MODE_PRIVATE);
fos.write(baf.toByteArray());
fos.close();
} catch (IOException e) {
Log.e("downloadDatabase", "downloadDatabase Error: ", e);
return false;
} catch (NullPointerException e) {
Log.e("downloadDatabase", "downloadDatabase Error: ", e);
return false;
} catch (Exception e) {
Log.e("downloadDatabase", "downloadDatabase Error: ", e);
return false;
}
return true;
}
我的问题:我可以用数据库打开
SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.menuswitcher/files/" + DATABASE_NAME, null, SQLiteDatabase.OPEN_READONLY);
,但如果我输入db.query(DATABASE_TABLE_Bewirtschafter, null, null, null, null, null, null);
,我会收到以下错误:
01-08 19:52:22.366: E/AndroidRuntime(6157): FATAL EXCEPTION: main
01-08 19:52:22.366: E/AndroidRuntime(6157): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
以下是我在Activity中调用它的方式: this.b3.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
DBAccess dbAccess = new DBAccess(HauptmenueActivity.this, 1, "FishingMatey.db");
if (dbAccess.downloadDatabase()) {
dbAccess.initDatabase();
Cursor cur = dbAccess.createBewirtschafterAllCursor();
Log.v("b3", cur.getString(cur.getColumnIndex("name")));
} else {
Log.e("b3", "Error!");
}
}
});
有人知道为什么这不起作用吗?
答案 0 :(得分:0)
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
此错误表示您在尝试读取光标之前忘记调用cursor.moveToFirst()
。
Cursor cursor = db.query(DATABASE_TABLE_Bewirtschafter, null, null, null, null, null, null);
if(cursor.moveToFirst()) {
// Do something with the first row, if it exists
}