I try to include transactions in my application because writing in database is very slow and I saw here and here that transactions are a solution but they are still very confusing to me.
I have Schedule objects that contains an object LineStation, and I want to write them in database using transactions.
Here, the method addSchedules in my class ScheduleDAO, that writes all schedules in database. It contains only one transaction.
public void addSchedules(ArrayList<Schedule> schedulesList) {
SQLiteDatabase db = this.dh.getWritableDatabase();
db.beginTransactionNonExclusive();
for (Schedule schedule : schedulesList) {
ContentValues values = new ContentValues();
// insert linestation
LineStationDAO.getLineStationDAO().addLineStation(schedule.getLineStation());
values.put(/*...*/);
/* ... */
db.insert(DatabaseHandler.TABLE_SCHEDULE, null, values);
}
db.setTransactionSuccessful();
db.endTransaction();
db.close();
}
And this is, the method addLineStation in my class LineStationDAO that saves the object LineStation given. It's called by addSchedules and doesn't contain transaction because it is "nested" in the addSchedules transaction.
public void addLineStation(LineStation lineStation) {
SQLiteDatabase db = this.dh.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(/*...*/);
/* ... */
db.insert(DatabaseHandler.TABLE_LINE_STATION, null, values); // database is locked (code 5)
db.close();
}
The LineStation insert implies an SQLiteDatabaseLockedException (database is locked -code 5).
What I have done wrong, please? Thanks.
The problem is that a database transaction cannot exist across multiple database connections. In the addLineStation method, you are opening a second database connection, when you should be using the one created in addSchedules.
You need to pass the SQLiteDatabase db object down to the addLineStation method like this:
LineStationDAO.getLineStationDAO().addLineStation(db, schedule.getLineStation());
and change this:
public void addLineStation(SQLiteDatabase db, LineStation lineStation) {
ContentValues values = new ContentValues();
values.put(/*...*/);
/* ... */
db.insert(DatabaseHandler.TABLE_LINE_STATION, null, values); // database is no longer locked (code 5)
}
Basically, I have a Local DB file called DBhelper in which i have this function
public void addWallpost(Wall accountwallpost) {
Log.d("addWallPost", accountwallpost.toString());
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_WALL_ID, accountwallpost.wallID);
values.put(KEY_WALL_POSTER, (accountwallpost.poster).toString());
values.put(KEY_WALL_POST, accountwallpost.wallContent);
values.put(KEY_WALL_POSTER_COMPANY_ANNOUNCE_TITLE, accountwallpost.announcementTitle);
values.put(KEY_WALL_POSTER_COMPANY_ANNOUNCE_LINK, accountwallpost.announcementLink);
values.put(KEY_WALL_TARGET_NAME, (accountwallpost.target).toString());
values.put(KEY_WALL_NUMBER_LIKES, accountwallpost.userLike);
values.put(KEY_WALL_GAP, accountwallpost.gap);
db.insert(TABLE_ACCOUNTWALLPOST, null, values);
db.close();
}
I have this other file which loads from the server database all the values of the Wallpost table
public List<Wall> loadHome(long accountID, int start, int numberOfResult) throws Exception {
this.setFunction("LOAD_HOME");
this.addAccountID(accountID);
this.addParameter("start", start);
this.addParameter("numberOfResult", numberOfResult);
return WallParser.parseWallList(this.postJSON().getJSONArray("wallpost"));
}
What i need help in is how do i save the data from the server database to the Local DB?
I tried adding the code
DBHelper.get(context).addWallpost(accountwallpost);
But i dont know how to get a row from the server database since the data is gotten as a List.
Any help is appreciated.
I want to clear my SQLite db every time I hit a particular spot in my application.
I intended on just making a method that I could call called resetTables(), but this seems to be more challenging than I expected because I don't really know where to place it. Here is a snippet.
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
public void reset(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
}
I'm getting a yellow line under reset and I can't call this method in my code. Any ideas?
Note this question is similar, but couldn't get it to help me.
This worked:
public void resetTables(){
mDb.delete(TABLE_NAME, null, null);
}
first create one method where you create your database and table.
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_NAME, null, null);
db.close();
}
and call above method using on your button click event.
i have done it by this way...
#Override
public void onOpen(SQLiteDatabase db) {
// TODO Auto-generated method stub
super.onOpen(db);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
}
and yes it definitely worked for me..:)
I have been getting this exception, DatabaseObjectNotClosedException:
close() was never explicitly called on database '/data/data/com.project.test/databases/database'
E/SQLiteDatabase(13921): android.database.sqlite.DatabaseObjectNotClosedException:
Application did not close the cursor or database object that was opened here
I tried closing the database helper and cursors, but I will get runtime exception. This happens when I leave the activity and revisit it after hitting the back button.
How can I close my cursors and helpers properly?
I have tried two methods:
first, closing the cursors after each individual use, and closing the database helper onpause.
second, closing the cursors onpause along with the databasehelper, but both didn't work.
can someone help me with this?
EDIT:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this.getActivity();
context = this.getActivity().getApplicationContext();
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mDbHelper = new DatabaseHelper(context);
mDbHelper.open();
populateList();
}
public void populateList() {
directoryCursor = mDbHelper.fetchAllRootDirectories();
activity.startManagingCursor(directoryCursor);
adapter = new DirectoryListAdapter(this.getActivity(), directoryCursor);
this.setListAdapter(adapter);
}
......
private UpdateDatabaseListener updateDatabaseListener = new UpdateDatabaseListener() {
public void onUpdate(int from, int to) {
.....
findExistingRecordCursor = mDbHelper.findExistingRecords(from, to);
activity.startManagingCursor(findExistingRecordCursor);
if(findExistingRecordCursor.getCount() == 0) {
....
}
}
}
I have a database helper opened in the onCreate() function.
cursors used when populating the listview,
cursors used to find existing records,
cursors to get information.
UPDATE:
I have tried closing onPause and onDestroy, it still crashes with runtimeexception.
Are you closing the SQLiteDatabase object or not. If not try to close SQLiteDatabase Object like this
SQLiteDatabase db = SQLiteHelper classobject.getWriteableDatabase();
// block of code
db.close();
and run your application.
Could you please post your code so that it will be more helpful to understand your problem.
Sorry for the late reply.
From what I see, you have opened the db using
mDbHelpher.open()
After that you did populatelist()
did you try doing mDbHelpher.close() after that?
Same thing with the cursors. Because your error clearly says that the db or the cursor was left open.
As soon as you are done using the db, you should close. This should not give the problem even after you visit another activity and then press back button.
Also you said you get runtime exception when you close the db or the cursor. Is it the same exception or different?
I am trying to make my first Android app. I noticed that the SQLiteOpenHelper.onCreate() method is not called to create tables if the database not exists. However, the onCreate() method did not work even thought I tried to debug.
Please look at the code below and give me any suggestions. Any help will be appreciated.
public class NameToPinyinActivity extends Activity {
DatabaseOpenHelper helper = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nametopinyin);
Button searchButton = (Button) findViewById(R.id.search);
searchButton.setOnClickListener(new ButtonClickListener());
helper = new DatabaseOpenHelper(NameToPinyinActivity.this);
}
public class DatabaseOpenHelper extends SQLiteOpenHelper {
/** DB Name */
private static final String DB_NAME = "pinyin";
/** CREATE TABLE SQL */
private static final String CREATE_TABLE_SQL = "CREATE TABLE UNICODE_PINYIN"
+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "UNICODE TEXT NOT NULL, PINYIN TEXT NOT NULL)";
public DatabaseOpenHelper(Context context) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.beginTransaction();
try {
db.execSQL(CREATE_TABLE_SQL);
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
}
I have also had trouble with the SQLiteOpenHelper. What worked for me was storing a member variable
SQLiteDatabase db;
In the SQLiteOpenHelper subclass and calling
db = getWritableDatabase();
in the constructor.
The answer to this question also includes helpful information: SQLiteOpenHelper failing to call onCreate?
I hope this helps!
Until you call the method getWritableDatabase() or getReadableDatabase() of SQLiteOpenHelper class, database won't be created.
as simple as that database will be created in memory when you actually need that.:)
I had a similar problem where onCreate wasn't executed. Maybe this is of any use for someone even though it turned out being a different problem.
I was working on the database before and had already created one long time before. So now after making changes in onCreate() I was hoping to find the new tables created. But the SQLiteOpenHelper never called onCreate() again. Reason was, the database already existed. I was still working with the same device as before and consequently with the already existing (old) databse.
But there is hope. When the system sees a database with that name already exists, it also checks whether the version number is correct. In that case I simply forgot the database already existed. My solution was simply changing the version number. So onUpgrade() was called offering options for onCreate() changes.
So options were either uninstalling the complete app (and with it the database) or call onCreate again after upgrading the version number (and for example dropping) the old table and calling onCreate() again.
In any case, if onCreate() is not called, check twice if the database exists. Otherwise it's not called again.
I had a similar problem however it was not the OnCreate call that was the issue.
In the example code above, Kevin explained that the OnCreate is not called if the database already exists. However if, like me, you are using multiple tables from separate activities, then though you may have created the database already, the table associated with this activity may yet have not been created. Hence when you attempt to set the cursor data on a non-existent table, you will invoke an exception.
My solution was define a separate class called CreateTable which is called both from the OnCreate override and from the constructor after the
db = getWritableDatabase();
Call getWritableDatabase(); in the constructor
public DataBaseH(#Nullable Context context) {
super(context, dataBaseName, null, dataBaseVersion);
SQLiteDatabase db=this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable="CREATE TABLE IF NOT EXISTS "+tableName+ " ( "+
id+ " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"+
name+ " TEXT,"+
familyName+ " TEXT,"+
age+ " INTEGER);";
db.execSQL(createTable);
Log.i(TAG,"db.exect");
}
I was having a similar problem with onCreate() not executing when the app was very first run, so my database never got created. This is NOT the same as when onCreate() is not executing because the database already existed, because the database did not yet exist. Specifically, my DataProvider onCreate() was not executing, so the OpenHelper never got called either.
I verified I had everything set up the way that everyone described in the previous answers, but nothing resolved my problem. Posting this answer in case anyone else forgets one small detail like I did.
What resolved the problem for me was adding a entry in AndroidManifest.xml for my Data Provider, nested inside the tags, along with all of my entries. The only attributes I needed were:
android:name=".DataManagement.DbDataProvider"
android:authorities="com.example.myApplicationName.DataManagement.DbDataProvider"
android:exported="false"
(Make sure to change the values for the above attributes to match your project)
I cleaned, built, ran, and onCreate() methods for the data provider and open helper classes executed properly, and the database was created on first application launch!
I had the same problem.. the resolution for me was to add .db as extension of the database name
In my case, it was not being called because the database already existed! So, if possible, make sure to delete your app and install it back and only then check if it is being called or not.
I had the same problem where it seemed that the onCreate was not executed. I thought so because my logs were not displayed. Turned out that there was something wrong with the blank spaces in my SQL_create String.
#Override
public void onCreate(SQLiteDatabase db) {
try {
Log.d(LOG_TAG, "A table is created with this SQL-String: " + SQL_CREATE + " angelegt.");
db.execSQL(SQL_CREATE);
}
catch (Exception ex) {
Log.e(LOG_TAG, "Error when creating table: " + ex.getMessage());
}
}
This is my corrected SQL-String:
enterpublic static final String SQL_CREATE =
"CREATE TABLE " + TABLE_VOCAB_LIST +
"(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_GERMAN + " TEXT NOT NULL, " +
COLUMN_SPANISH + " INTEGER NOT NULL, "+
COLUMN_LEVEL + " INTEGER NOT NULL);)"; code here
I had forgotten one blank space and when I added it everything worked fine.
You can change AUTOINCREMENT to AUTO INCREMENT
Note
SQLiteOpenHelper Called onCreate when the database is created for the first time. If you create table in onCreate method you can't create new SQLiteDatabase. You can see example
#Override
public void onCreate(SQLiteDatabase db) {
String stringCreateTable = "CREATE TABLE "+"tblUser"+" ( " +
"id TEXT PRIMARY KEY, " +
"name TEXT )";
db.execSQL(stringCreateTable);
}