2012-07-03 67 views
0

我想從PHP(服務器)下載SQLITE數據庫並將其複製到Android(客戶端)的資產文件夾。我沒有得到所需的輸出。有人可以告訴我我犯了什麼錯誤或錯過了什麼嗎?謝謝你的幫助。下載並從數據庫從服務器複製到資產文件夾android

代碼:

boolean downloadDatabase(Context context) { 
    try { 
      Log.d("test", "downloading database"); 
      URL url = new URL("http://10.0.2.2/SvcEnggPlanner/" + "Services.sqlite"); 
      URLConnection ucon = url.openConnection(); 
      InputStream is = ucon.getInputStream(); 
      BufferedInputStream bis = new BufferedInputStream(is); 
      ByteArrayBuffer baf = new ByteArrayBuffer(50); 
      int current = 0; 
      while ((current = bis.read()) != -1) { 
        baf.append((byte) current); 
      } 

      FileOutputStream fos = null; 

      fos = context.openFileOutput("Services.sqlite", Context.MODE_PRIVATE); 
      if(fos!=null){ 
      fos.write(baf.toByteArray()); 
      fos.close(); 
      Log.d("test", "downloaded"); 
      } 
    } catch (IOException e) { 
      Log.e("test", "downloadDatabase Error: " , e); 
      return false; 
    } catch (NullPointerException e) { 
      Log.e("test", "downloadDatabase Error: " , e); 
      return false; 
    } catch (Exception e){ 
      Log.e("test", "downloadDatabase Error: " , e); 
      return false; 
    } 
    return true; 
} 

public void copyServerDatabase() { 
    SQLiteDatabase db = getReadableDatabase(); 
    db.close(); 

     OutputStream os = null; 
     InputStream is = null; 
     try { 
       Log.d("test", "Copying DB from server version into app"); 
       is = context.openFileInput("Services.sqlite"); 
       Log.d("test", ""+is); 
       os = new FileOutputStream("/data/data/com.sever/databases/"); 
       Log.d("test", ""+os); 
       copyFile(os, is); 
     } catch (Exception e) { 
      Log.d("test", "Server Database was not found - did it download correctly?");       
     } 
finally { 
       try { 

         if(os != null){ 
           os.close(); 
         } 
         if(is != null){ 
           is.close(); 
         } 
       } catch (IOException e) { 
         Log.d("test", "failed to close databases"); 
       } 
     } 
     Log.d("test", "Done Copying DB from server"); 

} 

    private void copyFile(OutputStream os, InputStream is) throws IOException { 
    Log.d("test", "In CopyFile"); 
     byte[] buffer = new byte[1024]; 
     int length; 
     while((length = is.read(buffer))>0){ 
      os.write(buffer, 0, length); 
     } 
     os.flush(); 
} 
} 
+0

請有人幫助我嗎? – Yogi

+0

你不能保存在資產文件夾,但你可以保存在SD卡 –

+0

謝謝。我會照辦的。 – Yogi

回答

2

你不能在你的Android應用程序的文件夾assets寫入文件,因爲它是不可寫。 Android apk文件只能讀取,不可寫入。

+0

謝謝。你能建議我如何從服務器下載數據庫到Android設備? – Yogi

+0

您可以將它下載到設備的外部存儲器(sd卡)或應用程序的內部存儲器中。有關更多信息,請參閱此處(http://developer.android.com/guide/topics/data/data-storage.html)。 – Angelo

+0

感謝您的幫助。我會照辦的。 – Yogi

相關問題