Skip to content

Instantly share code, notes, and snippets.

@Johnyoat
Created February 7, 2019 17:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Johnyoat/8d095628b26ea0dff2117538f1061053 to your computer and use it in GitHub Desktop.
Save Johnyoat/8d095628b26ea0dff2117538f1061053 to your computer and use it in GitHub Desktop.
Firestore Data Example
import android.annotation.SuppressLint;
import android.os.Bundle;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import java.text.SimpleDateFormat;
import java.util.Date;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class FirestoreDataExample extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db.collection("collectionName").document("documentId").addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
if (documentSnapshot != null){
DataObj obj = documentSnapshot.toObject(DataObj.class);
assert obj != null;
//Server time stamp
long dateStamp = (long) documentSnapshot.get("createTime");
Date date = new Date(obj.getDate());
@SuppressLint("SimpleDateFormat")
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
String dateText = simpleDateFormat.format(date);
System.out.println(dateText);
}
}
});
}
private class DataObj {
//Document fields
private String id;
private long date;
//Mutators
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment