I'm using ORMLite in my android app and I searched a lot but I don't have a clear way to do what I want. I would like to know if I can change the starting value of a generatedId value. For example now it starts in 1 and I would like to start in 010001 or 020001. I noticed that we have sqlite_sequence table inside. Must I change that value or must I do it in another way?.
Thank you very much!
For example now it starts in 1 and I would like to start in 010001 or 020001.
In general I take the opinion that you should not do something like this. The id field is designed to be an identity and your application should not depend on the values being anything particular.
If you need some specific number then I would generate it externally to the database and add it as another field on the items. So the id can float and be whatever the DB wants and you can have your special ID that you control.
Finally I solved it. Here is the trick:
#DatabaseField(allowGeneratedIdInsert = true, generatedId = true, columnName = ID)
private int id;
I allow generatedIdInsert so I can set manually my Id and if I don't generate it manually it will be autogenerated. After that I do a first explicit insert.
daoObject.setId(010000);
dao.create(daoObject);
Now when I insert a new object the generatedId will start in 010001.
I hope that this little trick help somebody.
You have to have the AUTO_INCREMENT = 0100001; in your CREATE TABLE but as this is most certainly generated code by ORMLite you would have to force it by using the ORMLite annotation.
#DatabaseField(generatedId = true,
columnDefinition = "INTEGER PRIMARY KEY AUTOINCREMENT = 0100001")
private int id;
Related
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.
SugarORM, in my opinion, is the easiest SQLite library to use and proven to be extremely helpful for junior Android developer like me. SugarORM automatically creates the table and add an AUTO_INCREMENT id column for every java class extending SugarRecord.
Inserting a new row can be as easy as someJavaObject.save(). But how can I get the inserted id once that row is inserted? In PHP I can do something like $id = mysql_insert_id(); after insertion.
I understand that I can just get the id of last row in the table. But the insertion of new row can somehow be very unpredictable. Let's say I have an activity and a service inserting a new row at the same time, I want to avoid getting the wrong id.
Thanks in advance for any help.
The save() method has to return it. Like:
long id = someJavaObject.save()
or try:
someJavaObject.save()
long id = someJavaObject.getId();
As Stan mentioned, save actually returns the id as long value. I used this by today.
If you want to use this for a freshly created row you may do something like this:
Region reg2 = new Region("Graz", 20, 20);
reg1.setId(reg1.save());
I'm new to app development using SQLite and Sugar ORM on Android, and have tried to read through the Sugar ORM documentation, but didn't find anything for how to update a saved object in SQLite. Can I still save the object after changing its properties? something like:
Customer myCustomer = (Customer.find(Customer.class, "id = ?", id)).get(0);
myCustomer.setName("new name");
myCustomer.setAddress("new Address");
myCustomer.save(); // is this okay for updating the object?
the save() method won't create another new object while leaving the old entry untouched, right?
Your code should update the row without issue.
From the docs - Update Entity:
Book book = Book.findById(Book.class, 1);
book.title = "updated title here"; // modify the values
book.edition = "3rd edition";
book.save(); // updates the previous entry with new values.
It will update your entity. The Sugar ORM overwriting your existing e.g Name and updated it with "new name" after the save() method call.
Updating a saved object is pretty straightforward.
Retrieve the object;
Object object= Object.findById(Object.class, ID);
Set the attributes you need to;
object.setAttr("new value");
Then finally call save;
object.save();
Alternatively, as someone mentioned above one can choose to use update() which works slightly differently and would ideally be used when changing several attributes;
First create the object and set the necessary attributes;
Object object= new Object();
object.setAttr("some data");
Then set an ID for the Object that ideally already exists in the database in order to target that item for replacement;
object.setID(ID);
And finally;
object.update();
Save and Object methods are completely different and both are really useful.
If you have an object and you say:
Object.save();
That will override all of the other fields as well for example:
column1 column2
1 1
if in your object you have only set column1 corresponding field a number like 2 you will get:
Object.save();
column1 column2
2 NULL
Object.update();
column1 column2
2 1
You don't need to use .setId() explicitly to get update working it looks for a unique item if it's found it will update that,if not it will create a new row.By default an auto increment ID column is added to each of your tables and used as unique ids for update.If you need your own fields to be unique use:
#Unique
String MyID
or for multiple of the same thing you can use:
#MultiUnique("MyFirstID,MySecondID")
public class MyClass extends SugarRecord {...
which both are name of your fields in the table.
In my Android project, ORMLite is functioning as a cache. I'm downloading data from a web server and placing it in the database. I'm calling createOrUpdate on my objects, but duplicates are appearing in the database. The database entries are identical except for the primary key (which is simply an auto incremented integer). I think that since my second object doesn't yet have a primary key, ORMLite considers the two as being different, even though every other field is identical.
Does anyone know if this is true?
You should not be calling createOrUpdate unless your object already has an id field set. The way ORMLite determines whether or not it exists in the database is to do a query-by-id on it. The code does:
ID id = extractId(data);
// assume we need to create it if there is no id <<<<<<<<<<<<<<<<<<<<<<<
if (id == null || !idExists(id)) {
int numRows = create(data);
return new CreateOrUpdateStatus(true, false, numRows);
} else {
int numRows = update(data);
return new CreateOrUpdateStatus(false, true, numRows);
}
I'll expand the javadocs to explain this better. They are very weak there. Sorry. I've updated them to be:
This is a convenience method for creating an item in the database if it does not exist. The id is extracted from the data argument and a query-by-id is made on the database. If a row in the database with the same id exists then all of the columns in the database will be updated from the fields in the data parameter. If the id is null (or 0 or some other default value) or doesn't exist in the database then the object will be created in the database. This also means that your data item must have an id field defined.
It seems like you manually need to extract the id of the already existing entry and then update the database, based on your actual unique identifier. Example with unique URLs:
CacheItem newEntry = fetchEntry("..."); // fetch it here
List<CacheItem> existing = mDao.queryForEq("url", newEntry.getUrl());
if (existing.size() > 0) {
int id = existing.get(0).getId();
newEntry.setId(id);
mDao.update(newEntry);
} else mDao.create(newEntry);
set your primary key for it to work normally.
#DatabaseField(columnName = "id",uniqueIndex = true)
private int id;
Worked for me. Exceptions are thrown at background but it works :D