In my Android application I created a database using sqlite browser and cpoied it into asset folder. then I created a table named EMPerson.
I need to add user defined data(user can insert details such as personName,date_of_birth,age,gender & bloodGrp) into this EMPerson table when the user click save button.
My DBHelper class is like this.
package my.easymedi.db;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import my.easymedi.entity.Person;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
public class DBHelper extends SQLiteOpenHelper {
/*Database attributes - the Android's default system path for your application database*/
private static final String pkg = "my.easymedi.controller";
private static String DB_PATH = "/data/data/" + pkg + "/databases/";
private static String DB_NAME = "EasyMediInfo.jpeg";
private static final int DB_VERSION = 1;
private final Context myContext;
private SQLiteDatabase myDatabase;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.myContext = context;
}
public void createDataBase() {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Toast.makeText(myContext, e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("CREATE_DB", e.getMessage());
}
}
}
private void copyDataBase() throws IOException {
InputStream databaseInput = null;
String outFileName = DB_PATH + DB_NAME; //path to copy the database
OutputStream databaseOutput = new FileOutputStream(outFileName); //open the empty db as an output stream
databaseInput = myContext.getAssets().open(DB_NAME);
byte[] buffer = new byte[512];
int length = databaseInput.read(buffer);
while(length > 0){
databaseOutput.write(buffer, 0, length);
databaseOutput.flush();
}
databaseOutput.flush();
databaseInput.close();
databaseOutput.close();
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
} catch (SQLiteException e) {
Toast.makeText(myContext, e.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("Check_DB", e.getMessage());
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public void openDatabase() {
String myPath = DB_PATH + DB_NAME;
myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}
public void closeDatabase() {
if(myDatabase != null){
myDatabase.close();
}
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public boolean insertIntoDatabase(Person person) {
String query = "INSERT INTO EMPerson (COLUMN_PERSON_NAME, COLUMN_DOB , COLUMN_AGE, COLUMN_GENDER, COLUMN_BLOODGRP) "
+ " VALUES ('" + person.getName() + "', '" + person.getDate_of_birth() + "', '" + person.getAge() + "', '" + person.getGender() + "', '" + person.getBloodGrp() + "')";
try {
myDatabase.execSQL(query);
return true;
} catch (Exception e) {
return false;
}
}
}
And this is my AddNewPerson class segment.
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnSave:
personName = etName.getText().toString();
date_of_birth = tvDOB.getText().toString();
age = tvAge.getText().toString();
int selected_rb_ID = genderGrp.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) findViewById(selected_rb_ID);
gender = rb.getText().toString();
bloodGrp = spiBloodGrp.getSelectedItem().toString();
Person person = new Person();
person.setName(personName);
person.setDate_of_birth(date_of_birth);
person.setAge(age);
person.setGender(gender);
person.setBloodGrp(bloodGrp);
//personArrayList.add(person);
DBHelper dbHelper = new DBHelper(this);
dbHelper.createDataBase();
dbHelper.openDatabase();
//SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
boolean flag = dbHelper.insertIntoDatabase(person);
//long affectedColumnId = sqliteDatabase.insert(AndroidOpenDbHelper.TABLE_NAME_GPA, null, contentValues);
if(flag){
Toast.makeText(getApplicationContext(), "Values inserted", Toast.LENGTH_SHORT).show();
}
dbHelper.closeDatabase();
break;
When I run the application log cat says 'no such table:EMPerson'
Can anyone plz explain what's wrong with these codes.
Thanx in advance
There seem to be two problems:
Change the extension of your database to ".db" from ".jpeg" (just a suggestion for good coding practice)
It seems you do not properly initialize "mydatabase" variable in your code:
The line:
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
should be calling this.openDatabase(...)
Similarly, when your database doesn't exist you copy the database but doesn't initialize mydatabase again (you should call openDatabase again)
Also, you can then modify the function openDatabase as
public boolean openDatabase() {
String myPath = DB_PATH + DB_NAME;
myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return myDatabase!= null ? true : false;
}
Change the DB_NAME to EasyMediInfo.db in Assets
B/coz the extension of Database file is .db
private static String DB_NAME = "EasyMediInfo.db";
Edited:-
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.myContext = context;
if (android.os.Build.VERSION.SDK_INT >= 4.2) {
DB_PATH = myContext.getApplicationInfo().dataDir
+ "/databases/";
} else {
DB_PATH = "/data/data/" + myContext.getPackageName()
+ "/databases/";
}
}
Related
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.
I have this problem with sqlite, i'm getting this warning:
A SQLiteConnection object for database '//data//data//com.compapps.booster//databases//booster.db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
And logcat is showing that continuously, even after closing the app:
Database already exists
So i think the programm perform execution even if the app is closed, here is the code of my class:
package com.compapps.booster.db;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.compapps.booster.model.AppInfo;
import com.compapps.booster.model.UsedAppInfo;
import com.compapps.booster.utill.Const;
public class ExternalDbOpenHelper extends SQLiteOpenHelper {
// Path to the device folder with databases
public static String DB_PATH;
// Database file name
public static String DB_NAME;
public SQLiteDatabase database;
public final Context context;
public SQLiteDatabase getDb() {
return database;
}
public ExternalDbOpenHelper(Context context, String databaseName,
int databaseVersion) {
super(context, databaseName, null, databaseVersion);
this.context = context;
// Write a full path to the databases of your application
String packageName = context.getPackageName();
DB_PATH = String.format("//data//data//%s//databases//", packageName);
DB_NAME = databaseName;
openDataBase();
}
// This piece of code will create a database if itï؟½s not yet created
public void createDataBase() {
boolean dbExist = checkDataBase();
if (!dbExist) {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
Log.e(this.getClass().toString(), "Copying error");
throw new Error("Error copying database!");
}
} else {
Log.i(this.getClass().toString(), "Database already exists");
}
}
// Performing a database existence check
private boolean checkDataBase() {
SQLiteDatabase checkDb = null;
try {
String path = DB_PATH + DB_NAME;
checkDb = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLException e) {
Log.e(this.getClass().toString(), "Error while checking db");
}
// Android doesnt like resource leaks, everything should
// be closed
if (checkDb != null) {
checkDb.close();
}
return checkDb != null;
}
// Method for copying the database
private void copyDataBase() throws IOException {
// Open a stream for reading from our ready-made database
// The stream source is located in the assets
InputStream externalDbStream = context.getAssets().open(DB_NAME);
// Path to the created empty database on your Android device
String outFileName = DB_PATH + DB_NAME;
// Now create a stream for writing the database byte by byte
OutputStream localDbStream = new FileOutputStream(outFileName);
// Copying the database
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = externalDbStream.read(buffer)) > 0) {
localDbStream.write(buffer, 0, bytesRead);
}
// Dont forget to close the streams
localDbStream.close();
externalDbStream.close();
}
public SQLiteDatabase openDataBase() throws SQLException {
String path = DB_PATH + DB_NAME;
if (database == null) {
createDataBase();
}
database = SQLiteDatabase.openDatabase(path, null,
SQLiteDatabase.OPEN_READWRITE);
return database;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertAutoKillApps(final ArrayList<AppInfo> listAutoKillApps) {
for (int i = 0; i < listAutoKillApps.size(); i++) {
if (listAutoKillApps.get(i).isChecked()) {
AppInfo info = listAutoKillApps.get(i);
ContentValues values = new ContentValues();
values.put(Const.TblAutoKillColumn.APP_NAME, info.getAppName());
values.put(Const.TblAutoKillColumn.PACKAGE_NAME,
info.getPkgName());
values.put(Const.TblAutoKillColumn.PROCESS_ID,
info.getProcessId());
int id = (int) database.insert(Const.TABLE_AUTO_KILL, null,
values);
}
}
}
public int insertAutoKillApp(AppInfo info) {
ContentValues values = new ContentValues();
values.put(Const.TblAutoKillColumn.APP_NAME, info.getAppName());
values.put(Const.TblAutoKillColumn.PACKAGE_NAME, info.getPkgName());
// values.put(Const.TblAutoKillColumn.PROCESS_ID, info.getProcessId());
int id = (int) database.insert(Const.TABLE_AUTO_KILL, null, values);
return id;
}
public int insertAllAutoKillApp(ArrayList<AppInfo> list) {
int count = 0;
for (int i = 0; i < list.size(); i++) {
AppInfo info = list.get(i);
ContentValues values = new ContentValues();
values.put(Const.TblAutoKillColumn.APP_NAME, info.getAppName());
values.put(Const.TblAutoKillColumn.PACKAGE_NAME, info.getPkgName());
// values.put(Const.TblAutoKillColumn.PROCESS_ID,
// info.getProcessId());
int id = (int) database.insert(Const.TABLE_AUTO_KILL, null, values);
if (id != -1) {
count += 1;
}
}
System.out.println("Total app kill inserted " + count);
return count;
}
public boolean deleteAutoKillApp(AppInfo info) {
int row = database.delete(Const.TABLE_AUTO_KILL,
Const.TblAutoKillColumn.PACKAGE_NAME + " = ?",
new String[] { info.getPkgName() });
if (row != 0) {
return true;
}
return false;
}
public int deleteAllAutoKillApp(ArrayList<AppInfo> list) {
int count = 0;
for (int i = 0; i < list.size(); i++) {
AppInfo info = list.get(i);
int row = database.delete(Const.TABLE_AUTO_KILL,
Const.TblAutoKillColumn.PACKAGE_NAME + " = ?",
new String[] { info.getPkgName() });
if (row != 0) {
count += 1;
}
}
System.out.println("Total app kill deleted " + count);
return count;
}
public ArrayList<AppInfo> getAutoKillApps() {
ArrayList<AppInfo> appList = new ArrayList<AppInfo>();
String selectQuery = "SELECT * FROM " + Const.TABLE_AUTO_KILL;
Cursor cursor = database.rawQuery(selectQuery, null);
try {
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
AppInfo info = new AppInfo();
info.setAppName(cursor.getString(0));
info.setPkgName(cursor.getString(1));
// info.setProcessId(cursor.getInt(2));
appList.add(info);
} while (cursor.moveToNext());
}
}
return appList;
} catch (Exception e) {
Log.d("Error in getting app auto kill from DB", e.getMessage());
return appList;
}
finally{
cursor.close();
}
}
public int insertUsedAppInfo(UsedAppInfo uAppInfo, boolean isUpdate) {
int id = 0;
if (isUpdate) {
ContentValues values = new ContentValues();
values.put(Const.TblAppUsedColumn.OPEN_COUNTER,
uAppInfo.getCounter());
values.put(Const.TblAppUsedColumn.OPEN_TIME, uAppInfo.getTime());
String[] args = new String[] { uAppInfo.getPackage_name() };
id = (int) database.update(Const.TABLE_APP_USED_DETAIL, values,
Const.TblAppUsedColumn.PACKAGE_NAME + "=?", args);
} else {
ContentValues values = new ContentValues();
values.put(Const.TblAppUsedColumn.PACKAGE_NAME,
uAppInfo.getPackage_name());
values.put(Const.TblAppUsedColumn.OPEN_COUNTER,
uAppInfo.getCounter());
values.put(Const.TblAppUsedColumn.OPEN_TIME, uAppInfo.getTime());
id = (int) database.insert(Const.TABLE_APP_USED_DETAIL, null,
values);
}
return id;
}
public UsedAppInfo gettUsedAppInfo(String packageName) {
UsedAppInfo uAppInfo = null;
String selectQuery = "SELECT * FROM " + Const.TABLE_APP_USED_DETAIL
+ " WHERE " + Const.TblAppUsedColumn.PACKAGE_NAME + " = "
+ "\"" + packageName + "\"";
System.out.println("Query coding: " + selectQuery);
try {
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
uAppInfo = new UsedAppInfo();
uAppInfo.setPackage_name(cursor.getString(0));
uAppInfo.setCounter(cursor.getInt(1));
uAppInfo.setTime(cursor.getString(2));
}
cursor.close();
}
return uAppInfo;
} catch (Exception e) {
Log.d("Error in getting app info from db", e.getMessage());
return null;
}
}
#Override
public synchronized void close() {
if (database != null) {
database.close();
}
super.close();
}
}
Can I have help please, thanks!
I'm using a premade database and I seem to be getting an error when I try to update a row. The exact error from logcat is: (1) no such table: AUD. Heres what my dbhelper class looks like:
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 = "/data/data/com.example.simplecurrency3/databases/";
private static String DB_NAME ="Currencies";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 2);// 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();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
And when I try to update a row:
Context context = getActivity().getApplicationContext();
DataBaseHelper dbHelper = new DataBaseHelper(context);
dbHelper.openDataBase();
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("UPDATE AUD SET AUD = 2.0")
You have never called createDataBase() method! You can put it into onCreate() method.
Good luck
Instead of updating a row, first check whether the table really exists by using the following query.
SELECT name FROM sqlite_master WHERE type='table'
I'm trying to understand how the connectivity works. I'm required to have a database in the assets folder(which I already built).I got an entire class adapter, was told to implement it in my code and start using it, but I'm not sure how to 'import' it. My main class is 'MainActivity', I tried DBAdapter adapter = new DBAdapter(); but that didn't work.
Here's the adapter class:
package com.example.movieass;
import android.content.ContentValues;
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 DBAdapter {
public static final String KEY_ID = "m_id";
public static final String KEY_TITLE = "m_title";
public static final String KEY_DESCRIPTION = "m_description";
public static final String KEY_RATING = "m_rating";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "database";
private static final String DATABASE_TABLE = "films";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"CREATE TABLE trailer (m_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"m_title TEXT NOT NULL, m_description TEXT NOT NULL, m_rating REAL NOT NULL);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL("DROP TABLE IF EXISTS trailer");
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS trailer");
onCreate(db);
}
} //end DatabaseHelper class
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertTrailer(String title, String description, String filename, double rating)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_DESCRIPTION, description);
initialValues.put(KEY_RATING, rating);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteTrailer(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null) > 0;
}
//---retrieves all the contacts---
public Cursor getAllTrailers()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_TITLE,
KEY_DESCRIPTION, KEY_RATING}, null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getTrailer(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ID,
KEY_TITLE, KEY_DESCRIPTION, KEY_RATING}, KEY_ID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
do{
Log.d("DBAdapter", "ID: " + mCursor.getString(mCursor.getColumnIndex("ID")));
}while (mCursor.moveToNext());
}
return mCursor;
}
//---updates a contact---
public boolean updateTrailer(long rowId, String title, String description, String filename, double rating)
{
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_DESCRIPTION, description);
args.put(KEY_RATING, rating);
return db.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
}
public boolean updateRating(long rowId, double rating)
{
ContentValues args = new ContentValues();
args.put(KEY_RATING, rating);
return db.update(DATABASE_TABLE, args, KEY_ID + "=" + rowId, null) > 0;
}
}
This is my working code to copy database.
private static String DB_PATH = "/data/data/com.demo.databaseDemo/databases/";
private static String DB_NAME = "myDatabase.db";
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();
}//end of copyDataBase() method
Also You can refer this for more details http://mobisys.in/blog/2012/01/tutorial-using-database-in-android-applications/
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;
}