i have an app that has database inside the assets folder.
But i want to get the database from my sdcard not from the assets, as i'm new to this, i did these steps :
I downloaded the new DB and put it inside the custom folder.
I changed the DB_PATH from
DB_PATH = "/data/data/com.test.project/databases/";
to
DB_PATH = Environment.getExternalStorageDirectory() + "/my_custom_folder/";
but when i try to access it, the app crashes , and that DB got deleted from my phone, any help ?
Here is the code to load it :
public class book_DB_Helper extends SQLiteOpenHelper {
public final static int DB_VERSION = 1;
private final static String DB_NAME = "my_book";
public static SQLiteDatabase db;
//// --- the old PATH 'from assets folder
//private static String DB_PATH = "/data/data/com.test.project/databases/";
//// --- my new path in the sdcard
private static String DB_PATH = Environment.getExternalStorageDirectory() + "/my_folder/";
private final Context context;
private final String TABLE_NAME = "tbl_recipes";
private final String ID = "id";
private final String RECIPE_NAME = "recipe_name";
private final String IMAGE_PREVIEW = "image_preview";
private final String COOK_TIME = "cook_time";
public my_book_DB_Helper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
SQLiteDatabase db_Read = null;
if (dbExist) {
//do nothing - database already exist
deleteDataBase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
} else {
db_Read = this.getReadableDatabase();
db_Read.close();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void deleteDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
dbFile.delete();
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public void close() {
db.close();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public ArrayList<ArrayList<Object>> getAllData(String RecipeNameKeyword) {
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
Cursor cursor = null;
if (RecipeNameKeyword.equals("")) {
try {
cursor = db.query(
TABLE_NAME,
new String[]{ID, RECIPE_NAME, IMAGE_PREVIEW, COOK_TIME},
null, null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
cursor.close();
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
} else {
try {
cursor = db.query(
TABLE_NAME,
new String[]{ID, RECIPE_NAME, IMAGE_PREVIEW, COOK_TIME},
RECIPE_NAME + " LIKE '%" + RecipeNameKeyword + "%'",
null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataList.add(cursor.getString(3));
dataArrays.add(dataList);
}
while (cursor.moveToNext());
}
cursor.close();
} catch (SQLException e) {
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
return dataArrays;
}
public ArrayList<Object> getDetail(long id) {
ArrayList<Object> rowArray = new ArrayList<Object>();
Cursor cursor;
try {
String SUMMARY = "summary";
String PREP_TIME = "prepare_time";
String SERVES = "serves";
String INGREDIENTS = "ingredients";
String DIRECTIONS = "directions";
cursor = db.query(
TABLE_NAME,
new String[]{RECIPE_NAME, IMAGE_PREVIEW, COOK_TIME},
ID + "=" + id,
null, null, null, null, null);
cursor.moveToFirst();
if (!cursor.isAfterLast()) {
do {
rowArray.add(cursor.getString(0));
rowArray.add(cursor.getString(1));
rowArray.add(cursor.getString(2));
rowArray.add(cursor.getString(3));
rowArray.add(cursor.getString(4));
rowArray.add(cursor.getString(5));
rowArray.add(cursor.getString(6));
rowArray.add(cursor.getString(7));
}
while (cursor.moveToNext());
}
cursor.close();
} catch (SQLException e) {
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
return rowArray;
}
}
Related
I am developing an app that uses sqlite database, and I am storing them in the assets folder.
I need the files to have descriptive numbers(like db_42_2_43_3.sqlite) but they don't work, I understood that this limitation is present with the files inside the res/raw folder (file names without capital letters, without numbers greater than 9, etc) but these files are not there, They are in the assets folder.
Note: the app works with filenames without numbers greater than 9 (as if the file would be in the res/raw folder)
Any suggestion? This is my SqlLiteDbHelper class
public class SqlLiteDbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public String DATABASE_NAME;
private static final String DB_PATH_SUFFIX = "/databases/";
static Context ctx;
public SqlLiteDbHelper(Context context, String db_filename) {
super(context, db_filename, null, DATABASE_VERSION);
ctx = context;
DATABASE_NAME = db_filename;
}
public ArrayList<Poi> getDetails(double lat, double lng, double radius) {//radius in meters
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Poi> poiList = new ArrayList<>();
String query = "SELECT * FROM puentes";
Cursor cursor = db.rawQuery(query, null);
if (cursor != null) {
while (cursor.moveToNext()) {
Poi cont = new Poi(cursor.getLong(0), cursor.getLong(1), cursor.getDouble(2), cursor.getDouble(3), cursor.getString(4), cursor.getString(6));
poiList.add(cont);
}
cursor.close();
db.close();
}
return poiList;
}
public void CopyDataBaseFromAsset() throws IOException {
InputStream myInput = ctx.getAssets().open(DB_PATH_SUFFIX + DATABASE_NAME);
String outFileName = getDatabasePath();
File f = new File(ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
if (!f.exists())
f.mkdir();
OutputStream myOutput = new FileOutputStream(outFileName);
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();
}
private String getDatabasePath() {
return ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX + DATABASE_NAME;
}
public SQLiteDatabase openDataBase() throws SQLException {
File dbFile = ctx.getDatabasePath(DATABASE_NAME);
if (!dbFile.exists()) {
try {
CopyDataBaseFromAsset();
System.out.println("Copying sucess from Assets folder");
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.CREATE_IF_NECESSARY);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
I am trying to create a quiz app where a category can be selected by clicking on a listView item. Each category has code like 0,1,2. For football, it is 0. After clicking on the football item, the app keeps on going to the home screen instead of logging the data I want. Please help me with the error.
Quiz Category Selection Class
String quizCategory = intent.getStringExtra("QuizCategory");
//Deciding which database to Open and choose
switch (quizCategory) {
case "0":
Log.i("Category", "Football");
Football football = new Football(this);
football.createDatabase();
football.openDatabase();
football.getWritableDatabase();
long x=football.getRowCount();
break;
default:
Log.i("Message", "Error");
}
}
Football Class
public class Football extends SQLiteOpenHelper {
private static final String Database_path = "/data/data/com.google.quiz/databases/";
private static final String Database_name = "football.db";
private static Context context;
private static final int version = 1;
public SQLiteDatabase sqlite;
public Football(Context context) {
super(context, Database_name, null, version);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
}
public void createDatabase() {
createDB();
}
private void createDB() {
boolean dbexist = DBexists();
if (!dbexist) {
this.getReadableDatabase();
copyDBfromResource();
}
}
private void copyDBfromResource() {
InputStream is;
OutputStream os;
String filePath = Database_path + Database_name;
try {
is = context.getAssets().open(Database_name);//reading purpose
os = new FileOutputStream(filePath);//writing purpose
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);//writing to file
}
os.flush();//flush the outputstream
is.close();//close the inputstream
os.close();//close the outputstream
} catch (IOException e) {
throw new Error("Problem copying database file:");
}
}
public void openDatabase() throws SQLException {
String myPath = Database_path + Database_name;
sqlite = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
private boolean DBexists() {
SQLiteDatabase db = null;
try {
String databasePath = Database_path + Database_name;
db = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
db.setLocale(Locale.getDefault());
db.setVersion(1);
db.setLockingEnabled(true);
} catch (SQLException e) {
Log.e("Sqlite", "Database not found");
}
if (db != null)
db.close();///close the opened file
return db != null ? true : false;
}
public long getRowCount() {
SQLiteDatabase db = this.getReadableDatabase();
long x = DatabaseUtils.queryNumEntries(db, "football");
db.close();
return x;
}
}
I'm extending DaoMaster.OpenHelper to manage assets folder database. Since it's not user related data the changes can be huge the only one thing I want to achieve is delete and recreate the database when there is a new version. What I don't understand is that this code works when i'm debugging my app on the emulator or even if i generate the apk and install it on my device manually. But when I deploy my app on the market and I install it on my device from there it looks like the it can't find the database.
Exception java.lang.RuntimeException: Unable to resume activity {com.livos.companionplants/com.livos.companionplants.main.MainActivity}: android.database.sqlite.SQLiteException: no such column: T.definition (code 1): , while compiling: SELECT T."_id",T."plant_id",T."definition" FROM "plant_definition" T ################################################################# Error Code : 1 (SQLITE_ERROR) Caused By : SQL(query) error or missing database. (no such column: T.definition (code 1): , while compiling: SELECT T."_id",T."plant_id",T."definition" FROM "plant_definition" T) #################################################################
#ApplicationScope
public class DatabaseOpenHelper extends DaoMaster.OpenHelper {
private String TAG = DatabaseOpenHelper.class.getSimpleName();
private static final String SP_KEY_DB_VER = "db_ver";
private static final int DATABASE_VERSION = 1;
private Context context;
private SharedPreferences sharedPreferences;
private SQLiteDatabase sqliteDatabase;
private static String DB_PATH;
private static String DB_NAME;
public DatabaseOpenHelper(Context context, SharedPreferences sharedPreferences, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
this.context = context;
this.sharedPreferences = sharedPreferences;
DB_NAME = name;
DB_PATH = context.getFilesDir().getAbsolutePath().replace("files", "databases") + File.separator;
try {
createDataBase();
} catch (Exception ioe) {
throw new Error("Unable to create database");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
/** Open Database for Use */
public void openDatabase() {
String databasePath = DB_PATH + DB_NAME;
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
(SQLiteDatabase.OPEN_READWRITE));
}
/** Close Database after use */
#Override
public synchronized void close() {
if ((sqliteDatabase != null) && sqliteDatabase.isOpen()) {
sqliteDatabase.close();
}
super.close();
}
/** Get database instance for use */
public SQLiteDatabase getSqliteDatabase() {
return sqliteDatabase;
}
/** Create new database if not present */
public void createDataBase() {
SQLiteDatabase sqliteDatabase;
if (databaseExists()) {
int dbVersion = sharedPreferences.getInt(SP_KEY_DB_VER, 1);
// If different version then delete current database and copy the new one from assets
if (DATABASE_VERSION != dbVersion) {
File dbFile = context.getDatabasePath(DB_NAME);
boolean dbFileDeleted = dbFile.delete();
if (!dbFileDeleted) {
Log.w(TAG, "Unable to update database");
} else {
createDataBase();
}
}
/* Check for Upgrade */
} else {
/* Database does not exists create blank database */
sqliteDatabase = this.getReadableDatabase();
sqliteDatabase.close();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(SP_KEY_DB_VER, DATABASE_VERSION);
editor.apply();
copyDataBase();
}
}
/** Check Database if it exists */
private boolean databaseExists() {
SQLiteDatabase sqliteDatabase = null;
try {
String databasePath = DB_PATH + DB_NAME;
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
e.printStackTrace();
}
if (sqliteDatabase != null) {
sqliteDatabase.close();
}
return sqliteDatabase != null;
}
/**
* Copy existing database file in system
*/
public void copyDataBase() {
int length;
byte[] buffer = new byte[1024];
String databasePath = DB_PATH + DB_NAME;
try {
InputStream databaseInputFile = this.context.getAssets().open(DB_NAME);
OutputStream databaseOutputFile = new FileOutputStream(databasePath);
while ((length = databaseInputFile.read(buffer)) > 0) {
databaseOutputFile.write(buffer, 0, length);
databaseOutputFile.flush();
}
databaseInputFile.close();
databaseOutputFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean isRoboUnitTest() {
return "robolectric".equals(Build.FINGERPRINT);
}
Solution using Kuffs proposition
#ApplicationScope
public class DatabaseOpenHelper extends DaoMaster.OpenHelper {
private String TAG = DatabaseOpenHelper.class.getSimpleName();
private static final String SP_KEY_DB_VER = "db_ver";
private static final int DATABASE_VERSION = 2;
private Context context;
private SharedPreferences sharedPreferences;
private SQLiteDatabase sqliteDatabase;
private static String DB_PATH;
private static String DB_NAME;
public DatabaseOpenHelper(Context context, SharedPreferences sharedPreferences, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
this.context = context;
this.sharedPreferences = sharedPreferences;
DB_NAME = name;
try {
createDataBase();
} catch (Exception ioe) {
throw new Error("Unable to create database");
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
/** Open Database for Use */
public void openDatabase() {
String databasePath = context.getDatabasePath(DB_NAME).toString();
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
(SQLiteDatabase.OPEN_READWRITE));
}
/** Close Database after use */
#Override
public synchronized void close() {
if ((sqliteDatabase != null) && sqliteDatabase.isOpen()) {
sqliteDatabase.close();
}
super.close();
}
/** Get database instance for use */
public SQLiteDatabase getSqliteDatabase() {
return sqliteDatabase;
}
/** Create new database if not present */
public void createDataBase() {
SQLiteDatabase sqliteDatabase;
if (databaseExists()) {
int dbVersion = sharedPreferences.getInt(SP_KEY_DB_VER, 1);
/* If different version then delete current database and copy the new one from assets*/
if (DATABASE_VERSION != dbVersion) {
File dbFile = context.getDatabasePath(DB_NAME);
boolean dbFileDeleted = dbFile.delete();
if (!dbFileDeleted) {
Log.w(TAG, "Unable to update database");
} else {
createDataBase();
}
}
} else {
/* Database does not exists create blank database */
sqliteDatabase = this.getReadableDatabase();
sqliteDatabase.close();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(SP_KEY_DB_VER, DATABASE_VERSION);
editor.apply();
copyDataBase();
}
}
/** Check Database if it exists */
private boolean databaseExists() {
SQLiteDatabase sqliteDatabase = null;
try {
String databasePath = context.getDatabasePath(DB_NAME).toString();
sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
e.printStackTrace();
}
if (sqliteDatabase != null) {
sqliteDatabase.close();
}
return sqliteDatabase != null;
}
/**
* Copy existing database file in system
*/
public void copyDataBase() {
int length;
byte[] buffer = new byte[1024];
String databasePath = context.getDatabasePath(DB_NAME).toString();
try {
InputStream databaseInputFile = this.context.getAssets().open(DB_NAME);
OutputStream databaseOutputFile = new FileOutputStream(databasePath);
while ((length = databaseInputFile.read(buffer)) > 0) {
databaseOutputFile.write(buffer, 0, length);
databaseOutputFile.flush();
}
databaseInputFile.close();
databaseOutputFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
yoh...
I was trying to retrieve data from my external database in assets
but when I run the app, seems like it created another database in /data/data/packagename/databases/ :-( not the external database from assets I inserted and causing an error(Unfortunately, App has stopped). Here's my Code:
ingameinterface .java*
public class ingameinterface extends Activity {
DBHelper dbhelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingameinterface);
String[] from = new String[] { "CtrlNo", "Prima", "Key_Word", "Val" };
int[] to = new int[] { R.id.itmCc1, R.id.itmCc2, R.id.itemCc3, R.id.itemCc4};
dbhelper = new DBHelper(this);
try {
dbhelper.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Cursor c = dbhelper.getData();
if (c.getCount() == 0) {
showmessage("Error!", "Nothing found.");
return;
}
StringBuffer buff = new StringBuffer();
while (c.moveToNext()) {
buff.append("Controlnum: " + c.getString(0) + "\n");
buff.append("Prima: " + c.getString(1) + "\n");
buff.append("Word: " + c.getString(2) + "\n");
buff.append("Value: " + c.getString(3) + "\n\n");
}
showmessage("Data", buff.toString());
}
public void showmessage(String title, String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
}
}
and
DBHelper.Java*
public class DBHelper extends SQLiteOpenHelper {
private static String DB_NAME = "db_vocabulary";
private SQLiteDatabase db;
private final Context context;
private String DB_PATH;
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
// throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
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 Cursor getData() {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
Cursor c = db.rawQuery("SELECT * FROM TblWords WHERE Prima = 1", null);
return c;
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
use this in your DBHelper.java file:
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists "+TABLE_NAME+"(PHONENUMBER VARCHAR,NAME VARCHAR)");
}
so that it will wont create another table if already that table exits in database.
here is my problem. I am creating my database of text in program called SqliteDbBrowser after that I want to put it into /assets/ folder in android and load it to the application.
All the tutorials assume that you don't have any database and you create it clean from application and then fill it.
I have already put data into my database and don't want to create new one.
Here is some guy's tutorial http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ and it somehow work's but it's not perfect, is it any other way to solve this ? Using ony SQLiteOpenHelper not mixing stuff?
public void getDataBaseData() {
// /PawnStorescopy.db
if (!new File("/data/data/" + this.getPackageName()
+ "/PawnStorescopy.sqlite").exists()) {
try {
FileOutputStream out = new FileOutputStream("data/data/"
+ this.getPackageName() + "DatabaseName.sqlite");
InputStream in = getAssets().open("DatabaseName.db");
byte[] buffer = new byte[1024];
int readBytes = 0;
while ((readBytes = in.read(buffer)) != -1)
out.write(buffer, 0, readBytes);
in.close();
// out.close();
} catch (IOException e) {
}
}
SQLiteDatabase sqliteDB = SQLiteDatabase.openOrCreateDatabase(
"/data/data/" + this.getPackageName()
+ "/DatabaseName.sqlite", null);
Cursor cursor = sqliteDB.rawQuery("SELECT * FROM TableName", null);
if (cursor.moveToFirst()) {
do {
////Get Data
} while (cursor.moveToNext());
imageFilter(listDatabase);
}
}
I don't see the problem. I used that same example and it worked.
In my project I had to check and, eventually, load the missing tables on the internal DB.
The DB will not be erased, unless you state so.
Therefore adding new tables will not erase any pre-existing ones.
Anyway, you said 'it somehow work's but it's not perfect', what do you mean? It either copies the tables or it doesn't. Right?
The example you provided a link for works well, but the best practice is to build your database within your android application, so you can export the ready database DLL with the data as insert statements, add those insert statements in a file let say under your raw folder and after creating the DB you can read the insert statements and execute them to have your data inserted.
First Put your Created Database in your Asset Folder.
Add Below Java File to your Project
package com.app.ourforms.database;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Vector;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBConnect extends SQLiteOpenHelper {
ArrayList<String> arraylistUrl;
public int GetCursor;
public DBConnect(Context context, String db_name) {
super(context, db_name, null, 2);
if (db != null && db.isOpen())
close();
this.myContext = context;
DB_NAME = db_name;
try {
createDataBase();
openDataBase();
} catch (IOException e) {
// System.out.println("Exception in creation of database : "+
// e.getMessage());
e.printStackTrace();
}
}
public void createDataBase() throws IOException {
// boolean dbExist = checkDataBase();
boolean dbExist = databaseExist();
if (dbExist) {
// System.out.println("Database Exist");
} else {
this.getReadableDatabase();
try {
copyDatabase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private void copyDatabase() throws IOException {
InputStream input = myContext.getAssets().open(DB_NAME);
String outputFileName = DB_PATH + DB_NAME;
OutputStream output = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
input.close();
// System.out.println(DB_NAME + "Database Copied !");
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
public boolean isOpen() {
if (db != null)
return db.isOpen();
return false;
}
#Override
public synchronized void close() {
if (db != null)
db.close();
super.close();
}
public boolean databaseExist() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
// System.out.println("My Pathe is:- " + myPath);
// System.out.println("Open");
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
// System.out.println("checkDB value:" + checkDB);
// System.out.println("My Pathe is:- " + myPath);
} catch (Exception e) {
// database does't exist yet.
}
if (checkDB != null) {
// System.out.println("Closed");
checkDB.close();
// System.out.println("My db is:- " + checkDB.isOpen());
}
return checkDB != null ? true : false;
}
public Cursor execCursorQuery(String sql) {
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, null);
GetCursor = cursor.getCount();
Log.i("Inside execCursorQuery try", sql);
} catch (Exception e) {
Log.i("Inside execCursorQuery exception", e.getMessage());
}
return cursor;
}
public void execNonQuery(String sql) {
try {
db.execSQL(sql);
// Log.d("SQL", sql);
} catch (Exception e) {
// Log.e("Err", e.getMessage());
} finally {
// closeDb();
}
}
// ****************** Declare all the global variable
// ****************************//
private Context myContext;
public String DB_PATH = "data/data/com.app.ourforms/databases/"; // path
// of
// your
// datbase
public static String DB_NAME = "OurForms.sqlite";// your database
// name
#SuppressWarnings("unused")
private static String ASSETS_DB_FOLDER = "db";
private SQLiteDatabase db;
public Vector<ArrayList<String>> getQuestion(String Query) {
Vector<ArrayList<String>> alldata = new Vector<ArrayList<String>>();
ArrayList<String> Question = new ArrayList<String>();
ArrayList<String> Option1 = new ArrayList<String>();
ArrayList<String> Option2 = new ArrayList<String>();
ArrayList<String> Option3 = new ArrayList<String>();
ArrayList<String> Option4 = new ArrayList<String>();
ArrayList<String> Option5 = new ArrayList<String>();
ArrayList<String> correct = new ArrayList<String>();
ArrayList<String> correctness = new ArrayList<String>();
ArrayList<String> Description = new ArrayList<String>();
Cursor alldata_ques = execCursorQuery(Query);
// GetCursor = alldata_ques.getCount();
if (alldata_ques != null) {
Log.e("Cursor length", "" + alldata_ques.getCount());
GetCursor = alldata_ques.getCount();
if (alldata_ques.getCount() > 0)
while (alldata_ques.moveToNext()) {
Question.add((alldata_ques.getString(alldata_ques
.getColumnIndex("Question"))));
Option1.add(alldata_ques.getString(alldata_ques
.getColumnIndex("A")));
Option2.add(alldata_ques.getString(alldata_ques
.getColumnIndex("B")));
Option3.add(alldata_ques.getString(alldata_ques
.getColumnIndex("C")));
Option4.add(alldata_ques.getString(alldata_ques
.getColumnIndex("D")));
Option5.add(alldata_ques.getString(alldata_ques
.getColumnIndex("E")));
correct.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Answer")));
correctness.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Correctness")));
Description.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Description")));
}
alldata.add(Question);
alldata.add(Option1);
alldata.add(Option2);
alldata.add(Option3);
alldata.add(Option4);
alldata.add(Option5);
alldata.add(correct);
alldata.add(correctness);
alldata.add(Description);
// Log.d("VECTORSIZE", String.valueOf(alldata.size()));
}
return alldata;
}
public Vector<ArrayList<String>> getQuestions(String Query) {
Vector<ArrayList<String>> alldata = new Vector<ArrayList<String>>();
ArrayList<String> Question = new ArrayList<String>();
ArrayList<String> Option1 = new ArrayList<String>();
ArrayList<String> Option2 = new ArrayList<String>();
ArrayList<String> Option3 = new ArrayList<String>();
ArrayList<String> Option4 = new ArrayList<String>();
ArrayList<String> Option5 = new ArrayList<String>();
ArrayList<String> correct = new ArrayList<String>();
ArrayList<String> Description = new ArrayList<String>();
Cursor alldata_ques = execCursorQuery(Query);
if (alldata_ques != null) {
Log.e("Cursor length", "" + alldata_ques.getCount());
if (alldata_ques.getCount() > 0)
GetCursor = alldata_ques.getCount();
while (alldata_ques.moveToNext()) {
Question.add((alldata_ques.getString(alldata_ques
.getColumnIndex("Question"))));
Option1.add(alldata_ques.getString(alldata_ques
.getColumnIndex("A")));
Option2.add(alldata_ques.getString(alldata_ques
.getColumnIndex("B")));
Option3.add(alldata_ques.getString(alldata_ques
.getColumnIndex("C")));
Option4.add(alldata_ques.getString(alldata_ques
.getColumnIndex("D")));
Option5.add(alldata_ques.getString(alldata_ques
.getColumnIndex("E")));
correct.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Answer")));
Description.add(alldata_ques.getString(alldata_ques
.getColumnIndex("Description")));
}
alldata.add(Question);
alldata.add(Option1);
alldata.add(Option2);
alldata.add(Option3);
alldata.add(Option4);
alldata.add(Option5);
alldata.add(correct);
alldata.add(Description);
// Log.d("VECTORSIZE", String.valueOf(alldata.size()));
}
return alldata;
}
}
In Above Code Change below line as per your project:
public String DB_PATH = "data/data/YOUR_PACKAGE_NAME/databases/"; // path of your datbase
public static String DB_NAME = "OurForms.sqlite";// your database Name
Inside your Activity Write Below Code For First Time Copy your Database to Application.
// For Database Copy
myPrefs = getSharedPreferences("myPrefs", 0);
// sharedPreferences = PreferenceManager
// .getDefaultSharedPreferences(getApplicationContext());
Data.FIRST_TIME_LAUNCH = myPrefs.getBoolean("FIRST_TIME_LAUNCH", true);
if (Data.FIRST_TIME_LAUNCH) {
Log.i(TAG, "FIRST TIME*************************");
dbConnect = new DBConnect(getApplicationContext(),
"OurForms.sqlite");
SharedPreferences.Editor editor = myPrefs.edit();
editor.putBoolean("FIRST_TIME_LAUNCH", false);
editor.commit();
}
Hope it will help you.
Follow this link:
https://github.com/jgilfelt/android-sqlite-asset-helper
Then,
Add your yourSqliteDb.db to folder in assets/databases. Create the folders if not present.
assets/databases/yourSqliteDb.db
How to create asset folder:
http://code2care.org/2015/create-assets-folder-in-android-studio/
Create SQLiteAssetHelper Class as:
public class MyDatabaseHelper extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "yourSqliteDb.db";
private static final int DATABASE_VERSION = 1;
public MyDatabase(Context mContext)
{
super(mContext, DATABASE_NAME, null, DATABASE_VERSION );
}
public Cursor getItems()
{
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery("Select * from items", null);
//items is a column name in your table in database
c.moveToFirst();
return c;
}
}
Now in MainActivity or wherever you need to read data from database,
MyDatabaseHelper myDbHelper = new MyDatabaseHelper(this);
SQLiteDatabase db = myDbHelper.ReadableDatabase();
String items = getResult(1); //number value from database table
public String getResult(int id)
{
String name = null;
try
{
Cursor c = null;
c = db.rawQuery("select item from items where _id="+id, null);
c.moveToFirst();
name = c.getString(c.getColumnIndex("item"));
c.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return name;
}