In fact, SQLiteOpenHelper is responsible for creating, updating, and more. If you want to create table programs, then you need to write a query for the creation tables in the onCreate method of the SQLiteOpenHelper class. If you want to update your database after a previously created database, you can write modified table queries using the onUpgrade method only; you will have to change the version of the database.
If you have already created the database from the outside, and if you want to use this database, you need to put this database in the resource folder and copy this file to the database folder, which is located in the /data/data/packagename/databases folder.
here is an example for copying a database from database to database
private static boolean copyDataBase(Context c) throws IOException { String DB_PATH = "/data/data/" + c.getPackageName() + "/databases/"; AssetManager mg = c.getResources().getAssets(); InputStream myInput = null; try { myInput = mg.open(DATABASE_NAME); } catch (IOException ex) { return false; } if (myInput != null) { String outFileName = DB_PATH + DATABASE_NAME; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[8000]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); myInput.close(); Log.d(TAG, "Database is copied"); return true; } return false; }
Here is a method for checking databases and its version for copying
public void copyDatabase() { try { SharedPreferences preferences = c.getSharedPreferences(c.getPackageName(), Context.MODE_PRIVATE); if (checkDataBase(c)) { if (preferences.getInt("dbversion", 0) != 0) { c.deleteDatabase(DatabaseHelper.DATABASE_NAME); } } getReadableDatabase(); close(); if (copyDataBase(c)) { Editor editor = preferences.edit(); editor.putInt("dbversion", DatabaseHelper.DATABASE_VERSION); editor.commit(); } } catch (Exception e) { e.printStackTrace(); } }
Here is an example that checks if a database exists or not?
public static boolean checkDataBase(Context c) { File f = new File("/data/data/" + c.getPackageName() + "/databases/" + DATABASE_NAME); if (!f.exists()) return false; SQLiteDatabase checkDB = null; try { checkDB = SQLiteDatabase .openDatabase("/data/data/" + c.getPackageName() + "/databases/" + DATABASE_NAME, null, SQLiteDatabase.OPEN_READONLY); checkDB.close(); } catch (SQLiteException e) { e.printStackTrace(); } return checkDB != null ? true : false; }
source share