I am using android room to store my records. Each record contains main 2 fields: date presented as String and corresponding number of phone unlocks for that day as integer.
I was wondering what is the best way to increment that number in database each time the user unlocks the phone.
Is there a better way than query for current number of unlocks in database, increment it by 1 and update the field?
Is there some clever way to just increment value without making a query first to know exact value?
Try with a simple update query:
#Query("UPDATE TableName SET FieldToIncrement = FieldToIncrement + 1 WHERE ID = :id")
public abstract void incrementValue(long id);
Just annotate field , that you want increment this annotation
#PrimaryKey(autoGenerate = true) private final int id;
And when user unlock phone , just create a new instance of your #Entity.
For the id in constructor of your #Entity pass 0 , Room automatically generate the next value.
Related
I'm using moor_flutter to persist my data in an SQLite database in my Flutter application. One of my columns for the sake of argument looks like this:
class Clients extends Table {
// Autoincrement automatically sets this to be a primary key
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text().withLength(min: 1, max: 60)();
TextColumn get phone => text().withLength(min: 1, max: 50)();
}
I'm looking to store an array of clients I have recently opened in a List of length 10. Every time somebody would interact with that client, the list would place that client on the top of the list and remove the last one so that it would always be 10. It could also reorder them to bubble one from the middle, up to the top.
In any case, what I'm looking to do is create a new table called "Recents" which would have a single field of type List like so:
class Recents extends Table {
List<Client> recents => List<Client>[10].withLength(min: 0, max:10)()();
}
I couldn't find anything usable on the interwebz so here we are StackOverflowers! How would you solve this conundrum?
There isn't any good way in the SQLite database to store a list in a single column of a table the natural way is to store list items in the other table which every single row represents a single item of your list and connect that with a relation to other tables for example for if consider a scenario which we have a Users table and each user entity have a list of phone numbers that associated with we can store all the users in the Users table and store all the phone numbers in other table and we will create a userId column in the phone numbers table and we add a userId for each phone number that indicates this phone number is associated with the specific user with unique userId "the relation" and this way when we want to get a phone numbers list for a user we can query phone numbers table for the phone numbers that have specific userId
Users Table
UserId
Username
0
A
1
B
3
C
Phone Numbers Table
Id
PhoneNumber
UserId
0
+099888
0
1
+121181288
0
2
+31188218
0
3
+121221295
1
4
+9852121328
2
5
+2512165
2
the second way you can handle this scenario is converting your List to a type that is supported in SQLite for example convert your list items to a JSON string and insert that as text into a column of a user table and when you read this field you can convert it to a List of items, Most of ORM's will provide a tool that helps you with us a secnario
for a moor, you can use a converter here is the link to the documentation
https://moor.simonbinder.eu/docs/advanced-features/type_converters/
But notice that this approach is less flexible for example you
can't query on the phone numbers and it has a bad effect on performance
I am making an attendance management system. I want to user sqlite database for android . everything is good but how can I insert attendance in database for each and every new date . Example : today is 16th july I am taking todays attendance but tomorrow also I need attendance for tomorrow data and so on through the month and years .
You can create user table with UserID , Name and ect columns
and attendance table with Date,FOREIGN KEY(UserID) REFERENCES UserTable(UserID) ,Attendance (INTEGER)( 1->true and 0->false) ,EntranceTime and ect
You can refer below table structure.
Columns:
id : store unique id, primary key
date: store date (Y-m-d)
userId : userId
isAttended : 0 or 1
If there is more info(e.g. departments, sections) you want to store then of course you can.
Notes: sqlite database cannot accepts boolean values so you need to store it as false = 0 or true = 1.
I'm having an error on using update with using cast (column1 as int) query. I need a VARCHAR column for our data seurity (encrypting our data). I can't find an answer on google. Please help me. Thanks
If your column1 were declared as VARCHAR, then most likely its affinity means that the actual underlying storage class in SQLite is TEXT. If you have the need to store integers, then you should have declared this column as INT or INTEGER. That being said, the following update might work:
UPDATE tickets SET is_send = 1;
This would work if SQLite can do the conversion from integer to string for you. If not, then use:
UPDATE tickets SET is_send = '1';
Or, if you want to cast, then use:
UPDATE tickets SET is_send = CAST('1' AS TEXT);
In general, if you have the need to store numbers, use a number column, and vice-versa for text.
Is there any way to set a field auto increment with android Room?
There is a table which contains 3 fields: id, name, order. And I want the field order to be an auto increment field.
#PrimaryKey(autoGenerate = true)
private long id;
private String name;
private int order;
Set field as primary key can achieve this, but there is already one id.
I can handle the order by myself, maybe set the field order as unique is much safer. But I prefer letting the db do it automatically. How can I do that?
Currently, Android doesn't support auto increment. Even for primary key, its not auto-increment, its auto-generate. It won't be serial numbers. It will generate a random hash numbers.
Auto generate is supported only for primary key but not for any normal column
#PrimaryKey(autoGenerate = true)
Annotate your Entity class with the code above.
I currently have an app where I store user data in a SQLite database, and one of my fields is a User ID. I would like to add an option to auto-generate User IDs in an mmddyyXXX format, where XXX is a sequential number per user that resets every day.
Does anyone know how I would approach this? I looked at some of the other similar questions, but they don't seem to be helpful.
This is not complicated at all. If your'e similar with SQLite in android just take the date and the userId using a SELECT and generate that string yourself.
If the XXX is not the userId just save another table containing 'tokens' for users. every userId would have a 'token'.
Every new day just change the contents of this table.
I believe you could use a TRIGGER that will generate the userid when a row is inserted.
The following may suit :-
CREATE TRIGGER IF NOT EXISTS newuserid AFTER INSERT ON users
BEGIN
UPDATE users SET userid = strftime('%m%d',date('now'))||substr(strftime('%Y',date('now')),3)||
(
SELECT CAST(substr('000',1,3-length(count()+1)) AS TEXT)||CAST((count()+1) AS TEXT)
FROM USERS
WHERE substr(userid,1,6) = strftime('%m%d',date('now'))||substr(strftime('%Y',date('now')),3)
)
WHERE userid IS NULL;
END;
The trigger is named newuserid
userid is the column for the auto-generated id. The above relies upon it being NULL so it cannot be a PRIMARY INDEX.
There is no reliance upon other columns.
Testing
Starting with an empty table :-
Inserting 4 rows using INSERT INTO users VALUES(null,'This is a new user'); results in :-
To check for another date the rows are adjusted from 041018??? to 040918??? as per :-
4 more rows are inserted using INSERT INTO users VALUES(null,'This is a new user');, resulting in :-
Note this answer isn't intended to be fail-safe but rather the basis of the concept for the answer.