I’m downloading a database from a website. The downloaded database is called db.php
and it’s going to be stored at data/data/my.package.name/files under the name FishingMatey.db. The database is in the filesystem from the DDMS and I can open it on the PC in SQLite Studio. There my database is filled with the right tables and the right data. Here’s my code to download the SQLite database:
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;
}
My problem: I can open the database with
SQLiteDatabase db = SQLiteDatabase.openDatabase("/data/data/com.example.menuswitcher/files/" + DATABASE_NAME, null, SQLiteDatabase.OPEN_READONLY);, but if I enter db.query(DATABASE_TABLE_Bewirtschafter, null, null, null, null, null, null); I receive the following error:
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
Here’s how I call it in the 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!");
}
}
});
Does anybody know why this doesn’t work?
This error means that you forgot to call
cursor.moveToFirst()before trying to read your Cursor.