Android SQLite Database Connection not succesfull - android

i encountered a little problem with my current project. I am doing an android application which needs to connect to a SQLite database to work through some statements. I believe the statements etc are fine, my only problem is the fact that the connection to the database is not succesfull.
LogCat Error:
04-18 08:20:30.688: E/Database(304): sqlite3_open_v2("jdbc:sqlite:res/raw/randomdb.db", &handle, 1, NULL) failed
So my code so far for connecting to the database is like this:
String url = "jdbc:sqlite:res/raw/randomdb.db";
SQLiteDatabase db;
db = SQLiteDatabase.openDatabase(url, null, SQLiteDatabase.OPEN_READONLY);
As you can see, i am trying to acces a database which is located in my project/res/raw folder. Does anyone see the mistake?
!!!UPDATE!!!
*I tried to go the way with SQLiteOpenHelper, but still encouner an error i cannot seem to solver. Here is my new code:*
public class DatabaseAdapter extends SQLiteOpenHelper {
private static String dbPath= "data/data/com.YourPackageName/applicationDb/";
private static String dbName = "YourDBName";
private SQLiteDatabase applicationDatabase;
private final Context applicationContext;
private boolean checkDataBase(){
File dbFile = new File( dbPath + dbName);
return dbFile.exists();
}
public void openDataBase() throws SQLException{
String fullDbPath= dbPath + dbName;
applicationDatabase = SQLiteDatabase.openDatabase( fullDbPath,null,SQLiteDatabase.OPEN_READONLY);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
I get this error:
Implicit super constructor SQLiteOpenHelper() is undefined for default constructor. Must define an explicit constructor
Any ideas? Would be great!

if you want to connect your android application with SQLite database then you need to extends SQLiteOpenHelper
public class AbcClass extends SQLiteOpenHelper
after that you need to Override these method:
onCreate and onUpgrade
and constructor of AbcClass looks like:
public AbcClass(Context context) {
super(context, DB_NAME, null, VERSION); //public static final String DB_NAME = "test.sqlite";
}

public boolean databaseExist()
{
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
This is the solution...
OR-----------------------
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;
}

I think the path you specify is not the correct one and so as mentioned in one of the other answers the database is not found. However I had never used the method openDatabase to read from the raw folder so I do not know which is the correct path.
However once upon a time I had shipped the database along with my application. It resided in the assets folder and once the application started I copied it in the private application storage (much like any database created with SqliteOpenHelper). From then on I used the usual way with SqliteOpenHelper to access the database.
Basically for this I followed the blog mentioned in this thread and because my database file was bigger than 1MB I used the technique described in this thread. Hopefully combining those two you will get your database running!
EDIT Btw you are wrong, openDatabase does not accept url, but path.

Related

android sqlite - table data cannot be updated

the table ( i.e. vaccines) structure is :
id- auto increment primary key
dose1_date - string
dose2_date - string
The DatabaseAccessor class is as follows. The initDB() and setVaccineDates methods are called from another activity. But the database is not updated. The logged message is found in the logcat however. The DatabaseHelper class is not shown here.
public class DatabaseAccessor {
public static DataBaseHelper myDbHelper = null;
public static SQLiteDatabase rdb = null;
public static SQLiteDatabase wdb = null;
public static synchronized final void initDB(Context context) throws Exception {
if (myDbHelper == null) {
myDbHelper = new DataBaseHelper(context);
myDbHelper.openDataBase();
rdb = myDbHelper.getReadableDatabase();
wdb = myDbHelper.getWritableDatabase();
}
}
public static void setVaccineDates(String birthDate) throws SQLException{
try {
String[] selections = null;
String qry = null;
qry = "select * from vaccines order by id";
Cursor cursor = wdb.rawQuery(qry, selections);
Log.d("update qry===== ", qry);
while (cursor.moveToNext()) {
int rowID = Integer.parseInt(cursor.getString(0));
ContentValues values = new ContentValues();
values.put("dose1_date","66666");
values.put("dose2_date","7777");
wdb.update("vaccines", values, "id=?", new String[] {String.valueOf(rowID)});
//wdb.close();
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}// end of method setVaccineDates
}
What to do ?
Edit : If I uncomment the wdb.close() line , I see in logcat
'06-09 04:21:05.387: W/System.err(4144): java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.cloudsoft.vaccine/databases/vaccines2.db
'
As a newbie in android it was just a mistake out of ignorance that this situation took place: after update operation I tried to find the changes in the database file (i.e. file with .db extension sitting inside assets folder in Eclipse) through sqlite browser . But what actually happens is the app running in the device (real one or emulator) has its own database which is created from the .db extension file inside assets folder and consequent database operations only affect the app's own database leaving no touch on the database inside the mentioned folder in Eclipse. And there is the way to watch the app's very own database in the running device in Eclipse's 'File Explorer' (in DDMS mode) with the help of Questoid SQlite Manager

Not able to open pre-installed database using Sqlite AssetHelper library

I am working on pre-installed database and using SqliteAssetHelper library for that.
This is my db code
public class DBController extends SQLiteAssetHelper {
private static final String DATABASE_NAME = "user.db";
private static final int DATABASE_VERSION = 1;
private final String TABLE_NAME = "User";
public DBController(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public ArrayList<UserData> getAllUserData() {
ArrayList<UserData> data_list = new ArrayList<>();
try {
// open database to query
SQLiteDatabase mySqliteDb = getWritableDatabase();
} catch (Exception e) {
Log.e("exception", "" + e);
}
close();
return data_list;
}
}
Error: Missing databases/user.db file (or .zip, .gz archive) in assets, or target folder not writable
and when I change my code to SQLiteDatabase mySqliteDb = getReadableDatabase(); I am getting android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database error.
I search for the problem and mostly everyon saying check your db present inside databases folder or not.
I tried using zip also still no luck. I guess I am missing something.
Your assets/ directory belongs inside main/, not inside app/.

SQLiteOpenHelper: onCreate() method not called on physical device

I have done many tests on an android emulator running in version 4.4.
On my app I create a sqlite database with one table using SQLiteOpenHelper:
package com.findwords.modeles;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import com.findwords.MainActivity;
import com.findwords.controleurs.MenuController;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by louk on 02/01/14.
*/
public class DictionaryDbHelper extends SQLiteOpenHelper{
// declare constants fields
private static final String DB_PATH = "/data/data/com.findwords/databases/";
private static final String DB_NAME = "dictionary_db";
private static final int DB_VERSION = 1;
// declared constant SQL Expression
private static final String DB_CREATE =
"CREATE TABLE dictionary ( " +
"_id integer PRIMARY KEY AUTOINCREMENT, " +
"word text NOT NULL, " +
"definition text NOT NULL, " +
"length integer NOT NULL " +
");";
private static final String DB_DESTROY =
"DROP TABLE IF EXISTS dictionnary";
/*
* constructor
*/
public DictionaryDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
* 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 = MenuController.getInstance().getMainActivity().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();
}
/*
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
try {
createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
* #see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DB_DESTROY);
onCreate(db);
}
}
Moreover I have written an adapter with a method open:
/*
* open database connection
*/
public DictionaryDbAdapter open() throws SQLException {
mDbHelper = new DictionaryDbHelper(mContext);
mDb = mDbHelper.getWritableDatabase();
return this;
}
It's working well on the emulator so the onCreate() method of the SQLiteOpenHelper class is called and create the database, but is not called on my phone (Google Nexus 5).
My phone is not rooted so I can't access the folder /data/data/com.myapp/databases .
However I want this application to work on any phone so I don't want to root my phone.
Thanks in advance to anyone who could help me.
Let i try to explain you some things.
In an application to connect to the database , we specify the name and version of the database . In this situation, the following may occur :
1) There is no database . This may be for example in the case of initial setting program. In this case, the application itself must create the database and all the tables in it. And further, it is already working with the newly created database.
2) Database exists, but its version is outdated. It may be the case update. For example a new version of the program need additional fields in the old tables or new tables . In this case, the application must update existing tables and create new ones if necessary.
3) There is a database and its actual version . In this case, the application successfully connects to the database and running.
As you know , the phrase " application must " tantamount to the phrase " the developer must ", ie it is our task . To handle the situations described above , we need to create a class that inherits for SQLiteOpenHelper. Call it DBHelper. This class will provide us with methods to create or update the database in case of their absence or obsolescence.
onCreate - a method that will be called if the database to which we want to connect - does not exist(it's your case)
The onCreate method is called only for the first time - when the DB is actually created. So if you uninstall your app and then install it again - it will get called, but if you install on top of the existing copy onCreate will not be called (since the DB already exists)
As #Asahi said, Database is only created only if you reinstall the app. But since you said that My phone is not rooted so I can't access the folder /data/data/com.myapp/databases, I want to point out that you can connect your mobile to the computer, install the correct USB drivers and use DDMS to see the file structure of your mobile phone. There you can see the database of your app along with the Shared Preferences and other files.
PS :- To see all the folder of real device on ddms you need root access. If your device is not rooted and you don't want to root your one then you can install the device on emulator which shows all folders in DDMS.

java.lang.illegalstateexception database not open android

When I am trying to insert to data base log cat shows an error like java.lang.illegalstateexception database not open android.
But I have opened the db using
db = SQLiteDatabase.openDatabase(DATABASE_PATH, null,
SQLiteDatabase.OPEN_READWRITE);
The error is not occurring frequently.Anybody know the reason for this?
Try it like this:
if (!db.isOpen()) {
db = getApplicationContext().openOrCreateDatabase(DATABASE_PATH, SQLiteDatabase.OPEN_READWRITE, null);
}
try
DatabaseHelper dataHelper;
SQLiteDatabase mDb;
public DbManager openDB() throws SQLException {
mDb = dataHelper.getWritableDatabase();
return this;
}
and call this method where your re writing your current code.
Try this code
public class DataBaseHelper extends SQLiteOpenHelper{
public SQLiteDatabase openDataBase() throws SQLException{
//Open the database
File dbFile = _myContext.getDatabasePath( DB_PATH + DB_NAME );
_myDataBase = SQLiteDatabase.openDatabase(dbFile.toString(), null, SQLiteDatabase.OPEN_READWRITE);
return _myDataBase;
}//end of openDataBase() method
}
maybe you are opening an opened Database. close your database every time your work is done.

How to check existing database before creating new database on android 2.2?

I need to check existing database before creating new database on android 2.2. How to check it?
use openOrCreateDatabase method
Read here
----- EDIT ------
public boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
}catch(SQLiteException e){
//database does't exist yet.
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
Doesn't it work with the DatabaseHelper ?
If you haven't tried here is code I posted before...
Android - Sqlite database method undefined fot type
You should need to check database already exists or not, if not than create database else not create database. Please you can use below query.
CREATE TABLE if not exists TABLE_NAME (key data_type);
Call this query inside onCreate method.
To check if your database was created you can use the following code and it will not be recreated every time you open the application.
dbName = is the name of you DB
public static boolean doesDatabaseExist(Context context, String dbName) {
File dbFile = context.getDatabasePath(dbName);
return dbFile.exists();
}

Categories

Resources