resetting pre-populated sqlite database in android - java

I added a pre-populated database to the assets directory in an Android App, but when I delete and add a new one the query results still return old data.
I followed this tutorial, and below is my database class:
package com.example.fishselector;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
class DB extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.fishselector/databases/";
private static String DB_NAME = "sqldb3";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DB(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
//do nothing - database already exist
} else {
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
//database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
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(outFileName);
//transfer bytes from the inputfile to the 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_READONLY);
}
#
Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
#
Override
public void onCreate(SQLiteDatabase db) {
try {
createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#
Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
}

It's not working because you are not deleting the database file on the file system.
What your code does is copy the file from assets into the private storage area for your app in /data/data/com.example.fishselector/databases/.
Then the next time you run it you check if it already exists there, and if it does, do nothing:
boolean dbExist = checkDataBase();
if (dbExist) {
//do nothing - database already exist
} else {
So simply deleting it or replacing it in assets won't mean a thing because hey ho, there it still is, in /data/data/ as if nothing happened.
To fix: in your emulator, go into "Settings/Apps/YourApp/" and click "Clear Data". This will delete any data in the private storage area for your app. Then you can try and run your app again and it will not find the file and will copy your new database over from assets.

Related

Android SQLite, onCreate() not being called

I've been struggling to create a SQLite DB within my Android application.
I've looked at numerous tutorials, and quite a few existing questions on stack overflow and other sites.
Here is my DatabaseHelper class
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
public SQLiteDatabase db;
public static final String DATABASE_NAME = "user.db";
//Module table
public static final String MODULE_TABLE = "modules_table";
public static final String MODULE_COL_1 = "ID";
public static final String MODULE_COL_2 = "CODE";
public static final String MODULE_COL_3 = "TITLE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
Log.d("SQL", "SQLite dbhelper");
db = getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("create table " + MODULE_TABLE + "(" + MODULE_COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MODULE_COL_2 + " TEXT, " + MODULE_COL_3 + " TEXT " +")");
db.execSQL("create table modules_table (ID INTEGER PRIMARY KEY
AUTOINCREMENT, CODE TEXT, TITLE TEXT)");
Log.d("SQL", "SQLite onCreate");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + MODULE_TABLE);
onCreate(db);
}
}
I've managed to get SQLite dbhelper to appear in logcat, but cannot get SQLite onCreate to appear, and cannot find the db anywhere in the file explorer or the device itself, both emulated and real device.
Any help would be greatly appreciated, and apologies for the formatting of the code!
I'd suggest using the following (temporarily) in the activity :-
DatabaseHelper myDBHelper = new DatabaseHelper(this); //<<<<<<<<< you appear to already have the equivalent of this line (if so use whatever variable name you have given to the DatabaseHelper object)
Cursor csr = myDBHelper.getWritableDatabase().query("sqlite_master",null,null,null,null,null,null);
DatabaseUtils.dumpCursor(csr);
csr.close();
Run and then check the log. You should see output for your modules_table and also sqlite_sequence (the latter because you have coded autoincrement.
sqlite_master is a system table that stores system information, such as table and index names i.e. the schema.
Additional - access to the database file
On a device that isn't rooted each applications data (data/data) is protected so you won't be able to see the database file.
On an emulator, it depends upon the emulator. I believe later versions of Android studio do now allow access e.g. :-
Note the above is Android 10.1 Pie (API 28) and hence the database has Write-Ahead Logging (WAL) and thus the -shm and -wal files also exist.
The package is mjt.pvcheck. The full path is data/data/mjt.pvcheck/databases.
As you can see cache directory, then I'd suggest that for some reason, perhaps a failure, the database doesn't exist, but you do appear to have access as per however upon checking through the virtual device file explorer the only sub folder I have within my package is the cache.
Perhaps, try rerunning on the device (note in device explorer re-select the device as it doesn't refresh), which may be another reason why you didn't see the database.
I don't use SQL query like
db.execSQL("create table modules_table (ID INTEGER PRIMARY KEY
AUTOINCREMENT, CODE TEXT, TITLE TEXT)");
Log.d("SQL", "SQLite onCreate");
instead, I'm using my own implementation of SQLiteOpenHelper class
import android.content.Context;
import android.content.res.AssetManager;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.zip.GZIPOutputStream;
public class DbProvider extends SQLiteOpenHelper {
private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock(true);
private static final int VERSION = 0;
private final String DB_NAME = "mydb";
private final AssetManager assets;
private DbProvider(Context context) {
super(context, DB_NAME, null, VERSION);
assets = context.getAssets();
}
#NonNull
public static DbProvider getInstance() {
return new DbProvider(App.getContext());
}
#NonNull
public static ReentrantReadWriteLock.WriteLock writeLock() {
return LOCK.writeLock();
}
#NonNull
public static ReentrantReadWriteLock.ReadLock readLock() {
return LOCK.readLock();
}
#NonNull
public static ReentrantReadWriteLock getLock() {
return LOCK;
}
public static void close(DbProvider instance) {
try {
instance.close();
} catch (Exception ex) {
}
}
#Override
public void onCreate(SQLiteDatabase db) {
executeQuery(db, "db-scripts/database.sql", false);
Log.w("database", "database create");
executeQuery(db, "db-scripts/database_updates.sql", true);
Log.w("database", "database update");
}
private void executeQuery(SQLiteDatabase db, String sql, boolean shouldHandleExceptions) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(assets.open(sql)));
String line;
File tempDbScript = new File(Environment.getExternalStorageDirectory(), "iErunt/dbBackup");
tempDbScript.getParentFile().mkdirs();
tempDbScript.createNewFile();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempDbScript));
while ((line = bufferedReader.readLine()) != null) {
line = line.replaceAll("\t+", " ").replaceAll("\n+", " ").replaceAll(" +", " ").replaceAll(";", ";\n");
if (line.startsWith("--") || line.isEmpty()) {
continue;
}
bufferedWriter.write(line);
bufferedWriter.flush();
}
bufferedWriter.close();
bufferedReader.close();
bufferedReader = new BufferedReader(new FileReader(tempDbScript));
db.beginTransaction();
while ((line = bufferedReader.readLine()) != null) {
if (!(line = line.trim().replace(";", "")).isEmpty()) {
if (shouldHandleExceptions) {
try {
db.execSQL(line);
} catch (SQLException ex) {
Log.e("database", ex.getMessage(), ex);
}
} else {
db.execSQL(line);
}
}
}
db.setTransactionSuccessful();
db.endTransaction();
tempDbScript.delete();
} catch (IOException ex) {
Log.e("database", ex.getMessage(), ex);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
}
}
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
executeQuery(db, "db-scripts/database_updates.sql", true);
}
}
and put initial DB schema of your database in assets/db-scripts/database.sql
and whenever you make DB modifications put your alter queries in assets/db-scripts/database_updates.sql. Be sure to increase VERSION of the database when updating the database.
What this class does is read your entire SQL script and executes one by one. which significantly reduces development time.
Note: You'll need android.permission.WRITE_EXTERNAL_STORAGE permission, as this creates a temp file and deletes it at the end
Hope this helps!

Eclipse error database connection [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
What should I do?Thanks
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
Public class DataBaseHelper extends SQLiteOpenHelper
{
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
//destination path (location) of our database on device
private static String DB_PATH = "";
private static String DB_NAME ="finala";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;
public DataBaseHelper(Context context)
{
super(context, DB_NAME, null, 1);// 1? its Database Version
if(android.os.Build.VERSION.SDK_INT >= 17){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.mContext = context;
}
public void createDataBase() throws IOException
{
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
this.getReadableDatabase();
this.close();
try
{
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
//Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
//Open the database, so we can query it
public boolean openDataBase() throws SQLException
{
String mPath = DB_PATH + DB_NAME;
//Log.v("mPath", mPath);
mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
//mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}
#Override
public synchronized void close()
{
if(mDataBase != null)
mDataBase.close();
super.close();
}
}
public class DataHelper {
}
And the errors are:
-The type DatabaseHelper must implement the inherited abstract method SQLiteOpenHelper.onCreate(SQLiteDatabase)
-Breakpoint:DataBaseHelper
-The type DatabaseHelper must implement the inherited abstract method SQLiteOpenHelper.onUpgrade(SQLiteDatabase,int,int)
-Syntax error on token "Public" public expected
-The public type DataBaseHelper must be defined in it's own file.
Public class DataBaseHelper extends SQLiteOpenHelper
That is not "Public"
"public" please.
You have to override onCreate() and onUpgrade() from SqliteOpenHelper
Because SqliteOpenHelper is an abstract class. Whenever you extends an abstract class you need to override (implement) the abstract methods of it.
Read the SQLiteHelper class reference.
-The type DatabaseHelper must implement the inherited abstract method SQLiteOpenHelper.onCreate(SQLiteDatabase)
You need to add
#Override
public void onCreate(SQLiteDatabase db) {
}
with some implementation that creates your database schema in case the database file was just created.
-Breakpoint:DataBaseHelper
There's a breakpoint on the line. This is not an error, just a message.
-The type DatabaseHelper must implement the inherited abstract method SQLiteOpenHelper.onUpgrade(SQLiteDatabase,int,int)
You need to add
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
as the method that updates your database schema. You can leave it empty at first.
-Syntax error on token "Public" public expected
Use public with lowercase p.
-The public type DataBaseHelper must be defined in it's own file.
Package-level public class sources must be in a file that matches the class name. DataHelper and DataBaseHelper do not match; rename the other.
Overall, it looks like you're trying to use a prepopulated database. Consider using android-sqlite-asset-helper library for that instead of attempting to copy a flawed example you've found somewhere.

Android Another Activity call Main Activity Databasehelper Function fail

Databasehelp.java
package com.example.abc2;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/com.example.abc2/databases/";
private static String DB_NAME = "DB_BusData";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
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(outFileName);
//transfer bytes from the inputfile to the 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_READONLY);
}
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// Add your public helper methods to access and get content from the database.
// You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
// to you to create adapters for your views.
}
MainActivity.java
public void printInspectorFormat(){
try {
Log.d(null,"1234545");
DataBaseHelper myDbHelper = new DataBaseHelper(this.getApplicationContext());
myDbHelper = new DataBaseHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
}
UltililyActivity.java
MainActivity cls2= new MainActivity();
cls2.printInspectorFormat();
when in Ultility Activity i m trying to call the Main activity Function, But return error
java.lang.NullPointerException
Maybe databasehelper does not share? or what? how to solve this?
You can not create instances of Activity yourself. They lack the Context that is added by the system when it creates them. Almost anything you can do with an Activity will fail if you created it yourself via new Activity().
But you can move your printInspectorFormat into another class responsible for database access and add a Context parameter. Now every Activity can use the method by passing itself as context.
class DbBackend {
public static void printInspectorFormat(Context context) {
try {
Log.d(null,"1234545");
DataBaseHelper myDbHelper = new DataBaseHelper(context.getApplicationContext());
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
}
}
from any Activity
DbBackend.printInspectorFormat(this);
You should also consider using a solid implementation for asset based databases like https://github.com/jgilfelt/android-sqlite-asset-helper since yours does not look very safe. And maybe read a tutorial like http://www.vogella.de/articles/AndroidSQLite/article.html which also shows you some pattern how to use SQLiteOpenHelper.

How to use an existing database with an Android application [duplicate]

This question already has answers here:
Ship an application with a database
(15 answers)
Closed 9 years ago.
I have already created an SQLite database. I want to use this database file with my Android project. I want to bundle this database with my application.
Instead of creating a new database, how can the application gain access to this database and use it as its database?
NOTE:
Before trying this code, please find this line in the below code:
private static String DB_NAME ="YourDbName"; // Database name
DB_NAME here is the name of your database. It is assumed that you have a copy of the database in the assets folder, so for example, if your database name is ordersDB, then the value of DB_NAME will be ordersDB,
private static String DB_NAME ="ordersDB";
Keep the database in assets folder and then follow the below:
DataHelper class:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper {
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
private static String DB_NAME ="YourDbName"; // Database name
private static int DB_VERSION = 1; // Database version
private final File DB_FILE;
private SQLiteDatabase mDataBase;
private final Context mContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
DB_FILE = context.getDatabasePath(DB_NAME);
this.mContext = context;
}
public void createDataBase() throws IOException {
// If the database does not exist, copy it from the assets.
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist) {
this.getReadableDatabase();
this.close();
try {
// Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}
// Check that the database file exists in databases folder
private boolean checkDataBase() {
return DB_FILE.exists();
}
// Copy the database from assets
private void copyDataBase() throws IOException {
InputStream mInput = mContext.getAssets().open(DB_NAME);
OutputStream mOutput = new FileOutputStream(DB_FILE);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
// Open the database, so we can query it
public boolean openDataBase() throws SQLException {
// Log.v("DB_PATH", DB_FILE.getAbsolutePath());
mDataBase = SQLiteDatabase.openDatabase(DB_FILE, null, SQLiteDatabase.CREATE_IF_NECESSARY);
// mDataBase = SQLiteDatabase.openDatabase(DB_FILE, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}
#Override
public synchronized void close() {
if(mDataBase != null) {
mDataBase.close();
}
super.close();
}
}
Write a DataAdapter class like:
import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class TestAdapter {
protected static final String TAG = "DataAdapter";
private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;
public TestAdapter(Context context) {
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}
public TestAdapter createDatabase() throws SQLException {
try {
mDbHelper.createDataBase();
} catch (IOException mIOException) {
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}
public TestAdapter open() throws SQLException {
try {
mDbHelper.openDataBase();
mDbHelper.close();
mDb = mDbHelper.getReadableDatabase();
} catch (SQLException mSQLException) {
Log.e(TAG, "open >>"+ mSQLException.toString());
throw mSQLException;
}
return this;
}
public void close() {
mDbHelper.close();
}
public Cursor getTestData() {
try {
String sql ="SELECT * FROM myTable";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur != null) {
mCur.moveToNext();
}
return mCur;
} catch (SQLException mSQLException) {
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
}
Now you can use it like:
TestAdapter mDbHelper = new TestAdapter(urContext);
mDbHelper.createDatabase();
mDbHelper.open();
Cursor testdata = mDbHelper.getTestData();
mDbHelper.close();
EDIT: Thanks to JDx
For Android 4.1 (Jelly Bean), change:
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
to:
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
in the DataHelper class, this code will work on Jelly Bean 4.2 multi-users.
EDIT: Instead of using hardcoded path, we can use
DB_PATH = context.getDatabasePath(DB_NAME).getAbsolutePath();
which will give us the full path to the database file and works on all Android versions
If you are having pre built data base than copy it in asset folder and create an new class as DataBaseHelper which implements SQLiteOpenHelper
Than use following code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelperClass extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/package_name/databases/";
// Data Base Name.
private static final String DATABASE_NAME = "DBName.sqlite";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE_Name = "tableName";
public Context context;
static SQLiteDatabase sqliteDataBase;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
* Parameters of super() are 1. Context
* 2. Data Base Name.
* 3. Cursor Factory.
* 4. Data Base Version.
*/
public DataBaseHelperClass(Context context) {
super(context, DATABASE_NAME, null ,DATABASE_VERSION);
this.context = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* By calling this method and empty database will be created into the default system path
* of your application so we are gonna be able to overwrite that database with our database.
* */
public void createDataBase() throws IOException{
//check if the database exists
boolean databaseExist = checkDataBase();
if(databaseExist){
// Do Nothing.
}else{
this.getWritableDatabase();
copyDataBase();
}// end if else dbExist
} // end createDataBase().
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
public boolean checkDataBase(){
File databaseFile = new File(DB_PATH + DATABASE_NAME);
return databaseFile.exists();
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transferring byte stream.
* */
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DATABASE_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the input file to the output file
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();
}
/**
* This method opens the data base connection.
* First it create the path up till data base of the device.
* Then create connection with data base.
*/
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/**
* This Method is used to close the data base connection.
*/
#Override
public synchronized void close() {
if(sqliteDataBase != null)
sqliteDataBase.close();
super.close();
}
/**
* Apply your methods and class to fetch data using raw or queries on data base using
* following demo example code as:
*/
public String getUserNameFromDB(){
String query = "select User_First_Name From "+TABLE_USER_DETAILS;
Cursor cursor = sqliteDataBase.rawQuery(query, null);
String userName = null;
if(cursor.getCount()>0){
if(cursor.moveToFirst()){
do{
userName = cursor.getString(0);
}while (cursor.moveToNext());
}
}
return userName;
}
#Override
public void onCreate(SQLiteDatabase db) {
// No need to write the create table query.
// As we are using Pre built data base.
// Which is ReadOnly.
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// No need to write the update table query.
// As we are using Pre built data base.
// Which is ReadOnly.
// We should not update it as requirements of application.
}
}
Hope this will help you...
I had trouble with the other DatabaseHelpers regarding this problem, not sure why.
This is what worked for me:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = DatabaseHelper.class.getSimpleName();
private final Context context;
private final String assetPath;
private final String dbPath;
public DatabaseHelper(Context context, String dbName, String assetPath)
throws IOException {
super(context, dbName, null, 1);
this.context = context;
this.assetPath = assetPath;
this.dbPath = "/data/data/"
+ context.getApplicationContext().getPackageName() + "/databases/"
+ dbName;
checkExists();
}
/**
* Checks if the database asset needs to be copied and if so copies it to the
* default location.
*
* #throws IOException
*/
private void checkExists() throws IOException {
Log.i(TAG, "checkExists()");
File dbFile = new File(dbPath);
if (!dbFile.exists()) {
Log.i(TAG, "creating database..");
dbFile.getParentFile().mkdirs();
copyStream(context.getAssets().open(assetPath), new FileOutputStream(
dbFile));
Log.i(TAG, assetPath + " has been copied to " + dbFile.getAbsolutePath());
}
}
private void copyStream(InputStream is, OutputStream os) throws IOException {
byte buf[] = new byte[1024];
int c = 0;
while (true) {
c = is.read(buf);
if (c == -1)
break;
os.write(buf, 0, c);
}
is.close();
os.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
If you already have a database, keep it in your asset folder and copy it in your application. For more detail, see Android database basics.
You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.

Database not copying from assets

Little to say ill just paste my code hoping that someone will see what im missing:
Database.Java
package gr.peos;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class Database extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "/data/data/gr.peos/databases/";
//Name of the Database to be created.
private static String DB_NAME = "BLib";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* #param context
*/
public Database(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() throws IOException{
//First we check if the database already exists, Method declared later
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exists
}else{
//By calling this method an empty database will be created into the default system path
//of your application so we are going to be able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase(); //Method declared later
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* #return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transferring byte stream.
* */
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(outFileName);
//transfer bytes from the inputfile to the 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();
}
//Opening the Database
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
/
//Finally overriding a few methods as required
#Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
The part to call this is on the onCreate method of my main activity (Tried others too it wasnt the problem).
Database myDbHelper = new Database(null);
myDbHelper = new Database(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
}catch(SQLException sqle){
throw sqle;
}
The weird part now. On my device (I dont have root access so cant extract the db after it's been created), my Data appears to be 48KB. When running the exact same code on the emulator the database isnt copied over (Im not picking on any exception). To be exact the android/metadata table seems to be getting copied but the other tables along with the data arent. Any ideas?
I am giving you the complete code,plz reply if you success
public class DataBaseHelper extends SQLiteOpenHelper{
private Context mycontext;
private String DB_PATH = "/data/data/gr.peos/databases/";
//private String DB_PATH = mycontext.getApplicationContext().getPackageName()+"/databases/";
private static String DB_NAME = "BLib.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/gr.peos/databases/BLib.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();
}
if your file name have extension in assets folder to must add in code.
like
private static String DB_NAME = "BLib.extension";
extension is like as ".sqlite",".db" ...etc

Categories