Android Database not being created on install / android packages - android

I want to use a SQLite database within my application. I have created a class which extends SQLiteOpenHelper. When I first wrote the code the database appeared in /data/data/(package)/database. The package name was my reverse domain + /mobile/app. I then created a separate package within my project reverse domain + /mobile/data and moved my Database class into it.
/data/data/(original package)/database existed until I reloaded(to not use the snapshot) my emulator.
since then:
/data/data/(original package)/ is created but with no database directory, /data/data/(data package)/ is not created on the file system. I have tried:
moving my database class back to the original package
creating a new version of the emulator
uninstalling the app within the emulator and then re-installing it.
increasing the database version variable
commenting our code associated with the database class in other parts of my app.
Here is my db class code.
public class BusinessOpsDatabase extends SQLiteOpenHelper {
private static final String TAG = "BusinessOpsDatabase";
private static final int DB_VERSION = 1;
private static final String DB_NAME = "bss_business_ops";
// country table variables
public static final String TABLE_COUNTRY = "country";
public static final String ID = "_ID";
public static final String COL_COUNTRY_NAME = "country_name";
private static final String CREATE_TABLE_COUNTRY = "create table "
+ TABLE_COUNTRY + " (" + ID
+ " integer primary key autoincrement, " + COL_COUNTRY_NAME
+ " text not null);";
private static final String COUNTRY_SCHEMA = CREATE_TABLE_COUNTRY;
public BusinessOpsDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// create tables
db.execSQL(COUNTRY_SCHEMA);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// drop country
Log.w(TAG, "Upgrading database. Existing contents will be lost. ["
+ oldVersion + "]->[" + newVersion + "]");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_COUNTRY);
// create tables
onCreate(db);
}
}

http://www.techotopia.com/index.php/An_Android_SQLite_Database_Tutorial
Use above link to learn . you may solve all your problems regarding sqlite

I managed to resolve the problem by adding the following code to the database constructor.
SQLiteDatabase db = getWritableDatabase();

Related

How to make changes to the database without having to uninstall APK every time?

public class ProjectConstants {
public static final String myDbName = "ContactsDatabase.db";
public static final String myTableName = "ContactDetails";
// public static final String myTableName = "ContactDetails1";
public static final String nameColumn = "ContactName";
public static final String numberColumn = "ContactNumber";
}
First I create a contact application with Table Name : ContactDetails
Then I do all the adding, editing and deleting operations over that database table. Say I have 15 contact details in that database table named ContactDetails.
Now in the above code snippet I make 2 changes:
I comment this line
//public static final String myTableName = "ContactDetails";
And I uncomment this line
public static final String myTableName = "ContactDetails1";
Now if I run the code, the App crashes.
My learning from Stack Overflow has crudely taught me 2 things to ponder
1.
Remember to uninstall and then reinstall your app so the onCreate
method is called again and the database recreated.
2.
If the database is created for the first time, the onCreate method is
called in the helper class, otherwise onUpgrade is called.
My subclass that extends SQLiteOpenHelper class looks like this,
public class DBHelper extends SQLiteOpenHelper {
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQLCreateEntries =
"CREATE TABLE " + ProjectConstants.myTableName + " (" +
ProjectConstants.nameColumn + TEXT_TYPE + COMMA_SEP +
ProjectConstants.numberColumn + TEXT_TYPE + " )";
private static final String SQLDeleteEntries = "DROP TABLE IF EXISTS " + ProjectConstants.myTableName;
public DBHelper(Context context) {
super(context, String.valueOf(name), null, version);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQLCreateEntries);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(SQLDeleteEntries);
onCreate(sqLiteDatabase);
}
Now if I follow the instruction in the 1st quote block by uninstalling and reinstalling the application every time I mess with the database, the app never crashes.
But if I revert back to the original database,(then I do this uninstalling and reinstalling the application) obviously my data in the database do not exist anymore.
As mentioned above my Database table named "ContactDetails" which held 15 contacts will no more have that data now.
But I want that 15 contacts to stay intact inside my database Table "ContactDetails".
Is there anyway to make changes to the database without having to uninstalling-reinstalling apk and without losing the previous data ?
You have write SQL Commands and execute block of SQL commands with different version of code on OnUpgrade() of Helper class as follows:
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(SQLDeleteEntries);
onCreate(sqLiteDatabase);
switch(i){
case 1:
<commands for version 1>
break;
case 2:
<commands for version 2>
break;
}
You can write the swich cases as per version of applications. you can write different block of SQL commands as you want to execute on different version of applications.

In an Android app, where do new SQLite records get saved to in the filesystem?

I am trying to implement an Android application that uses SQLite as its data store. I am using ActiveAndroid. I have a model called Item, and I create items in the following way, calling this from the Activity's onCreate method:
Item item = new Item();
item.name = "test item";
item.save();
After launching my app, I then go to the Android Device Monitor to have access to the database files. And what I see are 2 databases in the filesystem of my app: Application.db and todoListDatabase:
Both of these databases contain a table called items, but only Application.db's version of the items table actually contains the new item records I created. Is that correct?
If this is correct, then what is the point of todoListDatabase?
Edit
Here are the relevant files I have:
My SQLite Helper class:
public class ItemDatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "todoListDatabase";
private static final String ITEMS = "items";
private static final String KEY_ID = "id";
private static final String KEY_BODY = "name";
public ItemDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TODO_TABLE = "CREATE TABLE " + ITEMS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_BODY + " TEXT" + ")";
db.execSQL(CREATE_TODO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion == 2) {
db.execSQL("DROP TABLE IF EXISTS " + ITEMS);
onCreate(db);
}
}
}
My Item class:
#Table (name = "Items")
public class Item extends Model {
#Column(name = "name")
public String name;
public Item() {
super();
}
public Item(String name){
super();
this.name = name;
}
}
There's just not enough information in this question, to allow it to be answered. SQLite Databases don't just appear. You have to create them. Typically, you do that with a SQLiteOpenHelper.
Unless you do something odd, your database will be in the directory:
/data/data/<your application's package name>/databases
For example, a database for the Google mail application might be:
/data/data/com.google.android.gm/databases/mail.db
Because I was using ActiveAndroid, creating a SQLiteOpenHelper was doing double work. That's why I was seeing 2 databases. To fix this, I deleted the ItemDatabaseHelper class. Then, when I go to the Android Device Monitor to see the database files, I see that Application.db is the only database there, and it has the items I created in it.

how to create database once only, then read and write multiple times from it, SQLite, OpenHelper, Android

I made two classes, the main class that extends Activity and the Database class that holds the database and it's methods. parts of the code from the database class are shown below.
the SQLiteOpenHelper class is a nested class inside the database class. I took it from an example I found on the internet. inside of this nested class is the method,
db.execSQL(SCRIPT_CREATE_DATABASE);
how do I create a new database? If I instantiate the Database class from the Main class like this:
Database db = new Database(this);
does that instantiation automatically instantiate the nested SQLiteOpenHelper class too? so i don't have to explicitly do that.
however for this example of how to create a database, i am confused. if every time I instantiate a new instance calling the addNewRow() method like this:
public void addNewRow(String label, int price){
Database db = new Database(context);
db.openToWrite();
db.insertNewRow(checkBoxStatus, label, price);
db.close();
}
then a new database is created on the "new Database(context)" call, and next I add the info to enter into the columns. and finally call db.close(), however every time i call the addNewRow method shown above, it will instantiate a new database and that also instantiates SQLiteOpenhelper class so a new database is created. that means the last database has been overwritten, and my last row added has been lost, is this correct?
how do i use this Database class to create a Database only once and then read and write things from it with multiple calls like this?
Database db = new Database(context);
db.openToWrite(); or db.openToRead();
// read or update or create new row in database
db.close();
the database class:
public class Database {
public static final String MYDATABASE_NAME = "my_database";
public static final String MYDATABASE_TABLE = "my_table";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_CHECKBOX_STATUS = "check_box_status";
public static final String KEY_CHECKBOX_LABEL = "check_box_label";
public static final String KEY_PRICE = "price";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"CREATE TABLE " + MYDATABASE_TABLE + " (" + "ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"KEY_CHECKBOX_STATUS INTEGER, " + "KEY_CHECKBOX_LABEL TEXT, " + " KEY_PRICE INTEGER" + ");";
SQLiteDatabase sqLiteDatabase;
SQLiteHelper sqLiteHelper;
Context context;
public Database(Context c){
context = c;
}
// after this all the rest of the methods for get and set of database values
code for the SQLiteOpenHelper class, nested inside of the Database Class:
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Yes, every time you instantiate a Database class a SQLiteHelper is instantiate. But the SQLiteHelper onCreate is only called if the database does not exist. You can test this by adding a new column to one of the table and then try to insert a row having value in this column then your app will crash. The error would be "no such column". You then need to clear your data or change the version of your database or uninstall your app to have your change table to be recreated.
Whenever you want to just open your database, you need to use this:
myDatabase = myOpenHelper.getWritableDatabase();
This won't create a new database. It would just return the instance of existing database on which you can do Read/Write operations.
Refer this to get a firm idea of how creating database works in Sqlite. Hope it helps.
private static final String SCRIPT_CREATE_DATABASE =
"CREATE TABLE IF NOT EXISTS " + MYDATABASE_TABLE + " (" + "ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"KEY_CHECKBOX_STATUS INTEGER, " + "KEY_CHECKBOX_LABEL TEXT, " + " KEY_PRICE INTEGER" + ");";
Use this query while creating the table. It will create the Table if it doesn't exist.

How to store data in android for a long time?

I am trying to develop android application (first time), so I'm using SQLite to store data. But every time I run the application all data are null! I think the problem is when I run the application it recreates all the tables and they come as new empty tables!
Can anyone help or give example how to check if the tables are already created, and if yes copy the data, if not create and that means it's a first time!
How can I store data for a long time by using SQLite? If I cant what is the best way to store data?
//food
private static final String food= "food";
//---- columns -----
private static final String fid = "fid";
private static final String fname= "fname";
private static final String category = "category";
private static final String quantity= "quantity";
private static final String unit= "unit";
private static final String carbs= "carbs";
//food
private static final String DATABASE_CREATE_Food="CREATE TABLE "
+food+" ("+fid
+ " INTEGER PRIMARY KEY AUTOINCREMENT , "
+fname+ " TEXT NOT NULL, "
+category+" TEXT Not NULL, "
+quantity+" Double Not Null, "
+carbs+" Integer NOT NULL, "
+unit+" TEXT NOT NULL"
+");";
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_Food);
}
/** Called when the DATABASE_VERSION is changed to higher version */
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MyAppDB.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS" + food);
onCreate(db);
}
There are a lot of ways to store data in android, SQLite is one of them.
There is probably something wrong with your code, because it shouldn't be null everytime you start the app. Post your code here, so someone can find out what's wrong with it.
For other ways to store data in android, check out this link from developer.android site
http://developer.android.com/guide/topics/data/data-storage.html

Adding new table to database after app has executed once

I'm making a simple database in Android. I want to add new table after my code has executed once. Now, whenever i try changing my onCreate() method in EventDataSqlHelper class my app crashes.
This is probably because onCreate() associated with SQLiteOpenHelper is executed only when app is first run and we can't make further modifications in it .
I also tried writing a separate function for adding new table. It worked perfectly on first execution.But since on 2nd exection it will overwrite its previous database, hence it causes app to crash.
Is there any way to add new tables to database if database has already been created?
package org.example.sqldemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
/** Helper to the database, manages versions and creation */
public class EventDataSQLHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "events.db";
private static final int DATABASE_VERSION = 1;
// Table name
public static final String TABLE = "events";
// Columns
public static final String TIME = "time";
public static final String TITLE = "title";
public EventDataSQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + "( " + BaseColumns._ID
+ " integer primary key autoincrement, " + TIME + " integer, "
+ TITLE + " text not null);";
Log.d("EventsData", "onCreate: " + sql);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
This is what onUpgrade and DATABASE_VERSION is for.
Example:
You have a table events, and is executed on phone.
Now you decide, you want a new table users.
change DATABASE_VERSION = 2; (this is your version number)
in onCreate() , create all tables (create table events & create table users)
in onUpgrade(), create all tables that changed between version oldVersion and newVersion (create table users)
Later if you want to add new tables, increment DATABASE_VERSION again, and create all tables in onCreate, and changes in onUpgrade
You could use CREATE TABLE IF NOT EXISTS TABLENAME ... as your query, that wouldn't overwrite your existing table.

Categories

Resources