CS453 | mobile programming
  • outline
  • projects
  • syllabus
  • links

Android - Precreating an SQLite Database and Bundling w/ Project

 

Step 1: create SQLite Database using some client tool

Example : SQLiteBrowser

 

Step 2: Move created database file from step 1 to assests folder in project

Example : right click on assets folder and "import->File System" then select wherever the sql file is from step #1.

assets folder location for database file

 

 

 

 

 

 

 

 


<<<<<here we have the mydb database file in the assests folder

 

 

 

 

 

 

Step 3: In your code you must "copy" this database located assests folder to the database folder

 
//INSIDE YOUR ACTIVITY CLASS

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);

try { String destPath = "/data/data/" + getPackageName() +"/databases"; File f = new File(destPath); if (!f.exists()) { f.mkdirs(); f.createNewFile(); //---copy the database from the file assets/mydb // TO the databases folder with name MyDB CopyDB(getBaseContext().getAssets().open("mydb"), new FileOutputStream(destPath + "/MyDB")); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //method to copy over file public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException { //---copy 1K bytes at a time--- byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); }//end copyDB

 

cs453:mobile programming

  • home
  • outline
  • projects
  • syllabus
  • links