android - inserting long into SQLite Integer field - android

I am working on an app and need some help. I have a table where I store some informations and another which has a reference. The column where the reference is made is named "COLUMN_MODULE_ID". In my DBHelper, I have declared it as an Integer. But the value I get (which is the ID from the other inserted table row which I get as a long type) seems to not get into the table.
If I put i.e. 600 hard coded into the column "COLUMN_MODULE_ID", everything works fine. But if I set the long value "module_id" hard coded to 600 and put the variable into the column, it doesn't work.
Any suggestions?
edit:
Okay, after further inspection, I have the following code:
Uri moduleUri = mContext.getContentResolver().insert(DataContract.ModuleEntry.CONTENT_URI,
moduleValues);
String moduleId = moduleUri.getLastPathSegment();
Log.v("Module ID: ", moduleId);
getQuestionsArrayFromJson(moduleName, century, moduleId);
Lets expect, that the Log says "Module ID: 887". My App doesn't work.
But if I add
moduleId = "887"
after
String moduleId = moduleUri.getLastPathSegment();
, the log says the same but my App works. I have no clue why but I think it must be some type thing.
edit #2:
So I came further to the point where the whole thing blows up. When I fetch my data from a JSON String, I implement it into a table, which works fine. However, I get the _id from the inserted entry, which inserts just fine, with the following snippet:
long moduleId = ContentUris.parseId(moduleUri);
so when I log the variable moduleId, it shows the right _id.
When I try to insert it into another sqlite table, it doesn't work.
questionValues.put(DataContract.QuestionEntry.COLUMN_QUESTION_NO, questionNo);
questionValues.put(DataContract.QuestionEntry.COLUMN_QUESTION_TEXT, text);
questionValues.put(DataContract.QuestionEntry.COLUMN_MODULE_ID, moduleId);
Uri questionUri = mContext.getContentResolver().insert(DataContract.QuestionEntry.CONTENT_URI,
questionValues);
I just can't access it from my app. If I change the code to have a fix number in it like:
questionValues.put(DataContract.QuestionEntry.COLUMN_QUESTION_NO, questionNo);
questionValues.put(DataContract.QuestionEntry.COLUMN_QUESTION_TEXT, text);
questionValues.put(DataContract.QuestionEntry.COLUMN_MODULE_ID, 555);
Uri questionUri = mContext.getContentResolver().insert(DataContract.QuestionEntry.CONTENT_URI,
questionValues);
I can access the module with the id 555 just fine from my app. So I think it has something to do with the type that the ContentUris.parseId gives back.
I can also put the 555 in a long or int variable and put the variable into the questionValues.
Any suggestions?

Okay I figuered it out. My Code was fine. I had another problem, clearing the table everytime I fetched new data into my database. Bad mistake, sorry.

Related

SQLite in Android adding quotes to start and end of datelike string

Interesting issue while using SQLite in Android. I am seeing an inconsistency in the string length and quoting of a string between what is stored in the database and the materialized value seen in Java.
We are using an ORM called SugarORM to query the DB, but I've traced the offending code to the internal android.database.sqlite.SQLiteCursor class used within SugarORM, specifically the cursor.getString(columnIndex) method.
I have a string in the database that is an ISO data string 2019-03-25T19:19:39.664Z and is stored in a VARCHAR column . I have confirmed using DB Browser for SQLite that the length of the string as its stored in the database is indeed 24 characters. SELECT LENGTH(MyStringColumn) FROM MyTable WHERE ...
When I get the value of this string via cursor.getString(columnIndex), it is returning the string "2019-03-25T19:19:39.664Z". Notice the leading and trailing quotes. Java reports to me that the string is 26 characters long.
Any value that I store in this column that is not an ISO data does not have this behavior. I tried tracing the SQLiteCursor source back, but ultimately it ends up being a Native method and that's where my skill set stops.
Can anyone explain what might be going on here? I am probably just going to write a wrapper around my queries to get rid of the quotes, but its all very perplexing. The date string is being fed to a JavaScript interpreter and causing it to fail when creating a JavaScript Date object.
If it helps, I have replicated the behavior on both my S7 physical device and a Pixel 6 emulator.
As a quick get around you could use :-
SELECT length(replace(mystringcolumn,'"','')) FROM mytable;
or before using the original SELECT use :-
UPDATE mytable SET mystringcolumn = replace(mystringcolumn,'"','');
If this doesn't fix the issue, then for some reason it is the code that retrieves the data that is at fault.
e.g. consider :-
DROP TABLE IF EXISTS mytable;
CREATE TABLE IF NOT EXISTS mytable (mystringcolumn VARCHAR);
INSERT INTO mytable VALUES('2019-03-25T19:19:39.664Z'),('"2019-03-25T19:19:39.664Z"');
SELECT length(mystringcolumn), length(replace(mystringcolumn,'"','')) FROM mytable;
which results in :-
i.e. The 2nd row, 2nd column retrieves the appropriate value by using the replace function to strip of the quotes, if they exist.
As to why the quotes exist could depend upon either the way that the data is inserted (perhaps you have inadvertenly coded the quotes but the db being looked at isn't the actual database as copied from the App) or the way in which the data is being retrieved that for some reason adds them.
I don't believe it likely that the Cursor getString method has a bug in which the quotes are added, otherwise such an issue would likely be a recurring issue.

Get the value from the cursor in Android SQLite

I used the below code to get the "place" value from the "place" column using a cursor. The value of the place in my database is a string,but It returns a number that I have no idea what it is.
here's my code:
meeting.setPlace(cursor.getString(cursor.getColumnIndex("place")));
I think I've inserted them correctly... here it is:
contentValues.put("place",R.string.consert7_place);
db.insert(TBL_MEETING,null,contentValues);
R.string.consert7_place is an integer, not a String.
You need to use getResources().getString(R.string.consert7_place)
For more details, see Android: How do I get string from resources using its name?
Your cursor.getString usage is fine.

Copy data between tables with some static values

I need to copy data from one table to another. Doing so, I'd like to set manually some static values that will override data from source table. Here is example:
INSERT INTO users (id_usr, name, description, mod_date, user_type) 
SELECT id_usr, name, description, '2014-03-19 15:15:09', 'public'
FROM users_temp
WHERE user_type="" OR user_type IS NULL;
'Datetime' string and 'public' are those static values.
I'd like to know if it is possible, because on Android phone(SQLite from external native library) it doesn't copy any records, but on Windows it works fine.
I've found the problem. My users_temp table was actually a virtual table created from file. While creating that virtual table I have defined wrong charset. It caused that, at the end of every value there was added some kind of white character and condition:
WHERE user_type="" OR user_type IS NULL;
was never fulfilled.
After fixing the problem, statement is executing correctly.

Android: SqliteDatabase's lastModified() is giving wrong value

I am using sqlcipher database. I am tracking the lastModified time of my database. According to my understanding long value returned by lastModified() function will change only if we update or add a value to the database we refer. I am using a query to fetch (not modifying) a value from the database, for this i am using the below code
mDatabaseFileObj = mContext.getDatabasePath("xxx.db");
Log.i(""," "+mDatabaseFileObj.lastModified());
mSQLiteDatabase = net.sqlcipher.database.SQLiteDatabase.openOrCreateDatabase(...)
Log.i(""," "+mDatabaseFileObj.lastModified());
mCursor = mSQLiteDatabase.rawQuery(query, null);
do{
....
}while(..)
In this i had printed two logs. First log before creation of mSQLiteDatabase obj and another log after that.According to the doc for lastModified() both the values printed by the logs should be same as i just quering not modifying the database. But the value is changing.
I couldnt sort out this problem.Give your thoughts on this.
An addtional info is, i had placed this code snippet in a function and i am calling that function 5 times and strangely for the first time alone the log is printing different values but for the rest 4 times the log printed values are same..
Thanks in Advance
Deepak,
openOrCreateDatabase is not a read only operation. In particular the wrapping library, which is based on the Android sqlite library, manipulates a table called android_metadata when the database is open. This could cause the timestamp to change, because the database is actually modified during open.
mDatabaseFileObj this is reference to your File object from OS don't confuse this with database in SQLITE database are implemented on top of file system only, so in first line you are printing when this file was last modified,
while second line you are trying to alter the file, and third line again printing time, so as per me and going with file systemn behaviour you will get a different time stamp, this doesn't mean if content inside this file was modified or not.
Just imagine it like this, open a txt file in windows and save it again without changing it notice time before and after they will be different.
Hope this help.

Android - how to use "select last_insert_rowid();"

I'm newbie in Android.
I want to display a new ID in the TextView.
So, I just think of getting latest ID that had been store in the database and declare as Integer add 1 to the value that I get then display to the TextView.
I have read many of the question regarding the getting the latest ID. How can I use select last_insert_rowid();?
Thanks!
last_insert_rowid() works only for records that have been inserted in the same session.
If your column is declared as INTEGER PRIMARY KEY, then SQLite will automatically generate a value for it if you don't specify one in a new record.
If you really need the ID before you have inserted the record, you can execute something like this:
SELECT max(_id) FROM MyTable
if you use autoincrement use
SELECT * from SQLITE_SEQUENCE;
to get the latest id.
Cursor c = database.rawQuery("SELECT last_insert_rowid()", null);
c.moveToFirst();
int id = c.getInt(0);
id += 1;
I'm a newbie too so can't explain very well. The above will get the last insert id from the same session. It won't work if a new session is started, ie you insert something and close the connection and reopen it, as it will then return 0 so you'll need to bear that in mind as your TextView would always show 1. As like you I read many questions about it without knowing how to implement it. The above code is how I managed to use it without getting outofbounds exceptions.

Categories

Resources