Android SQLite search a column - android

I have code that gives me a number, and I have an Android SQLite table.
The first column has a lots of numbers and I need to compare the number that I got from the code to these numbers in the table and find the one that matches my number that I got from the code. Once I find it, I need to update the row.....
what is the best way to do it.....?

Your question lacks details, like the name of the column holding the number value and the column(s) being updated when the record is found, but you'll be using something that resembles:
UPDATE your_table
SET column_1 = ?,
column_2 = ?
WHERE number_column = number_from_code

Related

SQLite (Android) : UPDATE query with ORDER BY

Android, SQLite : I want to insert rows in between other rows in myTable using SQLite in android. For this, I am trying to increment ids of the all rows starting say row 3. So that I can insert a new row at position 3.
The primary key of myTable is column id. There are no other constraints in the table.
I have tried using the query mentioned in https://stackoverflow.com/a/9177264/6671004. This query does work in mySQL but not in Android (SQLite)
Here's the line of code :
database.execSQL("UPDATE myTable SET id = (id + 1) where id > 2 ORDER BY id desc");
Here's the error I'm getting on Android Studio (Compile time) :
https://imgur.com/a/9r0iyAa
This is the exception I'm getting if I remove 'ORDER BY id DESC' from the query :
java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: myTable.id (code 1555)
Is this the correct way to do this? Or is there a better way?
As pointed out by many, this is definitely not the correct way to go.
But I found workaround in case someone else is looking for a similar implementation.
Here it is :
UPDATE myTable SET id = - (id + 1) WHERE id > 1;
UPDATE myTable SET id = - id WHERE id < 0;
This is a hack which I found here.
Again, this is not the correct way to go. But just posting a working solution I found.
I have tried using the query mentioned in
https://stackoverflow.com/a/9177264/6671004. This query does work in
mySQL but not in Android (SQLite)
That question is tagged MYSQL. MYSQL has many differences from SQLite.
Here's the line of code :
database.execSQL("UPDATE myTable SET id = (id + 1) where id > 2 ORDER
BY id desc");
The SQLite UPDATE SQL takes the form of :-
i.e. there is no ORDER BY clause and hence the error saying that if you're going to use any KEYWORD then it must be a BETWEEN or IN or a ; (of course you could also extend the condition using AND OR and so on).
This is the exception I'm getting if I remove 'ORDER BY id DESC' from
the query :
The reason being is that the rowid (id being an alias of rowid) has an implied UNIQUE constraint and that the rows will be updated according to the id column in order. So if there are more than 3 rows (or have been and the last row has never been deleted) then when the id is 3, a row with 4 will exist and 3 + 1 = 4 so the row already exists and hence the UNIQUE constraint being encountered.
I want to insert rows in between other rows in myTable using SQLite in
android. For this, I am trying to increment ids of the all rows
starting say row 3. So that I can insert a new row at position 3.
In short that is not a good idea and is virtually definitely not needed.
Is this the correct way to do this? Or is there a better way?
Definitely no
At a guess you want a nice humanly understandable value so you can know what's going on. For example you may present a list with the sequence so you can then say delete the row that has a sequence of 3 and thus equate that to the id column. Fine until you present the list in a different order which may be more user friendly. Suddenly your sequence becomes complicated or even useless and if displayed confusing.
identifiers are intended to identify a row and allow fast access to that row as a numerical index will be more efficient (than a human easily readable non-numeric index) to process. They also cater for reducing unnecessary additional processing (shifting data).
An efficient methodology is presenting the list with tying the id to the position in the list (so position could be the nth element of an array that holds the respective id, regenerating the list (the underlying array) according to a different order so the nth element will still have the respective id).
Embarking on a process of shifting rows will impose additional resource usage for example extra disk IO whose cost is relatively expense. This will be compounded by the fact that you will have to process the rows in reverse order to get around the UNIQUE constraint, that in itself is going to require using even costlier methods because SQLite will by default try to perform the updates efficiently rather than cater for the efficiencies required to digress from recognised/accepted techniques that utilise the underlying efficiencies.
I found this one working. And remove autoincrement from id
String strSQL1 = "UPDATE people_table SET id = (id +1) WHERE id < 0";
String strSQL = "UPDATE people_table SET id = (id -1) WHERE id > 1";
db.execSQL(strSQL);
db.execSQL(strSQL1);

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.

how would I get a random rowId from my database?

I have a database wherein i get my questions , correct answers/options from... I want my application to automatically generate random rowIds so that the questions could be shuffled.. Of course, the question that's already shown should not display again. I want to get 10 questions then finish();..
Using a random rowId is the wrong approach. What if the database is modified and the ID becomes invalid? You'd have to check every ID and regenerate when an invalid ID comes up.
Instead, you should use a LIMIT clause in your SELECT statement with a random number less than the number of rows in the table.
No need to generate random ids first. Just insert your rows, making sure you have the questionId column.
When you want read your database. Do something like quizid = rand() ....
After that you select the row with quizid in your database
SELECT * FROM quiztable WHERE questionId = quizid
Something like that will give you a random row from your database.
I think you get the point.

how to read a specific column from existing SQLiteBatabase in Android?

I have a database having 28 rows just for saving app data. My goal is to read One specific column (not one value) from it.
However, I don't want to read all columns at once, because it's slow as I have blob's in db too. Instead, I'd like to read just one column at a time, separately. Can you plese help me to solve this problem.
If you want to read one ROW do something along those lines:
SELECT * FROM tablename WHERE id='5' LIMIT 1;
where 'id' is supposer do be in the table 'tablename'
or else try something like this:
SELECT datafield FROM tablename WHERE 1;
which will give you all the 'datafield' data from the table (ie. a Column).
If this doesn't help you at all then post the code you are already using.

Android's SimpleCursorAdapter with queries using DISTINCT

Here's an interesting question that I'm shocked hasn't been asked more often on the internet. Android's CursorAdapters are extremely useful once you get a ContentProvider up and running and learn how to use it, but they are limited due to their requirement on having the _id field as part of their query (an error is thrown without it). Here's why:
My specific problem is that I have two spinners: One spinner should contain unique "category" names from the database, and the other should populate with all the database entries from the selected "category" (category being the column name, here). This seems like a pretty simple setup that many programs might use, no? Trying to implement that first spinner is where I've run into problems.
Here's the query that I would like for that first spinner:
SELECT DISTINCT category FROM table;
Making this query throws an error on CursorAdapter because the _id column is required as part of the query. Adding the _id column to the projection naturally returns every row of the table, since you're now asking for distinct id's as well, and every id is distinct (by definition). Obviously I would rather see only one entry per category name.
I've already implemented a work around, which is to simply make the query above and then copy the results into an ArrayAdapter. My reason for this post is to see if there was a more elegant solution to this odd little problem and start a discussion on what I could be doing better. Alternate implementation suggestions, such as using different kinds of controls or adapters, are very welcome.
Here's the query I ended up with:
SELECT _id, category FROM table_name GROUP BY category;
I used the rawQuery() function on an SQLiteDatabase object to carry this out. The "GROUP BY" piece was the key towards getting the right results, so thanks to user Sagar for pointing me in the right direction.
Do consider user Al Sutton's answer to this question as well, as it may be a more elegant solution to this problem.
Thanks everyone!
I'd suggest having a separate table with just _id & category in it which contains one row per unique category. Your data rows can then replace their category field with the _id from the category table.
This has the added advantage you can change the category in the categories table and it will show up in all entries in that category.
SELECT DISTINCT category,_id FROM table GROUP BY category;
I think this should give you what you are looking for. The results from this will be the category, and the first _id for that category. You can ignore the second column (_id).
You can specify an _id field alias in your select statement that is just a constant value, for example:
SELECT DISTINCT 0 _id, category FROM table;
Better yet, I solved this problem by using:
SELECT DISTINCT category AS _id FROM table
Now, you have a column with the name _id which has what you want in it

Categories

Resources