android: cache gson data in sqlite database - android

I want to use a local sqlite database to cache all gson objects. Therefore I created some Gson classes like this one:
package com.getbro.bro.Json;
import com.google.gson.annotations.SerializedName;
public class User extends Item {
public User(String Sex, String UserName, String[] Followed){
this.Sex = Sex;
this.UserName = UserName;
this.Followed = Followed;
}
#SerializedName("sex")
public String Sex;
#SerializedName("username")
public String UserName;
#SerializedName("followed")
public String[] Followed;
#Override
public String toString() {
return UserName;
}
}
Now I want to use this class as Sugar ORM model, but then, I have to rewrite the constructor to something like this:
public User(Context c, String Sex, String UserName, String[] Followed){
this.Sex = Sex;
this.UserName = UserName;
this.Followed = Followed;
}
How can I get Gson to use this "special" constructor and select the wright context?

With 1.3 release, sugar doesn't require a Context parameter in the constructor. So, it makes easy for Gson classes to use Sugar.
Specifically with Gson, you could use their custom serializers in case you don't have the default constructor. More details here.. https://sites.google.com/site/gson/gson-user-guide#TOC-Custom-Serialization-and-Deserialization

Related

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

Auto increment primary key in sugar orm

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();

Realm query with List

I'm using realm to store my data on Android. Awesome framework! Now the only problem I'm now having is:
I got a array list strings with id's of Countries in my database.
Now I retrieve my Drinks that contains a relationship to countries.
Is there a way that I could to do a query like this:
String [] ids;
realm.where(Drinks.class).equalsTo("country.id", ids);
Something like that?
Or do I really need to do a query to get me all drinks and then filter the list manually?
EDIT:
My classes:
public class Drinks extends RealmObject {
#PrimaryKey
private String id;
private String name;
private Country country;
}
public class Country extends RealmObject {
#PrimaryKey
private String id;
private String name;
}
What you want to do is possible with link queries in theory (searching for "country.id"), however link queries are slow. Also you'd need to concatenate a bunch of or() predicates together, and I would not risk that with a link query.
I would recommend using the following
public class Drinks extends RealmObject {
#PrimaryKey
private String id;
private String name;
private Country country;
#Index
private String countryId;
}
public class Country extends RealmObject {
#PrimaryKey
private String id;
private String name;
}
And when you set the Country in your class, you also set the countryId as country.getId().
Once you do that, you can construct such:
RealmQuery<Drinks> drinkQuery = realm.where(Drinks.class);
int i = 0;
for(String id : ids) {
if(i != 0) {
drinkQuery = drinkQuery.or();
}
drinkQuery = drinkQuery.equalTo("countryId", id);
i++;
}
return drinkQuery.findAll();
Since the Realm database has added RealmQuery.in() with the version 1.2.0
I suggest using something like this.
//Drinks
public class Drinks extends RealmObject {
#PrimaryKey
private String id;
private String name;
private String countryId;
//getter and setter methods
}
//Country
public class Country extends RealmObject {
#PrimaryKey
private String id;
private String name;
//getter and setter methods
}
The code to use inside activity/fragments to retrieve drink list
String[] countryIdArray = new String[] {"1","2","3"} //your string array
RealmQuery<Drinks> realmQuery = realm.where(Drinks.class)
.in("countryId",countryIdArray);
RealmResults<Drinks> drinkList = realmQuery.findAll();
In latest version of Realm 7+, you can use anyOf to match a field against a list of values.
anyOf("name", new String[]{"Jill", "William", "Trillian"})
in older versions, use in instead of anyOf and with kotlin use oneOf instead of in.
see this issue
To match a field against a list of values, use in. For example, to find the names “Jill,” “William,” or “Trillian”, you can use in("name", new String[]{"Jill", "William", "Trillian"}). The in predicate is applicable to strings, binary data, and numeric fields (including dates).
Doc.-> https://realm.io/docs/java/latest#queries

Android - read a C structure into android

I have a C structure with 2 attributes, say the content and the val
How do I read this into an android file? Does android support any structure?
My structure is like
struct data[] = {
{"aakash", 2260},
{"anuj", 1}}
How to read such structures in android?
For Android supports Java Platform. Structure is not belong to Java. You Can Achieve the Same with Pojo Classes.
Public Class MyData {
private String username;
private double points;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public double getPoints() {
return points;
}
public void setPoints(double points) {
this.points = points;
}
public MyData(String username,double points)
{
this.username = username;
this.points = points;
}
}
MyData[] data = new MyData[2];
data[0]= new MyData("aakash", 2260);
data[1]= new MyData("anuj", 1);
If the structure is as simple as a String and an Integer, and you really wanna write to file using C, read using Java. You can use a Plain Text File, Use a CSV format to store the values. It'll be easy to read/write in both languages.
You can't store those objects into a binary file and have Java read it effortlessly. Although, If the file was created using Java, then it should be easy.

GSON does not cast Json string to class

I am trying to convert JSonObject string to some specific classes.
MyClass mc= new Gson().fromJson(jo.toString(),MyClass.class);
After this step all values of mc is null.
Value of the jo.toString() :
{
"__type":"MyClass:#MyProject.Model",
"ID":1,
"Comment":"First Record",
"SubClassID":534,
"Active":true,
"Date":"\/Date(1323087840000+0200)\/"
}
MyClass.java has attributes ID, Comment...
Thanks Regards...
MyClass.Java:
public class MyClass extends ABase
{
private String _Comment;
public String getComment(){
return _Comment;
}
public void setComment(String value){
_Comment = value;
}
private Integer _ID;
public Integer getID(){
return _ID;
}
public void setID(Integer value){
_ID = value;
}
private java.util.Date _Date;
public java.util.Date getDate(){
return _Date;
}
public void setDate(java.util.Date value){
_Date = value;
}
}
The problem is that the JSON element names do not match the Java field names, and no explicit alternative name-mapping configuration was provided to Gson.
Possible Solutions:
Change the Java field names to exactly match the JSON element names. This of course isn't always possible, e.g., when the JSON element names include characters or formats not valid for Java field names.
Change the JSON element names to exactly match the Java field names. This of course isn't always possible, e.g., when the JSON is from a third party.
Provide Gson with name-mappings, using either the #SerializedName annotation, or a FieldNamingPolicy.

Categories

Resources