java.lang.ClassCastException: java.util.HashMap cannot be cast to Ride - android

DatabaseReference ridesRef = database.getReference("rides");
ridesRef.equalTo(from).orderByChild("from").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, "dataSnapshot.getChildrenCount(): " + dataSnapshot.getChildrenCount());
if (dataSnapshot.getChildrenCount() > 0) {
ArrayList<Ride> value = (ArrayList<Ride>) dataSnapshot.getValue();
Log.i(TAG, value.toString());
for (Ride r : value) { // error occurs here
Log.i(TAG, "r.getTime:" + r.getTime());
Log.i(TAG, "getFrom:" + r.getFrom());
}
}
}
});
Log output is:
09-02 18:08:25.070 23651-23651 I/RidesFragment:
dataSnapshot.getChildrenCount(): 1
09-02 18:08:25.070 23651-23651 I/RidesFragment: [{to=Hackerscher
Markt, userID=0, time=1472831718565, regularly=false, price=0,
chosenUserID=0, active=true, places=1, from=Hauptbahnhof Berlin,
meetingPointDescription=blaues ei}]
public class Ride {
private String from;
private String to;
private long time;
private int places;
private String meetingPointDescription;
private boolean regularly;
private boolean active;
private float price;
private int userID;
private int chosenUserID;
public Ride() {
// Default constructor required for calls to DataSnapshot.getValue(Ride.class)
}
public Ride(String from, String to, long time, int places, String meetingPointDescription, boolean regularly,
boolean active, float price, int userID, int chosenUserID) {
this.from = from;
this.to = to;
this.time = time;
this.places = places;
this.meetingPointDescription = meetingPointDescription;
this.regularly = regularly;
this.active = active;
this.price = price;
this.userID = userID;
this.chosenUserID = chosenUserID;
}
// automatically generated getters and setters...
}

Third time I got an answer to my own question :/
ArrayList<Ride> value = (ArrayList<Ride>) dataSnapshot.getValue();
has to be replaced by
GenericTypeIndicator<ArrayList<Ride>> t = new GenericTypeIndicator<ArrayList<Ride>>() {};
ArrayList<Ride> value = dataSnapshot.getValue(t);
and everything works as expected.

Related

How to get optimized java code from kotlin source file?

I have converted below kotlin file from existing options
#Entity
data class DatabaseVideo constructor(
#PrimaryKey
val url: String,
val updated: String,
val title: String,
val description: String,
val thumbnail: String)
/**
* Map DatabaseVideos to domain entities
*/
fun List<DatabaseVideo>.asDomainModel(): List<DevByteVideo> {
return map {
DevByteVideo(
url = it.url,
title = it.title,
description = it.description,
updated = it.updated,
thumbnail = it.thumbnail)
}
}
The Java out put file is here as below
#Metadata(
mv = {1, 1, 18},
bv = {1, 0, 3},
k = 2,
d1 = {"\u0000\u0010\n\u0000\n\u0002\u0010 \n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\u001a\u0016\u0010\u0000\u001a\b\u0012\u0004\u0012\u00020\u00020\u0001*\b\u0012\u0004\u0012\u00020\u00030\u0001¨\u0006\u0004"},
d2 = {"asDomainModel", "", "Lcom/example/android/devbyteviewer/domain/DevByteVideo;", "Lcom/example/android/devbyteviewer/database/DatabaseVideo;", "app_debug"}
)
public final class DatabaseEntitiesKt {
#NotNull
public static final List asDomainModel(#NotNull List $this$asDomainModel) {
Intrinsics.checkParameterIsNotNull($this$asDomainModel, "$this$asDomainModel");
Iterable $this$map$iv = (Iterable)$this$asDomainModel;
int $i$f$map = false;
Collection destination$iv$iv = (Collection)(new ArrayList(CollectionsKt.collectionSizeOrDefault($this$map$iv, 10)));
int $i$f$mapTo = false;
Iterator var6 = $this$map$iv.iterator();
while(var6.hasNext()) {
Object item$iv$iv = var6.next();
DatabaseVideo it = (DatabaseVideo)item$iv$iv;
int var9 = false;
String var10002 = it.getUrl();
String var10003 = it.getTitle();
String var10004 = it.getDescription();
String var10005 = it.getUpdated();
String var10 = it.getThumbnail();
String var11 = var10005;
String var12 = var10004;
String var13 = var10003;
String var14 = var10002;
DevByteVideo var16 = new DevByteVideo(var13, var12, var14, var11, var10);
destination$iv$iv.add(var16);
}
return (List)destination$iv$iv;
}
}
// DatabaseVideo.java
package com.example.android.devbyteviewer.database;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
#Metadata(
mv = {1, 1, 18},
bv = {1, 0, 3},
k = 1,
d1 = {"\u0000\"\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0000\n\u0002\u0010\u000e\n\u0002\b\u0012\n\u0002\u0010\u000b\n\u0002\b\u0002\n\u0002\u0010\b\n\u0002\b\u0002\b\u0087\b\u0018\u00002\u00020\u0001B-\u0012\u0006\u0010\u0002\u001a\u00020\u0003\u0012\u0006\u0010\u0004\u001a\u00020\u0003\u0012\u0006\u0010\u0005\u001a\u00020\u0003\u0012\u0006\u0010\u0006\u001a\u00020\u0003\u0012\u0006\u0010\u0007\u001a\u00020\u0003¢\u0006\u0002\u0010\bJ\t\u0010\u000f\u001a\u00020\u0003HÆ\u0003J\t\u0010\u0010\u001a\u00020\u0003HÆ\u0003J\t\u0010\u0011\u001a\u00020\u0003HÆ\u0003J\t\u0010\u0012\u001a\u00020\u0003HÆ\u0003J\t\u0010\u0013\u001a\u00020\u0003HÆ\u0003J;\u0010\u0014\u001a\u00020\u00002\b\b\u0002\u0010\u0002\u001a\u00020\u00032\b\b\u0002\u0010\u0004\u001a\u00020\u00032\b\b\u0002\u0010\u0005\u001a\u00020\u00032\b\b\u0002\u0010\u0006\u001a\u00020\u00032\b\b\u0002\u0010\u0007\u001a\u00020\u0003HÆ\u0001J\u0013\u0010\u0015\u001a\u00020\u00162\b\u0010\u0017\u001a\u0004\u0018\u00010\u0001HÖ\u0003J\t\u0010\u0018\u001a\u00020\u0019HÖ\u0001J\t\u0010\u001a\u001a\u00020\u0003HÖ\u0001R\u0011\u0010\u0006\u001a\u00020\u0003¢\u0006\b\n\u0000\u001a\u0004\b\t\u0010\nR\u0011\u0010\u0007\u001a\u00020\u0003¢\u0006\b\n\u0000\u001a\u0004\b\u000b\u0010\nR\u0011\u0010\u0005\u001a\u00020\u0003¢\u0006\b\n\u0000\u001a\u0004\b\f\u0010\nR\u0011\u0010\u0004\u001a\u00020\u0003¢\u0006\b\n\u0000\u001a\u0004\b\r\u0010\nR\u0016\u0010\u0002\u001a\u00020\u00038\u0006X\u0087\u0004¢\u0006\b\n\u0000\u001a\u0004\b\u000e\u0010\n¨\u0006\u001b"},
d2 = {"Lcom/example/android/devbyteviewer/database/DatabaseVideo;", "", "url", "", "updated", "title", "description", "thumbnail", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", "getDescription", "()Ljava/lang/String;", "getThumbnail", "getTitle", "getUpdated", "getUrl", "component1", "component2", "component3", "component4", "component5", "copy", "equals", "", "other", "hashCode", "", "toString", "app_debug"}
)
#Entity
public final class DatabaseVideo {
#PrimaryKey
#NotNull
private final String url;
#NotNull
private final String updated;
#NotNull
private final String title;
#NotNull
private final String description;
#NotNull
private final String thumbnail;
#NotNull
public final String getUrl() {
return this.url;
}
#NotNull
public final String getUpdated() {
return this.updated;
}
#NotNull
public final String getTitle() {
return this.title;
}
#NotNull
public final String getDescription() {
return this.description;
}
#NotNull
public final String getThumbnail() {
return this.thumbnail;
}
public DatabaseVideo(#NotNull String url, #NotNull String updated, #NotNull String title, #NotNull String description, #NotNull String thumbnail) {
Intrinsics.checkParameterIsNotNull(url, "url");
Intrinsics.checkParameterIsNotNull(updated, "updated");
Intrinsics.checkParameterIsNotNull(title, "title");
Intrinsics.checkParameterIsNotNull(description, "description");
Intrinsics.checkParameterIsNotNull(thumbnail, "thumbnail");
super();
this.url = url;
this.updated = updated;
this.title = title;
this.description = description;
this.thumbnail = thumbnail;
}
#NotNull
public final String component1() {
return this.url;
}
#NotNull
public final String component2() {
return this.updated;
}
#NotNull
public final String component3() {
return this.title;
}
#NotNull
public final String component4() {
return this.description;
}
#NotNull
public final String component5() {
return this.thumbnail;
}
#NotNull
public final DatabaseVideo copy(#NotNull String url, #NotNull String updated, #NotNull String title, #NotNull String description, #NotNull String thumbnail) {
Intrinsics.checkParameterIsNotNull(url, "url");
Intrinsics.checkParameterIsNotNull(updated, "updated");
Intrinsics.checkParameterIsNotNull(title, "title");
Intrinsics.checkParameterIsNotNull(description, "description");
Intrinsics.checkParameterIsNotNull(thumbnail, "thumbnail");
return new DatabaseVideo(url, updated, title, description, thumbnail);
}
// $FF: synthetic method
public static DatabaseVideo copy$default(DatabaseVideo var0, String var1, String var2, String var3, String var4, String var5, int var6, Object var7) {
if ((var6 & 1) != 0) {
var1 = var0.url;
}
if ((var6 & 2) != 0) {
var2 = var0.updated;
}
if ((var6 & 4) != 0) {
var3 = var0.title;
}
if ((var6 & 8) != 0) {
var4 = var0.description;
}
if ((var6 & 16) != 0) {
var5 = var0.thumbnail;
}
return var0.copy(var1, var2, var3, var4, var5);
}
#NotNull
public String toString() {
return "DatabaseVideo(url=" + this.url + ", updated=" + this.updated + ", title=" + this.title + ", description=" + this.description + ", thumbnail=" + this.thumbnail + ")";
}
public int hashCode() {
String var10000 = this.url;
int var1 = (var10000 != null ? var10000.hashCode() : 0) * 31;
String var10001 = this.updated;
var1 = (var1 + (var10001 != null ? var10001.hashCode() : 0)) * 31;
var10001 = this.title;
var1 = (var1 + (var10001 != null ? var10001.hashCode() : 0)) * 31;
var10001 = this.description;
var1 = (var1 + (var10001 != null ? var10001.hashCode() : 0)) * 31;
var10001 = this.thumbnail;
return var1 + (var10001 != null ? var10001.hashCode() : 0);
}
public boolean equals(#Nullable Object var1) {
if (this != var1) {
if (var1 instanceof DatabaseVideo) {
DatabaseVideo var2 = (DatabaseVideo)var1;
if (Intrinsics.areEqual(this.url, var2.url) && Intrinsics.areEqual(this.updated, var2.updated) && Intrinsics.areEqual(this.title, var2.title) && Intrinsics.areEqual(this.description, var2.description) && Intrinsics.areEqual(this.thumbnail, var2.thumbnail)) {
return true;
}
}
return false;
} else {
return true;
}
}
}
It is seems to be buggy. very difficult to understand.is there any options to get pure java code ? please let me know if we can able to perform conversion other than android studio
You have to realise that kotlin runs on JVM, hence it can do everything that Java can and nothing more. The extra features that Kotlin provides such as not null types etc are implemented using same byte code that java uses.
All the extra java code that you call "buggy", is there for some specific feature requirement of kotlin.
For example all the Intrinsics.checkParameterIsNotNull checks are there on variables that are declared non nullable, that is how kotlin makes sure that nulls are not introduced in such variables.
So the java output you see doesn't contain any extra code, its the actual java equivalent code of your kotlin class.

How to add timestamps to an adapter

I am trying to make a Chat bubble and I need to insert the timestamps in each bubble, I have my adapter to insert the messages but I do not know how to add the timestamps, someone could tell me how to do it.
Here the MainActivity code:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private View btnSend;
private EditText editText;
boolean myMessage = true;
private List<ChatBubble> ChatBubbles;
private ArrayAdapter<ChatBubble> adapter;
private TextView dateTimeTx;
private TextView dateTimeRx;
private String dateTime;
private String timestamp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChatBubbles = new ArrayList<>();
listView = (ListView) findViewById(R.id.list_msg);
btnSend = findViewById(R.id.btn_chat_send);
editText = (EditText) findViewById(R.id.msg_type);
//set ListView adapter first
adapter = new MessageAdapter(this, R.layout.tx_chat_bubble, ChatBubbles);
listView.setAdapter(adapter);
//event for button SEND
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editText.getText().toString().trim().equals("")) {
Toast.makeText(MainActivity.this, "Please input some text...", Toast.LENGTH_SHORT).show();
} else {
//add message to list
ChatBubble ChatBubble = new ChatBubble(editText.getText().toString(), myMessage, timestamp.toString() );
ChatBubbles.add(ChatBubble);
adapter.notifyDataSetChanged();
editText.setText("");
if (myMessage) {
myMessage = false;
} else {
myMessage = true;
}
}
}
});
}
}
But I have a error in :
ChatBubble ChatBubble = new ChatBubble(editText.getText().toString(), myMessage, timestamp.toString() );
Here mi Adapter code:
public class MessageAdapter extends ArrayAdapter<ChatBubble> {
private Activity activity;
private List<ChatBubble> messages;
private String dateTime;
private SimpleDateFormat simpleDateFormat ;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
String isoDatePattern = "dd/MM/yyyy HH:mm";
simpleDateFormat = new SimpleDateFormat(isoDatePattern);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
ChatBubble ChatBubble = getItem(position);
int viewType = getItemViewType(position);
if (ChatBubble.myMessage()) {
layoutResource = R.layout.tx_chat_bubble;
} else {
layoutResource = R.layout.rx_chat_bubble;
}
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(ChatBubble.getContent());
holder.dateTimeTx.setText(ChatBubble.getTimestamp());
return convertView;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return position % 2;
}
private class ViewHolder {
private TextView msg;
private TextView dateTimeTx;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.txt_msg);
dateTimeTx = (TextView) v.findViewById(R.id.time_msg);
}
}
private String readFechaActual(long timestamp){
return simpleDateFormat.format(new Date(timestamp));
}
}
But I have another error in:
holder.dateTimeTx.setText(ChatBubble.getTimestamp());
Here is the ChatBubble class:
public class ChatBubble {
private String content;
private boolean myMessage;
private long timestamp;
public ChatBubble(String content, boolean myMessage, long timestamp) {
this.content = content;
this.myMessage = myMessage;
this.timestamp = timestamp;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
public long getTimestamp() {
return timestamp;
}
}
Create single (to avoid unused resource requirements) SimpleDateFormat in an adapter constructor:
private SimpleDateFormat simpleDateFormat ;
public MessageAdapter(Activity context, int resource, List<ChatBubble> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
String isoDatePattern = "dd/MM/yyyy HH:mm";
simpleDateFormat = new SimpleDateFormat(isoDatePattern);
}
Update the helper method to return formatted date string:
private String readFechaActual(long timestamp){
return simpleDateFormat.format(new Date(timestamp));
}
}
Use it in getView:
//set message content
holder.msg.setText(ChatBubble.getContent());
holder.dateTimeTx.setText("" + ChatBubble.getTimestamp()); // <--- ADD HERE
The adapter only connects View and Model, but actual data keeps in model, so you should change the BubbleChat class and add timestamp field:
public class ChatBubble {
private String content;
private boolean myMessage;
private long timestamp;
public ChatBubble(String content, boolean myMessage, long timestamp) {
this.content = content;
this.myMessage = myMessage;
this.timestamp = timestamp;
}
public String getContent() {
return content;
}
public boolean myMessage() {
return myMessage;
}
public long getTimestamp() {
return timestamp;
}
}
You should set the time in getView, same way you set the bubble's message.
You already have the field in the ViewHolder.
Also, ChatBubble ChatBubble = getItem(position); should be ChatBubble chatBubble = getItem(position);
And please use RecyclerView
Create a model
public class TimeDifference {
int years;
int months;
int days;
int hours;
int minutes;
int seconds;
String differenceString;
public TimeDifference(Context mContext, Date curdate, Date olddate) {
String y = " "+mContext.getString(R.string.year);
String ys = " "+mContext.getString(R.string.years);
String m = " "+mContext.getString(R.string.month);
String ms = " "+mContext.getString(R.string.months);
String d = " "+mContext.getString(R.string.day);
String ds = " "+mContext.getString(R.string.days);
String h = " "+mContext.getString(R.string.hour);
String hs = " "+mContext.getString(R.string.hours);
String mm = " "+mContext.getString(R.string.minute);
String mms= " "+mContext.getString(R.string.minutes);
String s = " "+mContext.getString(R.string.second);
String ss = " "+mContext.getString(R.string.seconds);
String a = " "+mContext.getString(R.string.ago);
float diff=curdate.getTime() - olddate.getTime();
if (diff >= 0) {
int yearDiff = Math.round( ( diff/ (365l*2592000000f))>=1?( diff/ (365l*2592000000f)):0);
if (yearDiff > 0) {
years = yearDiff;
setDifferenceString(years + (years == 1 ? y : ys) + a);
} else {
int monthDiff = Math.round((diff / 2592000000f)>=1?(diff / 2592000000f):0);
if (monthDiff > 0) {
if (monthDiff > 11)
monthDiff = 11;
months = monthDiff;
setDifferenceString(months + (months == 1 ? m : ms) + a);
} else {
int dayDiff = Math.round((diff / (86400000f))>=1?(diff / (86400000f)):0);
if (dayDiff > 0) {
days = dayDiff;
if(days==30)
days=29;
setDifferenceString(days + (days == 1 ? d : ds) + a);
} else {
int hourDiff = Math.round((diff / (3600000f))>=1?(diff / (3600000f)):0);
if (hourDiff > 0) {
hours = hourDiff;
setDifferenceString( hours + (hours == 1 ? h : hs) + a);
} else {
int minuteDiff = Math.round((diff / (60000f))>=1?(diff / (60000f)):0);
if (minuteDiff > 0) {
minutes = minuteDiff;
setDifferenceString(minutes + (minutes == 1 ? mm : mms) + a);
} else {
int secondDiff =Math.round((diff / (1000f))>=1?(diff / (1000f)):0);
if (secondDiff > 0)
seconds = secondDiff;
else
seconds = 1;
setDifferenceString(seconds + (seconds == 1 ? s : ss) + a);
}
}
}
}
}
}
}
public String getDifferenceString() {
return differenceString;
}
public void setDifferenceString(String differenceString) {
this.differenceString = differenceString;
}
public int getYears() {
return years;
}
public void setYears(int years) {
this.years = years;
}
public int getMonths() {
return months;
}
public void setMonths(int months) {
this.months = months;
}
public int getDays() {
return days;
}
public void setDays(int days) {
this.days = days;
}
public int getHours() {
return hours;
}
public void setHours(int hours) {
this.hours = hours;
}
public int getMinutes() {
return minutes;
}
public void setMinutes(int minutes) {
this.minutes = minutes;
}
public int getSeconds() {
return seconds;
}
public void setSeconds(int seconds) {
this.seconds = seconds;
}
}
Create Utils.java and add this
public static Date getDefaultDate(){
SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
f.setTimeZone(TimeZone.getDefault());
Date nowDate = new Date();
try {
nowDate = dateFormatter.parse(f.format(new Date()));
}catch (ParseException e){
e.printStackTrace();
}
return nowDate;
}
public static Date newDate(String timeStamp){
Date OurDate = null;
try{
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(timeStamp);
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormatter.setTimeZone(TimeZone.getDefault());
String n = dateFormatter.format(value);
OurDate = dateFormatter.parse(n);
}catch (ParseException e){
e.printStackTrace();
}
return OurDate;
}
For pass date into Adapter
TimeDifference now = new TimeDifference(mContext,Utils.getDefaultDate(),Utils.newDate("Your current time");
Toast.makeText(context, "Posted by "+now.getDifferenceString(), Toast.LENGTH_SHORT).show();

Android/Java, Cloud Firestore .toObject method not working

I develop an Android app which interacts with Google Firebase Cloud Firestore. To get data from Firestore, I use addOnCompleteListener with DocumentSnapshot.toObject() method. However, method toObject() seems not to work properly because it doesn't transmit data from snapshot to object.
Goal.class
#Entity
public class Goal {
// private variables
#PrimaryKey (autoGenerate = true)
private int id;
private String remoteId;
private int goalPos;
private String goalName;
private int goalCategory;
private String goalDescription;
private int goalColor;
private int goalFrequency;
private long goalFrequencyCode;
private boolean goalRewardType;
private double goalReward;
private int activated;
private boolean isSynced;
// constructor
public Goal() {
remoteId = "";
goalPos = 0;
goalName = "";
goalCategory = 15;
goalDescription = "";
goalColor = R.color.cat_Black;
goalFrequency = 0; // 0=Daily, 1=Weekly, 2=Monthly
goalFrequencyCode = 1111111111; // 1111111.111 - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday; first of month, middle of month, last of month
goalRewardType = false; // false = standard, true = individual
activated = 1; // 0=No, 1=Yes
isSynced = false;
}
// getter and setter
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRemoteId() {
return remoteId;
}
public void setRemoteId(String remoteId) {
this.remoteId = remoteId;
}
public int getGoalPos() {
return goalPos;
}
public void setGoalPos(int goalPos) {
this.goalPos = goalPos;
}
public String getGoalName() {
return goalName;
}
public void setGoalName(String goalName) {
this.goalName = goalName;
}
public int getGoalCategory() {
return goalCategory;
}
public void setGoalCategory(int goalCategory) {
this.goalCategory = goalCategory;
}
public String getGoalDescription() {
return goalDescription;
}
public void setGoalDescription(String goalDescription) {
this.goalDescription = goalDescription;
}
public int getGoalColor() {
return goalColor;
}
public void setGoalColor(int goalColor) {
this.goalColor = goalColor;
}
public int getGoalFrequency() {
return goalFrequency;
}
public void setGoalFrequency(int goalFrequency) {
this.goalFrequency = goalFrequency;
}
public long getGoalFrequencyCode() {
return goalFrequencyCode;
}
public void setGoalFrequencyCode(long goalFrequencyCode) {
this.goalFrequencyCode = goalFrequencyCode;
}
public LinkedList<Integer> getGoalFrequencyCodeAsList() {
LinkedList<Integer> stack = new LinkedList<>();
long number = goalFrequencyCode;
while (number > 0) {
long longTempMod = number % 10;
int intTempMod = (int) longTempMod;
stack.push(intTempMod);
number = number / 10;
}
return stack;
}
public void setGoalFrequencyCodeFromList(LinkedList<Integer> stack) {
double number = 0;
for (int j = 0; j < stack.size(); j++) {
Log.d(String.valueOf(j), String.valueOf(stack.get(j)));
}
if (stack.size() <= 1) {
goalFrequencyCode = 1111111111;
} else {
for (int i = 0; i < stack.size(); i++) {
Log.d(String.valueOf(stack.get(i)), String.valueOf(number));
number = number + (stack.get(i) * Math.pow(10, (stack.size() - 1 - i)));
}
Log.d("Sent from Goal - number", String.valueOf(number));
goalFrequencyCode = (long) number;
Log.d("Sent from Goal - long", String.valueOf(goalFrequencyCode));
}
}
public boolean getGoalRewardType() {
return goalRewardType;
}
public void setGoalRewardType(boolean goalRewardType) {
this.goalRewardType = goalRewardType;
}
public double getGoalReward() {
return goalReward;
}
public void setGoalReward(double goalReward) {
this.goalReward = goalReward;
}
public int getActivated() {
return activated;
}
public void setActivated(int activated) {
this.activated = activated;
}
public boolean getIsSynced() {
return isSynced;
}
public void setIsSynced(boolean isSynced) {
this.isSynced = isSynced;
}
#Override
public String toString() {
return "Goal{" +
"id=" + id +
", remoteId='" + remoteId + '\'' +
", goalPos=" + goalPos +
", goalName='" + goalName + '\'' +
", goalCategory=" + goalCategory +
", goalDescription='" + goalDescription + '\'' +
", goalColor=" + goalColor +
", goalFrequency=" + goalFrequency +
", goalFrequencyCode=" + goalFrequencyCode +
", goalRewardType=" + goalRewardType +
", goalReward=" + goalReward +
", activated=" + activated +
", isSynced=" + isSynced +
'}';
}
}
FirebaseService.class
public LiveData<ApiResponse<List<Goal>>> getGoals() {
final MutableLiveData<ApiResponse<List<Goal>>> list = new MutableLiveData<>();
if (mAuth.getCurrentUser() != null) {
userId = mAuth.getCurrentUser().getUid();
colRefGoals = firestore.collection(userId).document("data").collection("goals");
colRefGoals
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<Goal> goalsList = new ArrayList<Goal>();
for (DocumentSnapshot documentSnapshot : task.getResult()) {
Log.d("firebaseService", "DocumentSnapshop.getData: " + documentSnapshot.getData());
Goal goal = documentSnapshot.toObject(Goal.class);
Log.d("firebaseService", "DocumentSnapshot.toObject(Goal.class): " + goal.toString());
goalsList.add(goal);
}
ApiResponse<List<Goal>> apiResponse = new ApiResponse<List<Goal>>(goalsList);
list.setValue(apiResponse);
}
}
});
} else {
Throwable error = new Throwable("No user logged in");
ApiResponse<List<Goal>> apiResponse = new ApiResponse<List<Goal>>(error);
list.setValue(apiResponse);
return list;
}
return list;
}
Following my debug log comparison between .getData and .toObject:
12-05 19:53:42.663 11470-11470/com.benjaminsommer.dailygoals D/firebaseService: DocumentSnapshop.getData: {goals={goalRewardType=true, remoteId=10L44s0EcvTTzGajzhidgoals, id=2, goalFrequencyCode=1001111111, activated=1, goalColor=-4365347, goalCategory=8, goalDescription=Description Test, goalReward=1, goalPos=1, goalFrequency=2, goalName=Test}}
12-05 19:53:42.663 11470-11470/com.benjaminsommer.dailygoals D/firebaseService: DocumentSnapshot.toObject(Goal.class): Goal{id=0, remoteId='', goalPos=0, goalName='', goalCategory=15, goalDescription='', goalColor=2131558437, goalFrequency=0, goalFrequencyCode=1111111111, goalRewardType=false, goalReward=0.0, activated=1, isSynced=false}
.toObject doesn't transform the datasnapshot to my class. I already checked the documentation:
Important: Each custom class must have a public constructor that takes
no arguments. In addition, the class must include a public getter for
each property.
I have a constructor with no args and public getters for each property. I tried it with an empty constructor, but not working either. Is anything wrong with my getters? I use it in combination with Room, maybe there can be an issue?
Really appreciate your help and support.
Thanks, Ben

Time displayed on Android app is 1-hour ahead

I have an Android app that uses a backend web service to send and receive messages between devices.
Problem: The message time displayed in the app's Inbox and Sent box is 1-hour ahead (e.g. if the real time is 8:00am, the app shows 9:00am) Please help. Here is my code:
private static class DateTime {
static final char HOUR_OF_DAY_0 = 'H'; // (00 - 23)
static final char HOUR_0 = 'I'; // (01 - 12)
static final char HOUR_OF_DAY = 'k'; // (0 - 23) -- like H
static final char HOUR = 'l'; // (1 - 12) -- like I
static final char MINUTE = 'M'; // (00 - 59)
static final char NANOSECOND = 'N'; // (000000000 - 999999999)
static final char MILLISECOND = 'L'; // jdk, not in gnu (000 - 999)
static final char MILLISECOND_SINCE_EPOCH = 'Q'; // (0 - 99...?)
static final char AM_PM = 'p'; // (am or pm)
static final char SECONDS_SINCE_EPOCH = 's'; // (0 - 99...?)
static final char SECOND = 'S'; // (00 - 60 - leap second)
static final char TIME = 'T'; // (24 hour hh:mm:ss)
static final char ZONE_NUMERIC = 'z'; // (-1200 - +1200) - ls minus?
static final char ZONE = 'Z'; // (symbol)
// Composites
static final char TIME_12_HOUR = 'r'; // (hh:mm:ss [AP]M)
static final char TIME_24_HOUR = 'R'; // (hh:mm same as %H:%M)
// * static final char LOCALE_TIME = 'X'; // (%H:%M:%S) - parse format?
static final char DATE_TIME = 'c';
// (Sat Nov 04 12:02:33 EST 1999)
static final char DATE = 'D'; // (mm/dd/yy)
static final char ISO_STANDARD_DATE = 'F'; // (%Y-%m-%d)
// * static final char LOCALE_DATE = 'x'; // (mm/dd/yy)
More info:
public class Inbox {
private String messageID;
private String from;
private List<String> to;
private String subject;
private String voice_file;
private String datetime;
private String is_read;
public String getMessageID(){
return messageID;
}
public void setMessageID(String messageID){
this.messageID= messageID;
}
public String getFrom(){
return from;
}
public void setFrom(String from){
this.from= from;
}
public String getSubject(){
return subject;
}
public void setSubject(String subject){
this.subject= subject;
}
public String getVoiceFile(){
return voice_file;
}
public void setVoiceFile(String voice_file){
this.voice_file= voice_file;
}
public String getDateTime(){
return datetime;
}
public void setDateTime(String datetime){
this.datetime= datetime;
}
public List<String> getTo(){
return this.to;
}
public void setTo(List<String> to){
this.to= to;
}
public String getIsRead(){
return is_read;
}
public void setIsRead(String is_read){
this.is_read= is_read;
}
}
public class Sentbox {
private String messageID;
private String from;
private List<String> toName;
private List<String> to;
private String subject;
private String voice_file;
private String datetime;
public String getMessageID(){
return messageID;
}
public void setMessageID(String messageID){
this.messageID= messageID;
}
public String getFrom(){
return from;
}
public void setFrom(String from){
this.from= from;
}
public String getSubject(){
return subject;
}
public void setSubject(String subject){
this.subject= subject;
}
public String getVoiceFile(){
return voice_file;
}
public void setVoiceFile(String voice_file){
this.voice_file= voice_file;
}
public String getDateTime(){
return datetime;
}
public void setDateTime(String datetime){
this.datetime= datetime;
}
public List<String> getTo(){
return this.to;
}
public void setTo(List<String> to){
this.to= to;
}
public List<String> getToName(){
return this.toName;
}
public void setToName(List<String> toName){
this.toName= toName;
}
}

Json parsing with gson not working

This is my JSON string:
[{"BranchID":1,"SecurityCode1":13,"SecurityCode2":14,"PrintHeight":10,"PrintWidth":10,"Active":true}]
This is Code I am using to parse the JSON:
Type t = new TypeToken<List<Setting>>() {
}.getClass();
String json = ServiceHelper.getJSON(response);
List<Setting> list = (List<Setting>) gson.fromJson(json, t);
//list is null which it souldnt
This is the Setting class, Entity is ORMDroid entity class:
public class Setting extends Entity {
#Column(name = "id", primaryKey = true)
#SerializedName("BranchID")
public int BranchID;
public int securityCodeLPK;
public int securityCodeSDK;
#SerializedName("PrintHeight")
public int PrintHeight;
#SerializedName("PrintWidth")
public int PrintWidth;
#SerializedName("Active")
public String Active;
#SerializedName("SecurityCode1")
public String SecurityCode1;
#SerializedName("SecurityCode2")
public String SecurityCode2;
public Setting(int BranchID, int height, int width, String active, String securityCode1, String securityCode2) {
super();
BranchID = BranchID;
PrintHeight = height;
PrintWidth = width;
Active = active;
SecurityCode1 = securityCode1;
SecurityCode2 = securityCode2;
}
public Setting () {
super();
}
}
It seems to be OK, but list after gson.FromJson is null. What's wrong with this code?
Please help
You should use getType() instead of getClass().
Type t = new TypeToken<List<Setting>>() {}.getType();

Categories

Resources