Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is the simple and convenient code which I use:</p> <pre><code>public class DataBaseImportHelper { private DataBaseImportHelper() {}; // Avoid instantiation /** * Creates a empty database on the system and rewrites it with your own database. */ public static boolean importDataBase(Context context) { InputStream myInput = null; OutputStream myOutput = null; try { // Open local db from assets as the input stream myInput = context.getAssets().open(DATABASE_NAME); createEmptyDatabase(context); // See this method below // Open the empty db as the output stream myOutput = new FileOutputStream(getDatabaseFile(context)); // transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) &gt; 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myInput.close(); myOutput.close(); return true; } catch (IOException e) { e.printStackTrace(); } return false; } /** * Check if the database already exists. * @return true if it exists, false if it doesn't */ public static boolean isDatabaseExists(Context context) { return getDatabaseFile(context).exists(); } private static File getDatabaseFile(Context context) { return context.getDatabasePath(DatabaseHelper.DATABASE_NAME); } /** * Create an empty database into the default application database * folder.So we are gonna be able to overwrite that database with our database */ private static void createEmptyDatabase(Context context) { // use anonimous helper to create empty database new SQLiteOpenHelper(context, DatabaseHelper.DATABASE_NAME, null, 1) { // Methods are empty. We don`t need to override them @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } @Override public void onCreate(SQLiteDatabase db) { } }.getReadableDatabase().close(); } </code></pre> <p>}</p> <p>And using in code:</p> <pre><code>if(!DataBaseImportHelper.isDatabaseExists(this)){ if (!DataBaseImportHelper.importDataBase(this)){ throw new IllegalStateException("Database doesn`t exist and hasn`t been copied!"); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload