I have in my database two tables : one is full of content and the other just is empty (I have only built the name of the fields and that's it). The whole database is in the assets folder of my application.
I have a method supposed to add a new element to this empty table every time I click on a button.
OnClickListener poi_favoritesbutton_listener = new OnClickListener(){
#Override
public void onClick(View v) {
DatabaseAdapter.insertInTable(ID_NAME, ID_CAT1, ID_CAT2, ID_CAT3, ID_CUISINE);
}
};
Here is the method :
public static long insertInTable(String ID_NAME, String ID_CAT1,
String ID_CAT2, String ID_CAT3, String ID_CUISINE) {
ContentValues data = new ContentValues();
data.put(FAV_NAME, ID_NAME);
data.put(FAV_CAT1, ID_CAT1);
data.put(FAV_CAT2, ID_CAT2);
data.put(FAV_CAT3, ID_CAT3);
data.put(FAV_CUISINE, ID_CUISINE);
if (myDatabase == null) {
}
return myDatabase.insert("DATABASE_FAVTABLE", null, data);
}
I think it should be correct as I have followed what was discussed on SOF related topics but I'd like not just to "think" and be sure instead! I tried using debug mode / DDMC but no way to actually open my database in real time and check for evolution of its content...
Any suggestion ? Thanks !
ps: i'm using a real device to run my test, emulator is just killing my time.
According to insert() docs:
Returns
the row ID of the newly inserted row, or -1 if an error occurred
so basically all you need is to check if you did not get said -1 in return.
no way to actually open my database in real time and check for evolution of its content
You can pull the database table to the device and see the contents of the table under DDMS tab-> File Explorer
Related
As I changed the android version and the path from externalized to the default database-folder, I don't know where the error come from.
I found that the reason might be problems accessing the journal file is locked (it is created by the program).
the "test" is reading data and if it exists it updates and if not it inserts. This is done in a loop while reading lines from a file. For testing purpose i simplified it but the error is the same.
package ...;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class test {
public test(SQLiteDatabase MyDB)
{
MyDB.execSQL("CREATE TABLE IF NOT EXISTS testtable (mytext TEXT, number INT PRIMARY KEY)", new String[] {});
for (int i = 1; i < 5; i++)
{
String[] ColArray = { "any text", String.valueOf(i) };
Cursor readCursor = MyDB.rawQuery("SELECT mytext FROM testtable WHERE number=?", new String[] { String.valueOf(i) });
if (!readCursor.moveToNext()) // Error when executing moveToNext
/*
In the 2nd time it runs over this point an Error occurs:
android.database.sqlite.SQLiteCantOpenDatabaseException: unable to open database file (code 14)
I need to remove the journal file to be able to connect to the database it again - the change made by the Insert/Update is successfully saved!
*/ {
readCursor.close();
MyDB.execSQL("INSERT INTO testtable (mytext, number) VALUES(?, ?)", ColArray);
}
else {
readCursor.close();
MyDB.execSQL("UPDATE testtable SET mytext=? WHERE number=?", ColArray);
}
}
}
}
MyDB is a valid DB-Connection.
1) The Table is created
2) The Table is READ but Line 1 is not found
2a) READ again is possible until now if the read is closed.
3) Line 1 is INSERTED
4) when trying to READ again (the line 2 would not be found, too), moving the cursor fails.
The journalfile need to be deleted manually or the app will fail to start again when trying to connect.
Please Help! Thank you.
Maybe you should use the specialized insert and update methods.
In the documentation of the SQLiteDatabase it says for execSQL:
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
There are specialized methods for insert and update with similar names. I guess, that there is some problem generated, when the unspecific "execSQL" statement is used.
i solved it after hours of testing.
possibly the sqlite version is different in the old and new system... i changed the rom again - for some reason, this time i didn't copy the databasefile into the data-folder. Instead i let the program create a empty database and imported the data from text by the program itself from a csv-export.
I currently don't know if the problem was within the rom or (what seem to be the reason in my opinion) i created the problem by using the origin database which might be read and writeable but has problems when the journalfile should get processed. if somebody has an equal problem, he should try to create a new empty database in the new system.
I am writing a program to display the details of students' record in android. I am using a existing database and getting the data from it. Here I need to update the status as confirmed.
I have created a confirmation button which on pressing will update the status as confirmed. Here on pressing the button my code shows no error but the value is not updated in the database. For information I am using sqlitebrowser as my database.
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ContentValues values = new ContentValues();
//contentValues.put(DatabaseHelper.STATUS,"CONFIRMED");
StudentDetails = SQLiteDatabase.openDatabase("", null, SQLiteDatabase.OPEN_READWRITE);
//status.setText("CONFIRMED");
//mDbHelper.close();
values.put("Status", "Confrimed");
StudentDetails.insert("Student","", values);
Toast.makeText(getApplicationContext(), "Status upadated", Toast.LENGTH_LONG).show();
StudentDetails.close();
}
}
I noticed you've supplied "" as the argument to path for openDatabase(). Unless you're calling this on a member that will open the appropriate database, I believe this wouldn't open a valid database, and thus I wouldn't be surprised if a row didn't get written to the table you were trying to modify. Perhaps try supplying a database file name instead of a blank string and see if that works.
Also, if you're not implementing SQLiteOpenHelper in your own class as outlined in Saving Data in SQL Databases, I would suggest trying that instead of accessing the database in another way, if it isn't too much trouble. I've just made an app using this method, and I have no problems.
Nonetheless, I would assign a long to the output value of the insert function, and set a debug point or write its value of the console. If the value is -1, the method didn't assign a row to the table (possibly because of database constraints - perhaps check that you're satisfying them in terms of the values supplied in the Bundle).
The value returned from insert will be -1 if an error occurred, as outlined in the docs for insert(String table, String nullColumnHack, ContentValues values)).
You should use StudentDetails.update("Student","", values);
I have a database with multiple tables. One of these tables (sport) is where i have to put a static list of object, each one with an _id, name, logo and an int. The _id will be used by other tables to do some queries (eg. select from "table X" where sport_id = _id), so it shouldn't change overtime (is there a way to update all the reference to this _id if it will change?).
Where should i put the code (i think it will be a simple list of db.insertSport()) to make it add this row only one time (and check if the row number grow, to add the new ones)?
There won't be much row, 50 at the best.
I think I would make a method in the dbHelper to insert that data, then call that method immediately upon app start. I'm making a couple of assumptions here... first that you are shipping this static info with the app and when you want to add more info you will be shipping a new version.
You could store the data as a text file in your assets folder and then read the file in execute a batch insert in the method.
If you set it up right (use insertWithOnConflict and the CONFLICT_IGNORE flag in the method) it will only add the new rows (if any) each time so you can run it every time the app starts and not worry about duplicate data or crashes for constraint violations.
If you only want it to run the once and then again when there is additional info, put a version number in the text file and check that against the previous one (which you can store in SharedPreferences).
EDIT
Example of using insertWithOnConflict:
public long createItem(String yourdata) {
ContentValues initialValues = new ContentValues();
initialValues.put(YOUR_COLUMN, yourdata);
return mDb.insertWithOnConflict(YOUR_TABLE, null, initialValues,
SQLiteDatabase.CONFLICT_IGNORE);
}
You can read up on the SQLiteDatabase class (which has the constants and methods) here
I’m using a database helper to update a table with one row and two fields, I have the following code that that sends two phone numbers through.
dbHelper.updateNumbers(newSmsNumber, newVoiceNumber);
and the following method in the helper.
public void updateNumbers(String newSmsNumber, String newVoiceNumber) {
//Update code here
}
Can anyone show me the code I need to add in the method to update the two fields in the database.
Cheers,
Mike.
ContentValues cv = new ContentValues();
cv.put("SMS", newSmsNumber);
cv.put("Voice", newVoiceNumber);
db.update("[table name]", cv, "ID=?", new String[]{Integer.toString(id)});
There are some gaps to fill up though, the table name, and how you identify the entry you want to update (I put a "ID" field there in that example)
Did not run that code, did not really check, but that should give you an idea.
I am using my own SQLite3 database as opposed to creating a new one each time my app runs, as I have a few tables with static data that I am trying to display. I created my database and placed it in my assets folder. I then created my database helper and when I start my app I can open my database without problem but when I try to open my first table using the following code
private Cursor getData()
{
try
{
myDbHelper = new DatabaseHelper(this);
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor cursor = db.query("exhibitor", FROM, null, null, null,null, ORDER_BY);
startManagingCursor(cursor);
return cursor;
}
catch(SQLiteException e)
{
String err = e.toString();
return null;
}
}
It throws an error saying android.database.sqlite.SQLiteException: no such table: exhibitor: , while compiling: SELECT _id, EXHIBITOR FROM exhibitor ORDER BY EXHIBITOR but when I check the database exhibitor is there.
What am I missing?
Settings -> Applications -> Manage Applications -> (Click on your application) -> Clear data
Whenever you create new table in an existing database the table doesnt create because the OnCreate function of database handler will not be called everytime but only if required(like database not initiated). If that is not the case your newly created table actually hasnt created. Clear the data to force the db to instantiate itself.
Have you moved the database from the assets folder to /data/data/YOUR_PACKAGE/databases/ on the emulator?
This is a good detailed post about moving the database to /data/data/YOUR_PACKAGE/databases/ if it does not exist.
Here is another short and simple solution to it.
Clear Data and uninstall application from your device and re-install application in device...
Settings -> Applications -> Manage Applications -> Your Application Name -> Clear data
Using SQLiteOpenHelper.onCreate() does not create a new database every time your app starts - rather it creates a database if it does not already exist.
It sounds like you might have an empty database created by or for your helper (if there was no database at all, I might expect a different exception), and your separate database that you created outside of Android. Looks like you and your app are not looking in the same place for your data.
Just clearing the data did not work for me.
What worked was:
Uninstall app
Restart device or emulator
Disable Instant run (Not just the main group but all individual instant run settings)
Build -> Clean Project
Build -> Rebuild Project
hapend to me once
change your DATABASE_VERSION
if your DATABASE_VERSION =1 it will see just three table
if your DATABASE_VERSION = 2 it will see just more table but i really didn't know how many
good luck
I just had a simple mistake.
Reason:
Solution:
Just happened to me. I don't exactly know why but changing the DB_VERSION attribute to a bigger number made it work. The thing is: each time i'm changing the fields of the DB (attributes of the SQLiteDB class), i need to change that number.
Here is my answer according to the description of #ReivieraKid.
No, Uninstall, No Restart, Just checking the app memory if it is your real database, if return false, then copy the database to the memory again. Then You will All set. But to apply this method, you have to know the minimum size of your database.
https://stackoverflow.com/a/73332470/7608371