Auto increment primary key in sugar orm - android

How can define an auto increment primary key in Sugar model?
Do Sugar automatically creates unique ID for each record
import com.orm.SugarRecord;
public class Customers extends SugarRecord {
int id; // this field must be auto increment primary key
String name;
String tel;
String mobile;
String address;
String create_date;
public Customers(){}
public Customers(int id, String name, String tel, String mobile, String address, String create_date){
this.id = id;
this.name = name;
this.tel = tel;
this.mobile = mobile;
this.address = address;
this.create_date = create_date;
}
}

You may create a custom table my annotating your class with "#Table", but you should create a long type of "id" for the ORM to work with. The best way would be to let sugar do all the work.
Sugar will create an id field (you do not need to include in your class) and you may access it using "getId()" something like:
Customers customer = Customers.findById(Customers.class, 1)
long customer_id = customer.getId();

Related

Android Firebase, Unable to fetch the data

I created a family tree application on java and mysql database. Now I am testing an android app for the same. So I converted my mysql database file to JSON format and uploaded it to firebase. When I am inserting records on it, it is working perfectly fine but when I try to fetch the data it is showing the error:
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int
at com.google.android.gms.internal.firebase_database.zzkt.zzb(Unknown Source:180)
What should be the problem? I tried deleting the data from the database which I uploaded through JSON file and then inserted records directly from app into database and fetch them, it worked fine but when I am adding record from JSON file only then It is creating problem.
here is the code from the app for fetching data:
public void clicked(){
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<Family> FamilyList = new ArrayList<>();
for (DataSnapshot adSnapshot: dataSnapshot.getChildren()) {
Family f = adSnapshot.getValue(Family.class);
FamilyList.add(f);
// adsList.add(adSnapshot.getValue(Family.class));
}
Toast.makeText(MainActivity.this, "Total Records: "+FamilyList.size(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Family Model Class:
public class Family {
int id;
String name;
String fatherName;
int fid;
String city;
String state;
public Family(int id, String name, String fatherName, int fid, String city, String state) {
this.id = id;
this.name = name;
this.fatherName = fatherName;
this.fid = fid;
this.city = city;
this.state = state;
}
public Family()
{
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public int getFid() {
return fid;
}
public void setFid(int fid) {
this.fid = fid;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Here is the JSON Record Sample
It is the records which I entered through App
I think the converted JSON treated id and fid as String, while in mySQL they are int. (am I correct?)
Tell me if any other code is needed.
The problem relies on here
Family f = adSnapshot.getValue(Family.class);
you are trying to get data in an inappropriate type.
You should correct this by checking Family.class and check if the values there are the same as they are in your database structure in firebase, it will be helpful if you put your database structure here, or some images.
Check if for example in Family.class you have in your variable types the same as they are in firebase, with the same name also.
So for example if in firebase there is an string called name you should have in your constructor inside Family.class the same type and name.
String name;
and in Firebase your json key should be name too.
For instance, check this
your Family class for example should have the variables with the same name and type as your database.
Also check, if the value in firebase has "" is an String type and in your POJO you should have a variable with the type String for what you are trying to access, but if the value dosnt have "" it should be a long , int, double or any type of number.
EDIT: check this structure
It has all the values types as String, but in your Family.class you have the values right for this type of structure.
you should change your database at firebase so all your types matches with the ones in your Family.class, either way it won't fetch your values
Note: if you want to fetch all your values like they are at the first image, just change in Family.class from this:
int id;
String name;
String fatherName;
int fid;
String city;
String state;
to this:
String id;
String name;
String fatherName;
String fid;
String city;
String state;
Also change your constructor types and everything to match all Strings
The thing is that firebase creates unique IDs for each element in your database structure, and the types imported from your MySQL database are not the same as the firebase ones, I suggest you to either change your Family.class variable types as I mentioned above, or replicate your MySQL database with firebase and the same variable types.
This is happening because you have a variable of integer datatype in your model but you are returning String from Firebase... either convert your variable to string or return integer from firebase....
Both model and Firebase variable should be of a same data type.
As per your below error:-
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int at com.google.android.gms.internal.firebase_database.zzkt.zzb(Unknown Source:180)
I think, you need to check somewhere you tried to store value in int which is store in firebase in string.
So first check it and if necessary to cast then casting your value using Integer.parseInt or Integer.valueof
for example,
Integer.valueOf(dataSnapShot.getValue());
or
Integer.parseInt(dataSnapShot.getValue());
For more understanding this you can also refer stack overflow's below links:
Firebase DatabaseException: Failed to convert value of type java.lang.Long to String
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to double
Firebase android error "Failed to convert value of type "

How to store a object array by using Room in Android?

I want to cache a song-list in my app, the Song-list structure is like below:
#Entity
public class Songlist {
String _id;
String desc;
List<SongDesc> songWithComment;
.....
public static class SongDesc {
String comment;
Song song;
}
}
#Entity
pulbic class Song {
String name;
String type;
......
}
The lib of operating sqlite3 is android.arch.persistence.room, but it dosen't allow object references in a table.Is there any way to cache a song-list by using Room in Android?
Also if you want to store some custom objects, you can use #Embedded annotation like in example bellow :
class Address {
public String street;
public String state;
public String city;
#ColumnInfo(name = "post_code")
public int postCode;
}
#Entity
class User {
#PrimaryKey
public int id;
public String firstName;
#Embedded
public Address address;
}
If you want to save an ArrayList of some type into the database, you shuld use TypeConverter to convert the ArrayList from and into a simpler recognizable type to the database engine, like a String.
See this:
Android Room Database: How to handle Arraylist in an Entity?
and https://commonsware.com/AndroidArch/previews/room-and-custom-types

How do I set a unique primary key in Realm?

How do I set a unique primary key in Realm in Android? The Realm documentation says I cannot use anything but String or int/long, so is UUID type is out of the question too? What if I have items with the same name?
e.g.
public class GroceryItem extends RealmObject {
#PrimaryKey
private long id; <--- how can I make this unique without UUID?
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} }
Realm doesn't support any autoincrement for primary keys. Visit docs for more information about this. So, you are to handle it by yourself.
1) Use should use UUID. You can also get long, int or String value from it:
long: UUID.randomUUID().getMostSignificantBits();
int: (int) UUID.randomUUID().getMostSignificantBits();
String: UUID.randomUUID().toString();
2) Or you can query some data from your database and apply some rules to generate a new key. For example, query for the last element and increment it's primarykey. But that's not ideal way.

Manually updating a foreign key.

I am pretty much aware of the absence of foreign keys in Realm. But I encountered this issue. I receive data in a normalised way and I have to figure out how to properly persist the relations.
Example:
class User{
private int id;
private Email email;
}
class Email{
private int id;
private String address;
}
And I receive something like:
{user={id:1, emailId:1}}
How can I store this type of data in my existing realm object ?
You will have to parse the JSON yourself to setup the links. From your description it isn't clear if you User and Email is already in Realm, but if that is the case I would do something like this:
class User{
#PrimaryKey
private int id;
private Email email;
}
class Email{
#PrimaryKey
private int id;
private String address;
}
JSONObject json = new JSONObject("{id:1, emailId:1}");
realm.beginTransaction();
User user = realm.where(User.class).equalTo("id", json.getInt("id")).findFirst();
Email email = realm.where(Email.class).equalTo("id", json.getInt("emailId")).findFirst();
user.setEmail(email);
realm.commitTransaction();

Foreignfield no value Ormlite

I would like to ask assistance with using Ormlite. I have a class(Node.class) with fields-
#DatabaseField(generatedId = true)
public int id;
#DatabaseField
String path;
#DatabaseField
String label;
#DatabaseField
Date lastModified;
#DatabaseField
String resourceType = NODE_TYPE_ENTRY;
#DatabaseField
int status = NODE_STATUS_FRESH;
#DatabaseField
boolean leaf = false;
#DatabaseField
UUID uuid;
#ForeignCollectionField(eager = false)
public ForeignCollection<Node> children;
#ForeignCollectionField(eager = true)
public ForeignCollection<Property> properties;
#DatabaseField(foreign = true,index=true)
Node parent;
and another class(Classroom.class) with fields
#DatabaseField(generatedId=true)
int id;
#DatabaseField
String name;
#DatabaseField
String value;
#DatabaseField(foreign=true,index=true)
Node node;
My problem is that, when I add a property , the field node is always 0 and the result should be the id of the created node.
Hoping for your help.
Thanks
I think #k3v1n4ud3's comment is pointing you to the right answer.
You first need to insert the node into the Node table so the id field in the Node can be auto-generated and set on the node object. Then you can assign it to the node field in the Classroom so when you insert Classroom into the database, the node_id field will be non-0.
To quote the docs on "foreign objects" in ORMLite:
When you are creating a field with a foreign object, please note that the foreign object will not automatically be created for you. If your foreign object has a generated-id which is provided by the database then you need to create it before you create any objects that reference it.

Categories

Resources