This is a sample class which will help you quickly copy your database from assets folder to the android device. Simply make a new class in your project named as DataBaseHelper
public class DataBaseHelper {
// The system path of your application database.
private static String DATABASE_PATH;
// Your database name
private static final String DATABASE_NAME = "kbc_t8.sqlite";
// Your database version
private static final int DATABASE_VERSION = 1;
// defining table name so that you don't have to change the table name
// everywhere if your table name
// changes. Just change it here
private static final String TABLE_NAME = "table";
// Columns
private static final String QUESTIONS_COLUMN_ID = "_id";
private static final String QUESTIONS_COLUMN_LEVEL = "level";
private static final String[] questions_columns =
{ QUESTIONS_COLUMN_ID, QUESTIONS_COLUMN_LEVEL,};
// to store the context of the class that is calling the database
private Context contextSql;
private SQLiteDatabase dbObj;
private SqliteOpenHelper helperObj;
//constructor of database class
DataBaseHelper(Context context) {
contextSql = context;
//making your path more adjustable so you don't have to change the package name it will take by default
DATABASE_PATH = "/data/data/" + context.getPackageName()
+ "/databases/";
}
public void open() throws SQLException
{
helperObj = new SqliteOpenHelper(contextSql);
dbObj = helperObj.getWritableDatabase();
}
public void close()
{
if (dbObj != null)
dbObj.close();
helperObj.close();
}
public class SqliteOpenHelper extends SQLiteOpenHelper {
public SqliteOpenHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
try
{
copyDataBase();
}
catch (IOException e)
{
// throw new Error("Error copying database");
Log.e("copy_db", "Error copying database");
}
}
//Copies your database from your local assets-folder to the empty database
private void copyDataBase() throws IOException {
// Open your db as input stream
InputStream inputStream = contextSql.getAssets().open(DATABASE_NAME);
// Path to new db
String outFileName = DATABASE_PATH + DATABASE_NAME;
// Open new db of device
OutputStream outputStream = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] data = new byte[1024];
int length;
while ((length = inputStream.read(data)) > 0) {
outputStream.write(data, 0, length);
}
// Close what you have opened
outputStream.flush();
outputStream.close();
inputStream.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUESTIONS);
onCreate(db);
}
}
No comments:
Post a Comment