2010-04-09 90 views

回答

0

如果您打算創建一個新的SQLite數據庫,然後搭配並實施教程中所示的onCreate()方法。

但是,如果您使用的是由其他外部源創建的SQLite數據庫,並且您要將其拉下,請將onCreate()方法留空。

2

重要的是,在本教程中,當您調用該文件時,請確保您傳遞應用程序上下文getApplicationContext(),以便您有權訪問正確的資產,否則可能會得到FileNotFound異常。

33

試試這個代碼:

public class DataBaseHelper extends SQLiteOpenHelper { 
    private Context mycontext; 

    //private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/"; 
    private static String DB_NAME = "(datbasename).sqlite";//the extension may be .sqlite or .db 
    public SQLiteDatabase myDataBase; 
    /*private String DB_PATH = "/data/data/" 
         + mycontext.getApplicationContext().getPackageName() 
         + "/databases/";*/ 

    public DataBaseHelper(Context context) throws IOException { 
     super(context,DB_NAME,null,1); 
     this.mycontext=context; 
     boolean dbexist = checkdatabase(); 
     if (dbexist) { 
      //System.out.println("Database exists"); 
      opendatabase(); 
     } else { 
      System.out.println("Database doesn't exist"); 
      createdatabase(); 
     } 
    } 

    public void createdatabase() throws IOException { 
     boolean dbexist = checkdatabase(); 
     if(dbexist) { 
      //System.out.println(" Database exists."); 
     } else { 
      this.getReadableDatabase(); 
      try { 
       copydatabase(); 
      } catch(IOException e) { 
       throw new Error("Error copying database"); 
      } 
     } 
    } 

    private boolean checkdatabase() { 
     //SQLiteDatabase checkdb = null; 
     boolean checkdb = false; 
     try { 
      String myPath = DB_PATH + DB_NAME; 
      File dbfile = new File(myPath); 
      //checkdb = SQLiteDatabase.openDatabase(myPath,null,SQLiteDatabase.OPEN_READWRITE); 
      checkdb = dbfile.exists(); 
     } catch(SQLiteException e) { 
      System.out.println("Database doesn't exist"); 
     } 
     return checkdb; 
    } 

    private void copydatabase() throws IOException { 
     //Open your local db as the input stream 
     InputStream myinput = mycontext.getAssets().open(DB_NAME); 

     // Path to the just created empty db 
     String outfilename = DB_PATH + DB_NAME; 

     //Open the empty db as the output stream 
     OutputStream myoutput = new FileOutputStream("/data/data/(packagename)/databases /(datbasename).sqlite"); 

     // transfer byte to inputfile to outputfile 
     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = myinput.read(buffer))>0) { 
      myoutput.write(buffer,0,length); 
     } 

     //Close the streams 
     myoutput.flush(); 
     myoutput.close(); 
     myinput.close(); 
    } 

    public void opendatabase() throws SQLException { 
     //Open the database 
     String mypath = DB_PATH + DB_NAME; 
     myDataBase = SQLiteDatabase.openDatabase(mypath, null, SQLiteDatabase.OPEN_READWRITE); 
    } 

    public synchronized void close() { 
     if(myDataBase != null) { 
      myDataBase.close(); 
     } 
     super.close(); 
    } 

} 
+0

不錯,對我來說工作正常; d – 2013-04-19 08:06:32

+3

實際上,在編碼時使用mycontext.getApplicationInfo()。dataDir而不是硬編碼「/ data/data /(packagename)」。這是獲取應用程序數據目錄的官方方式。 – wheredidthatnamecomefrom 2014-10-21 14:29:50

6

將舊數據庫(old.db)在你的資源文件夾。鍵入這裏面的onCreate()你的活動:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
.... 

//=======Code For copying Existing Database file to system folder for use====// 
    // Copying Existing Database into system folder 
     try { 

      String destPath = "/data/data/" + getPackageName() 
        + "/databases/data.db"; 

      File f = new File(destPath); 
      if(!f.exists()){ 
      Log.v(TAG,"File Not Exist"); 
      InputStream in = getAssets().open("old.db"); 
      OutputStream out = new FileOutputStream(destPath); 

      byte[] buffer = new byte[1024]; 
      int length; 
      while ((length = in.read(buffer)) > 0) { 
       out.write(buffer, 0, length); 
      } 
      in.close(); 
      out.close(); 
      } 

     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      Log.v("TAG","ioexeption"); 
      e.printStackTrace(); 
     } 

     DBManager dbManager = new DBManager(this); 
     Log.v(TAG,"Database is there with version: "+dbManager.getReadableDatabase().getVersion()); 
     String sql = "select * from prizes"; 


     SQLiteDatabase db = dbManager.getReadableDatabase(); 
     Cursor cursor = db.rawQuery(sql, null); 
     Log.v(TAG,"Query Result:"+cursor); 


     cursor.close(); 
     db.close(); 
     dbManager.close(); 

.... 

} 

現在你必須做出一個DBManager類的子類SQLiteOpenHelper。插入抽象方法和構造函數。不要忘記在dbHelper的super()中輸入正確的數據庫名稱。

public class DBManager extends SQLiteOpenHelper { 

private static final int DATABASE_VERSION = 1; 
private static final String TAG = "DATABASES"; 

public DBManager(Context context) { 
    super(context, "data.db", null, DATABASE_VERSION); 

} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    Log.v(TAG,"On create Called:"+db.getPath()); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
} 
} 

現在,您可以通過實例化DBManager來訪問數據庫。

SQLiteDatabase db = dbManager.getReadableDatabase(); 
Cursor cursor = db.rawQuery(sql, null); 
... 

不要忘記關閉數據庫或你會得到一個SQLiteDatabaseNotClosed異常。

db.close(); 
dbManager.close(); 
1

你會想嘗試android sqlite asset helper。它爲我打開了一個預先存在的db一塊蛋糕。

我花了3個小時試圖手動完成所有工作,大概花了半個小時。有趣的是,我認爲我正在做圖書館爲我做的同樣的事情,但有些東西丟失了!

0

只能從資源文件夾讀取數據庫,因爲資源文件夾是隻讀的。如果你需要做更多的操作,如創建,更新,刪除,你可以做一個技巧。將資產數據庫中的數據庫複製到存儲中,然後您可以執行任何您想要的操作。

這裏是Working with Android Pre Built Database.

一個簡單的例子有一個易於使用的庫也從資產的文件夾中訪問數據庫。你可以檢查Android SQLiteAssetHelper(https://github.com/jgilfelt/android-sqlite-asset-helper)。祝你好運!

0

您需要將.sqlite數據庫轉換爲.db才能適應Android。

在你的應用首次啓動安裝

SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.COPY_TO_SYSTEM); 

後,在隨後的發佈會

SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.READ_FROM_DEVICE); 

只要火SQL查詢

database.sqlInject("INSERT INTO food VALUES('Banana','Vitamin A');"); 

取得成果在數組中CSV,JSON,XML

ArrayList<String> rows=new ArrayList<String>(); 
rows=database.sqlEjectCSV("SELECT * FROM food;"); 
for (int i=0;i<rows.size();i++) 
{ 
    //Do stuffs with each row 
} 

您需要爲此包含我的庫。此處的文檔:
https://github.com/sangeethnandakumar/TestTube

相關問題