2013-01-08 28 views
1

我從網站上下載的數據庫。下載的數據庫稱爲db.php ,它是怎麼回事名FishingMatey.db下被保存在數據/數據/ my.package.name /文件。數據庫位於DDMS的文件系統中,我可以在SQLite Studio的PC上打開它。在那裏我的數據庫充滿了正確的表格和正確的數據。這裏是我的代碼下載SQLite數據庫:錯誤在開放下載的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 

這是我怎麼稱呼它的活動: this.b3.setOnClickListener(新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!"); 
      } 
     } 
    }); 

是否anyb ody知道爲什麼這不起作用?

回答

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 
} 
+0

謝謝!有用! –