Fetching objects with Collections - android

I'm trying to list objects that have an inner Collection. I can save and retrieve objects just fine, but when I do:
parentRepo.findAll()
Only the last object has it's child object listed, others has an empty collection.
Parent model
#ForeignCollectionField(eager = false)
private Collection<Child> childs;
Child model
#DatabaseField(foreign=true,foreignAutoRefresh=true)
private Parent parent;
eager true or false doesn't make any difference. If i query a child and get its parent, I can get it's children as well. What am I missing?
Edit:
It's working for the modeling that I made. My mistake was that I need a Many-to-many relation between parent and child. I made a quick research and what I need is an intermediate model to achieve this. I'll close this question and will try to made this many-to-many relation between my models.

I solve my Many-to-Many relationships like this:
This is an example from an ongoing project. I have a Many-to-Many relationship between Preparation and GlideWax. To solve it I use thee classes: Preparation, GlideWax and PreparationGlideWax. PreparationGlideWax represents the connections between the the other classes, just like the way you usually solve many-to-many relationships with a table that is a "link" between the tables in the relationship. As you can see GripWax and Structure also has a Many-to_many relationship to preparation. Here is the code:
GlideWax.java
#DatabaseTable(tableName = "glide_waxes")
public class GlideWax {
#DatabaseField(id = true)
private int id;
#DatabaseField(canBeNull = false)
private String name;
#DatabaseField
private String description;
#DatabaseField(canBeNull = false)
private int inUse;
#DatabaseField(foreign=true)
private WaxBrand waxBrand;
#DatabaseField(foreign=true)
private GlideWaxType glideWaxType;
#ForeignCollectionField
private ForeignCollection<PreparationGlideWax> preparationGlideWaxes;
#ForeignCollectionField
private ForeignCollection<TestSessionGlideWax> testSessionGlideWaxes;
public GlideWax() {
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getInUse() {
return inUse;
}
public void setInUse(int inUse) {
this.inUse = inUse;
}
public WaxBrand getWaxBrand() {
return waxBrand;
}
public void setWaxBrand(WaxBrand waxBrand) {
this.waxBrand = waxBrand;
}
public GlideWaxType getGlideWaxType() {
return glideWaxType;
}
public void setGlideWaxType(GlideWaxType glideWaxType) {
this.glideWaxType = glideWaxType;
}
public ForeignCollection<PreparationGlideWax> getPreparationGlideWaxes() {
return preparationGlideWaxes;
}
public void setPreparationGlideWaxes(ForeignCollection<PreparationGlideWax> preparationGlideWaxes) {
this.preparationGlideWaxes = preparationGlideWaxes;
}
public ForeignCollection<TestSessionGlideWax> getTestSessionGlideWaxes() {
return testSessionGlideWaxes;
}
public void setTestSessionGlideWaxes(ForeignCollection<TestSessionGlideWax> testSessionGlideWaxes) {
this.testSessionGlideWaxes = testSessionGlideWaxes;
}
}
Preparation.java
#DatabaseTable(tableName = "preparations")
public class Preparation {
#DatabaseField(generatedId=true)
private int id;
#ForeignCollectionField
private ForeignCollection<PreparationGlideWax> preparationGlideWaxes;
#ForeignCollectionField
private ForeignCollection<PreparationGripWax> preparationGripWaxes;
#ForeignCollectionField
private ForeignCollection<PreparationStructure> preparationStructures;
#DatabaseField(foreign=true, canBeNull = false)
private SkiPair skiPair;
#DatabaseField(foreign=true, canBeNull = false)
private SkiTester skiTester;
#DatabaseField(foreign=true)
private Rfid rfid;
#DatabaseField(foreign=true, canBeNull = false)
private TestSession testSession;
#ForeignCollectionField
private ForeignCollection<Measurement> measurements;
public Preparation() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ForeignCollection<PreparationGlideWax> getPreparationGlideWaxes() {
return preparationGlideWaxes;
}
public void setPreparationGlideWaxes(ForeignCollection<PreparationGlideWax> preparationGlideWaxes) {
this.preparationGlideWaxes = preparationGlideWaxes;
}
public ForeignCollection<PreparationGripWax> getPreparationGripWaxes() {
return preparationGripWaxes;
}
public void setPreparationGripWaxes(ForeignCollection<PreparationGripWax> preparationGripWaxes) {
this.preparationGripWaxes = preparationGripWaxes;
}
public ForeignCollection<PreparationStructure> getPreparationStructures() {
return preparationStructures;
}
public void setPreparationStructures(ForeignCollection<PreparationStructure> preparationStructures) {
this.preparationStructures = preparationStructures;
}
public SkiPair getSkiPair() {
return skiPair;
}
public void setSkiPair(SkiPair skiPair) {
this.skiPair = skiPair;
}
public SkiTester getSkiTester() {
return skiTester;
}
public void setSkiTester(SkiTester skiTester) {
this.skiTester = skiTester;
}
public Rfid getRfid() {
return rfid;
}
public void setRfid(Rfid rfid) {
this.rfid = rfid;
}
public TestSession getTestSession() {
return testSession;
}
public void setTestSession(TestSession testSession) {
this.testSession = testSession;
}
}
PreparationGlideWax.java
#DatabaseTable(tableName = "preparation_glide_wax")
public class PreparationGlideWax {
#DatabaseField(generatedId=true)
private int id;
#DatabaseField(canBeNull = false)
private int layer;
#DatabaseField(foreign=true, canBeNull = false)
private GlideWax glideWax;
#DatabaseField(foreign=true, canBeNull = false)
private Preparation preparation;
public PreparationGlideWax() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getLayer() {
return layer;
}
public void setLayer(int layer) {
this.layer = layer;
}
public GlideWax getGlideWax() {
return glideWax;
}
public void setGlideWax(GlideWax glideWax) {
this.glideWax = glideWax;
}
public Preparation getPreparation() {
return preparation;
}
public void setPreparation(Preparation preparation) {
this.preparation = preparation;
}
}

As I said in the edit, I'm able to load the child from parent just fine. My problem is that I need a many-to-many relation between my models. I'll accept this answer in two days.

Related

Two ArrayList compare and update one Arraylist or overwrite in android?

I have two Arraylist.
ArrayList<Thumbnail> videoList = new ArrayList<>();
List<Giphy> giphyList = new ArrayList<>();
How to Compare two Arraylist and update List<Giphy> data in ArrayList<Thumbnail> or another third Arraylist or overwrite in List data in ArrayList<Thumbnail>?
Here Two Class Thumbnail and Giphy. Giphy class is compare to Thumbnail. Giphy Class data stored in Arraylist and Arraylist data Update in ArrayList or data overwrite in ArrayList.
class Thumbnail{
private String gif,videoUrl;
private int id, thumbUp, thumbDown;
public Thumbnail (int id,String gif,String videoUrl,int thumbUp,int thumbDown){
this.gif = gif;
this.videoUrl = videoUrl;
}
public String getGif() {
return gif;
}
public void setGif(String gif) {
this.gif = gif;
}
public String getVideoUrl() {
return videoUrl;
}
public void setVideoUrl(String videoUrl) {
this.videoUrl = videoUrl;
}
public int getId() {
return id;
}
public int getThumbUp() {
return thumbUp;
}
public int getThumbDown() {
return thumbDown;
}
public void setId(int id) {
this.id = id;
}
public void setThumbUp(int thumbUp) {
this.thumbUp = thumbUp;
}
public void setThumbDown(int thumbDown) {
this.thumbDown = thumbDown;
}
}
}
#Entity
Class Giphy{
#Id
private long id;
private String url;
private int thumbUp;
private int thumbDown;
public Giphy(){
}
public Giphy(long id,String url,int thumbUp,int thumbDown){
this.id = id;
this.url = url;
this.thumbUp = thumbUp;
this.thumbDown = thumbDown;
}
public long getId() {
return id;
}
public String getUrl() {
return url;
}
public int getThumbUp() {
return thumbUp;
}
public int getThumbDown() {
return thumbDown;
}
public void setId(long id) {
this.id = id;
}
public void setUrl(String url) {
this.url = url;
}
public void setThumbUp(int thumbUp) {
this.thumbUp = thumbUp;
}
public void setThumbDown(int thumbDown) {
this.thumbDown = thumbDown;
}
}

Android Nested Objects and Retrofit2

I am reading a JSON like this:
{
"matches": [{
"id": 246119,
"utcDate": "2018-08-17T18:15:00Z",
"status": "FINISHED",
"homeTeam": {
"id": 298,
"name": "Girona FC"
},
"awayTeam": {
"id": 250,
"name": "Real Valladolid CF"
},
"score": {
"winner": "DRAW",
"duration": "REGULAR"
}
}]
}
I must say that the JSON is valid. I am consuming this JSON through an API. I can correctly read the properties "id", "utc" and "status", but I could not with "score", "awayTeam" and "homeTeam". I don't really know how to work those properties. I'd like to handle each propertie of score, awayTeam, and homeTeam individually, for example, I want to get just the name of awayTeam and homeTeam and the 2 properties of score.
This, is my code:
MainActivity
public class MainActivity extends AppCompatActivity {
private Retrofit retrofit;
private static final String TAG = "Football";
private RecyclerView recyclerView;
private ListaPartidosAdapter listaPartidosAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
listaPartidosAdapter = new ListaPartidosAdapter(this);
recyclerView.setAdapter(listaPartidosAdapter);
recyclerView.setHasFixedSize(true);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this, VERTICAL, true);
recyclerView.setLayoutManager(layoutManager);
retrofit = new Retrofit.Builder()
.baseUrl("http://api.football-data.org/v2/")
.addConverterFactory(GsonConverterFactory.create())
.build();
obtenerDatos();
}
private void obtenerDatos() {
footballdataService service = retrofit.create(footballdataService.class);
Call<PartidosRespuesta> partidosRespuestaCall = service.obtenerlistaPartidos();
partidosRespuestaCall.enqueue(new Callback<PartidosRespuesta>() {
#Override
public void onResponse(Call<PartidosRespuesta> call, Response<PartidosRespuesta> response) {
if(response.isSuccessful()) {
PartidosRespuesta partidosRespuesta = response.body();
ArrayList<Partido> listaPartidos = partidosRespuesta.getMatches();
listaPartidosAdapter.adicionarListaPartidos(listaPartidos);
}
else {
Log.e(TAG, "onResponse: " + response.errorBody());
}
}
#Override
public void onFailure(Call<PartidosRespuesta> call, Throwable t) {
Log.e(TAG, "onFailure: " + t.getMessage());
}
});
}
}
Now this is my interface. footballdataService
public interface footballdataService {
#GET("competitions/2014/matches")
Call<PartidosRespuesta> obtenerlistaPartidos();
}
This is PartidosRespuestas class
public class PartidosRespuesta {
private ArrayList<Partido> matches;
public ArrayList<Partido> getMatches() {
return matches;
}
public void setMatches(ArrayList<Partido> matches) {
this.matches = matches;
}
}
This, is the adapter.
public class ListaPartidosAdapter extends RecyclerView.Adapter<ListaPartidosAdapter.ViewHolder> {
private static final String TAG = "Football_Adapter";
private ArrayList<Partido> dataset;
private Context context;
public ListaPartidosAdapter(Context context) {
this.context = context;
dataset = new ArrayList<Partido>();
}
#Override
public ListaPartidosAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_partidos, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
holder.status.setText(p.getId());
}
#Override
public int getItemCount() {
return dataset.size();
}
public void adicionarListaPartidos(ArrayList<Partido> listaPartidos){
dataset.addAll(listaPartidos);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView status;
public ViewHolder(View itemView) {
super(itemView);
status = (TextView) itemView.findViewById(R.id.status);
}
}
}
And this.., is Partido class
public class Partido {
private String id;
private String utcDate;
private String status;
private EquipoCasa homeTeam;
private EquipoVisita AwayTeam;
private Puntaje score;
public String getId() {
return id;
}
public String getUtcDate() {
return utcDate;
}
public String getStatus() {
return status;
}
public EquipoCasa getHomeTeam() {
return homeTeam;
}
public EquipoVisita getAwayTeam() {
return AwayTeam;
}
public Puntaje getScore() {
return score;
}
public void setId(String id) {
this.id = id;
}
public void setUtcDate(String utcDate) {
this.utcDate = utcDate;
}
public void setStatus(String status) {
this.status = status;
}
public void setHomeTeam(EquipoCasa homeTeam) {
this.homeTeam = homeTeam;
}
public void setAwayTeam(EquipoVisita awayTeam) {
AwayTeam = awayTeam;
}
public void setScore(Puntaje score) {
this.score = score;
}
public class EquipoCasa {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class EquipoVisita {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Puntaje {
private String winner;
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
}
POJO classes of your code should this:
AwayTeam.java
//AwayTeam
public class AwayTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
PartidosRespuesta.java
//Object response
public class PartidosRespuesta {
#SerializedName("matches")
#Expose
private List<Match> matches = null;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
}
HomeTeam.java
//HomeTeam
public class HomeTeam {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("name")
#Expose
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Score.java
//Score
public class Score {
#SerializedName("winner")
#Expose
private String winner;
#SerializedName("duration")
#Expose
private String duration;
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
Edit:
#Override
public void onBindViewHolder(ListaPartidosAdapter.ViewHolder holder, int position) {
Partido p = dataset.get(position);
HomeTeam homeTeam = p.getHomeTeam();
String nameHomeTeam = homeTeam.getName();
}
And tool convert json to java code: http://www.jsonschema2pojo.org/
try
public class Puntaje {
public String winner;
public String duration;
}
It's seems like you've problems with your models. Use this link to convert your json to java object.

Nested object in Json

This is my JSON:
I need to access to extra_services and get the service_name.
I know I can do it directly using Gson but the problem is that I need to use getters and setters because I'm using an adapter inside of a recycler, how can I do that?
here is my adapter class where I need to get the service name
public class ExtraServicesAdapter extends RecyclerView.Adapter<ExtraServicesAdapter.ViewHolder> implements View.OnClickListener
{
private ArrayList<Business> businessList;
private Activity activity;
private int layoutMolde,idb;
public ExtraServicesAdapter(Activity activity, ArrayList<Business> list, int layout)
{
this.activity = activity;
this.businessList = list;
layoutMolde = layout;
}
#Override
public ExtraServicesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_services_basic, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
if(businessList.get(position).getExtra_services()==null)
{
holder.txtNameServiceBasic.setText("There's nothing to show");
}
holder.txtNameServiceBasic.setText(businessList.get(position).getExtra_services());
}
#Override
public int getItemCount()
{
return businessList.size();
}
#Override
public void onClick(View v)
{
}
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView txtNameServiceBasic;
public ViewHolder( View itemView)
{
super(itemView);
txtNameServiceBasic = (TextView) itemView.findViewById(R.id.txtNameServiceBasic);
}
}
}
and this is my class where are the getters and setters that I'm using
public class Business {
private Integer id,rating;
private String name, description, cover_url_string, logo_url_string, icon_default,business_name,cover_default,extra_services;
private Boolean status;
public Business(){}
public Business(Integer id,Integer rating,String business_name, String name, String description, String logo_url_string, String cover_default, String icon_default,String cover_url_string,String extra_services) {
this.id = id;
this.name = name;
this.business_name=business_name;
this.description = description;
this.logo_url_string = logo_url_string;
this.cover_url_string = cover_url_string;
this.rating=rating;
this.icon_default=icon_default;
this.cover_default=cover_default;
this.extra_services=extra_services;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getRating() {
return rating;
}
public String getBusiness_name() {
return business_name;
}
public void setBusiness_name(String business_name) {
this.business_name = business_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogo_url_string() {
return logo_url_string;
}
public void setLogo_url_string(String logo_url_string) {
this.logo_url_string = logo_url_string;
}
public String getIcon_default() {
return icon_default;
}
public String getCover_default() {
return cover_default;
}
public String getCover_url_string() {
return cover_url_string;
}
public String getExtra_services() {
return extra_services;
}
public void setExtra_services() {
this.extra_services=extra_services;
}
}
You can add an ExtraServices class that contains a list of ExtraService
ExtraService
public class ExtraService {
private String Id;
private String ServiceName;
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getServiceName() {
return ServiceName;
}
public void setServiceName(String ServiceName) {
this.ServiceName = ServiceName;
}
ExtraServices
public class ExtraServices {
private List<ExtraService> extraServicesList;
public List<ExtraService> getExtraServicesList() {
return extraServicesList;
}
public void setExtraServicesList(List<ExtraService> extraServicesList) {
this.extraServicesList = extraServicesList;
}
public void add(ExtraService extraService){
if(extraServicesList == null){
extraServicesList = new ArrayList<>();
}
extraServicesList.add(extraService);
}
And in your Business class add getters and setters of ExtraServices
private ExtraServices extraServices;
public ExtraServices getExtraServices () {
return extraServices;
}
public void setExtraServices (ExtraServices extraServices) {
this.extraServices = extraServices;
}
After you have to do the setter process and in your Adapter you should do something like this:
holder.txtNameServiceBasic.setText(businessList.get(position).getExtraServices().getExtraServicesList().get(posistion).getServiceName());

How can I save an object efficiently in Android

I have an object which I for now save using SharedPreferences like this:
public String getActiveTripString(Context con) {
return preferences.getString(ACTIVE_TRIP, "-1");
}
public void setActiveTripString(Context context, String string) {
setString(context, string, ACTIVE_TRIP);
}
public PSTrip getActiveTrip(Context context) {
String active = getActiveTripString(context);
PSTrip psTrip = null;
if (active.contentEquals("-1")) {
return null;
} else {
try{
psTrip = JsonUtil.jsonToObject(active, PSTrip.class);
}catch (Exception e){
Log.i("","getActiveTrip error is:" + e.getMessage());
}
return psTrip;
}
}
public void setActiveTrip(PSTrip psTrip, Context context) {
try{
setActiveTripString(context, JsonUtil.objectToJson(psTrip, PSTrip.class));
}catch (Exception e){
Log.i("","setActiveTrip error is:" + e.getMessage());
}
}
Where I have function as you can see, that create a json and then save it as a string in SharedPrefferences. But The object is BIG, and the more I add into it, the app start to be more laggy until it's unresponsive.
I also need to use this object in a lot of places, so I always need to call:
GetActiveTrip to get it, make my modifications, then SetActiveTrip to save it.
I'm looking for a more efficient way to save it. I tried with REALM, to save it in a database, but because my object is so big, and modified in a lot of places, I did not quite manage to make it work, Having to call Realm a lot just to add items in the database, in order to have managed database items, so I can add them in my object, and so on. Which also I think might be memory consuming. And It crashes a lot with realm exceptions.
Any other way I could do this? Is saving to a file more efficient than to Shared Preferences? As I saw in Android Monitor, analysing my traces, the GSON function that creates the JSON takes a lot of resources.
Any suggestions what I could use?
EDIT: My object:
public class PSTrip extends RealmObject {
private boolean valid;
private String type;
private String travel_mode;
#PrimaryKey
private String id;
private Owner_data owner_data;
private int distance;
private String name;
private double checkinLat;
private double checkinLng;
private double checkoutLng;
private double checkoutLat;
private String icon;
private String status;
private Destination destination;
private int checkout_time;
private int checkin_time;
private Route route;
private String owner;
private String vehicle;
private Flight flight;
#SerializedName("last_updated")
private int lastUpdated;
#SerializedName("steps")
private RealmList<TripStep> tripSteps;
private RealmList<Record> records;
#SerializedName("planned_route")
private Planned_Route plannedRoute;
private Group group;
private float emissions;
private Co2PerKm co2_per_km;
private int update_interval;
private boolean isRoaming = false;
public boolean getIsRoaming() {
return isRoaming;
}
public void setIsRoaming(boolean isRoaming) {
this.isRoaming = isRoaming;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public int getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(int lastUpdated) {
this.lastUpdated = lastUpdated;
}
public RealmList<TripStep> getTripSteps() {
return tripSteps;
}
public void setTripSteps(RealmList<TripStep> steps) {
this.tripSteps = steps;
}
public String getVehicle() {
return vehicle;
}
public void setVehicle(String vehicle) {
this.vehicle = vehicle;
}
public Flight getFlight() {
return flight;
}
public void setFlight(Flight flight) {
this.flight = flight;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTravel_mode() {
return travel_mode;
}
public void setTravel_mode(String travel_mode) {
this.travel_mode = travel_mode;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Owner_data getOwner_data() {
return owner_data;
}
public void setOwner_data(Owner_data owner_data) {
this.owner_data = owner_data;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Destination getDestination() {
return destination;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
public int getCheckout_time() {
return checkout_time;
}
public void setCheckout_time(int checkout_time) {
this.checkout_time = checkout_time;
}
public int getCheckin_time() {
return checkin_time;
}
public void setCheckin_time(int checkin_time) {
this.checkin_time = checkin_time;
}
public Route getRoute() {
return route;
}
public void setRoute(Route route) {
this.route = route;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public PSTrip() {
}
public PSTrip(String id) {
this.id = id;
}
public double getCheckoutLng() {
return checkoutLng;
}
public void setCheckoutLng(double checkoutLng) {
this.checkoutLng = checkoutLng;
}
public double getCheckinLat() {
return checkinLat;
}
public void setCheckinLat(double checkinLat) {
this.checkinLat = checkinLat;
}
public double getCheckinLng() {
return checkinLng;
}
public void setCheckinLng(double checkinLng) {
this.checkinLng = checkinLng;
}
public double getCheckoutLat() {
return checkoutLat;
}
public void setCheckoutLat(double checkoutLat) {
this.checkoutLat = checkoutLat;
}
public boolean isRoaming() {
return isRoaming;
}
public void setRoaming(boolean isRoaming) {
this.isRoaming = isRoaming;
}
public Planned_Route getPlannedRoute() {
return plannedRoute;
}
public void setPlannedRoute(Planned_Route plannedRoute) {
this.plannedRoute = plannedRoute;
}
public boolean isValid() {
return valid;
}
public float getEmissions() {
return emissions;
}
public void setEmissions(float emissions) {
this.emissions = emissions;
}
public Co2PerKm getCo2_per_km() {
return co2_per_km;
}
public void setCo2_per_km(Co2PerKm co2_per_km) {
this.co2_per_km = co2_per_km;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public int getUpdate_interval() {
return update_interval;
}
public void setUpdate_interval(int update_interval) {
this.update_interval = update_interval;
}
public RealmList<Record> getRecords() {
return records;
}
public void setRecords(RealmList<Record> records) {
this.records = records;
}
}
Where: Route, Destination are the google maps object, if you are familiar with them, you know what they include and their size;
TripStep = similar with the STEP object from google BUT, it includes 2 arrays:
private RealmList<StopInfo> filteredLocations = new RealmList<>();
private RealmList<StopInfo> rawLocations = new RealmList<>();
In which I have to add a new location every 5-6 seconds in the rawLocations.
Add a new location each time the rawlocation I get is farther than x metres from the last rawLocation I got.
Getting the Object from Preferences, deserialising, getting the latest TripStep and adding the new Location to the filteredLocations and rawLocations seems to take a log of memory. So This is what I think is the problem
After all, I chose to use Realm, instead of shared preferences, it's more efficient, and even if I still have some issues with the changes I make to my file, I'm getting to a stable version quickly.
It has it's downsides (some REALM objects are not serialised correctly by GSON, and you will need to use jackson, and also not being able to use functions inside your model, or that it supports just primitives is a big issue with it, but if you manage to go over this, it's worth it)
Would not suggest adding Realm database to a project that is already big

ORMLite not loading foreign fields

I have the following problem , I have two classes related to record everything is fine however when I return the parent object , the related object is not filled out completely .
Below my classes
#DatabaseTable(tableName = "condicaopagamento")
public class CondicaoPagamento {
#DatabaseField(generatedId=true)
private Integer id;
#DatabaseField
private String descricao;
#DatabaseField
private Integer quatidadeParcela;
#DatabaseField
private Integer diasParcelamento;
#DatabaseField
private boolean usarMesComercial;
#DatabaseField
private Integer parcelaArredondamento;
#DatabaseField(canBeNull = true, foreign=true, maxForeignAutoRefreshLevel=3)
private FormaCobranca formaCobranca;
#DatabaseField
private Double desconto;
#DatabaseField
private Double acrescimo;
//#ForeignCollectionField
//private Collection<Cliente> clientes;
public Integer getId() {
return id;
}
public String getDescricao() {
return descricao;
}
public Integer getQuatidadeParcela() {
return quatidadeParcela;
}
public Integer getParcelaArredondamento() {
return parcelaArredondamento;
}
public Integer getDiasParcelamento() {
return diasParcelamento;
}
public FormaCobranca getFormaCobranca() {
return formaCobranca;
}
public Double getDesconto() {
return desconto;
}
// public Collection<Cliente> getClientes() { return clientes; }
public Double getAcrescimo() {
return acrescimo;
}
public boolean isUsarMesComercial() {
return usarMesComercial;
}
public void setId(Integer id) {
this.id = id;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public void setQuatidadeParcela(Integer quatidadeParcela) {
this.quatidadeParcela = quatidadeParcela;
}
public void setParcelaArredondamento(Integer parcelaArredondamento) {
this.parcelaArredondamento = parcelaArredondamento;
}
public void setUsarMesComercial(boolean usarMesComercial) {
this.usarMesComercial = usarMesComercial;
}
public void setFormaCobranca(FormaCobranca formaCobranca) {
this.formaCobranca = formaCobranca;
}
public void setDiasParcelamento(Integer diasParcelamento) {
this.diasParcelamento = diasParcelamento;
}
public void setAcrescimo(Double acrescimo) {
this.acrescimo = acrescimo;
}
public void setDesconto(Double desconto) {
this.desconto = desconto;
}
// public void setClientes(Collection<Cliente> clientes) {
// this.clientes = clientes;
// }
}
#DatabaseTable(tableName = "formacobranca")
public class FormaCobranca {
#DatabaseField(id = true)
private Integer id;
#DatabaseField
private String descricao;
public Integer getId() {
return id;
}
public String getDescricao() {
return descricao;
}
public void setId(Integer id) {
this.id = id;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
FormaCobranca fc = new FormaCobranca();
fc.setDescricao("FORMA 1");
DatabaseHelper helper = new DatabaseHelper(getContext());
FormaCobrancaDao daoFC = new FormaCobrancaDao(helper.getConnectionSource());
daoFC.createIfNotExists(fc);
FormaCobranca persistidoFC = (FormaCobranca)daoFC.queryForEq("id", 1).get(0);
CondicaoPagamento cp = new CondicaoPagamento();
cp.setDescricao("Condicao2");
cp.setFormaCobranca(persistidoFC);
CondicaoPagamentoDao daoCP = new CondicaoPagamentoDao(helper.getConnectionSource());
daoCP.createIfNotExists(cp);
//CondicaoPagamento persistido = (CondicaoPagamento)daoCP.queryForEq("descricao", "Condicao2").get(0);
CondicaoPagamento persistido = (CondicaoPagamento)daoCP.queryForId(1);
FormaCobranca pFC = persistido.getFormaCobranca();
In the pFC Property Description THIS coming " NULL " .
You forget to specify foreignAutoRefresh=true for #DatabaseField annotation.
Furthermore read this answer https://stackoverflow.com/a/14466145/3802890

Categories

Resources