Hello i'm a newbie on firebase, i'm creating a simple app to store text data on my firebase database. My goal is just to store the text but it seems that i cannot store the text.
I have this code for my send button which gets the value from the textbox and send it to the database. I can't figure out what's wrong.
public void onSendButtonClick(View v) {
String message = mMessageEdit.getText().toString();
Map<String, String> values = new HashMap<>();
values.put("name", "puf");
values.put("message", message.toString());
mFirebaseRef.push().setValue(values);
mMessageEdit.setText("");
}
Hope you could help me with this simple newbie problem.
Thanks. :)
I usually make a long variable to save date in millisecond.
long currentTimeInMillis = System.currentTimeInMillis();
Map<String, String> values = new HashMap<>();
values.put("date", currentTimeInMillis);
mFirebaseRef.push().setValue(values);
And then to convert it back I use DateFormat class (from android.text.format)
public static String getDate(String dateFormat, long currentTimeInMillis) {
return DateFormat.format(dateFormat, currentTimeInMillis); }
// Example usage
getDate("dd/MM/yyyy hh:mm:ss", "38232213325");
Try using a Map of type Map<String, Object> to write your values:
public void onSendButtonClick(View v) {
String message = mMessageEdit.getText().toString();
Map<String, Object> values = new HashMap<>();
values.put("name", "puf");
values.put("message", message);
mFirebaseRef.push().setValue(values);
mMessageEdit.setText("");
}
Related
I store a Date in Firestore. I get an HashMap<String, Object> from firestore and i want to recreate my object from it.
Before implementing the Date the working code was :
HashMap<String, Object> document = new HashMap<String, Object>();
document.put("name", "name");
JSONElement jsonElement = gson.toJsonTree(document);
Event event = gson.fromJson(jsonElement , Event.class);
I have now add the field
#ServerTimestamp
private Date dateOfEvent;
But when i try to serialize it i get the following error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT at path $.dateOfEvent
Because the JsonElement "dateOfEvent" look like this because it's a Firestore Timestamp:
{"dateOfEvent": {"nanoseconds":0,"seconds":1584921600}, "name": "test Event"}
Thanks for your time and your help.
Gson is expecting a Date string like 2020-02-27T09:00:00 but it's actually an object. You could setup your classes like this and add a helper method to get dateOfEvent as a Date:
class Event {
private String name;
private MyDate date;
}
class MyDate {
private Long nanoseconds;
private Long seconds;
// getters/setters for nanoseconds, seconds...
public Date asDate() {
// convert to date
}
}
I am using this method to store data in my firebase database:
First i store all the data in a Model Class, called SubjectDataModel,
then i get the push key from the firebase database.
and then i set value to that particular key.
Here is my code :
SubjectDataModel:
public class SubjectDataModel {
public String id;
public String dbName;
public String subName;
public String tagline;
public int preference;
public SubjectDataModel()
{
}
public SubjectDataModel(String id, String dbName, String subName, String tagline, int preference) {
this.id = id;
this.dbName = dbName;
this.subName = subName;
this.tagline = tagline;
this.preference = preference;
}
}
Then i use the following code to push it to the database and then i also store the key id locally.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
String id = ref.push().getKey();
SubjectDataModel newSub = new SubjectDataModel(id, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(id).setValue(newSub);
Now imagine, later in time, i want to update this data,
so i have the key id stored, so i can access it, i also have edited all the other data locally, so now if i make a SubjectDataModel Object with that data and again do ref.child(id).setValue(newSub); with the stored id, will the data be updated ? Or is there any other method to do so ?
updateChildren() is the method you are looking for, refer this documentation Firebase Read and Write Data on Android
Here's an example from documentation...
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
Post post = new Post(userId, username, title, body);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
Okay, so i tried this and it works perfectly, like i expected it to. No need for me to use maps or anything. Simplest way to update data.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
SubjectDataModel newSub = new SubjectDataModel(idForUpdate, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(idForUpdate).setValue(newSub);
So here basically, i created the object with the required data, and pushed it back to the same id with which i created a node in the firebase database, so it updates that same node with the new values.
The application I'm developing is really similar to Instagram.
On Instagram, users can change their usernames anytime. And if you change your username, your posts also show the updated username.
How can I implement this on a firebase database environment?
For example, I have VO below.
#IgnoreExtraProperties
public class Post {
String uid;
String username;
String content;
int likesCount = 0;
Map<String, Boolean> likes = new HashMap<>();
Map<String, Boolean> hashtags = new HashMap<>();
public Post() {
// Default constructor required for calls to DataSnapshot.getValue(Post.class)
}
public Post(String uid, String username, String content) {
this.uid = uid;
this.username = username;
this.content = content;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("username", username);
result.put("content", content);
result.put("likesCount", likesCount);
result.put("likes", likes);
result.put("hashtags", hashtags);
return result;
}
}
If I include "username" in the Post Object, I can show each post with the usernames synchronously, but it will be difficult to show the latest updated "username" all the time.
If one user's Posts are over 1000, should I update all the posts at the same time when the username is changed?
If I exclude "username" in Post object I can load updated "username" asynchronously each time after any Post is loaded.
Or at the first time just show old username, and check if it is changed everytime when the Post is loaded, and update it asynchronously.
Which is the most efficient and proper way to implement for it?
I am new to Kumulos development.
I want to get selected data from table of kumulos.
Like If user enter username and password i check from table that data exits or not.
But the issue is while checking data inserted in table and not giving me correct output.
While testing api in browser it works fine.
My code for select from table is below.
public void CallApiLogin(){
final String Uname=editUname.getText().toString();
final String pass=editPass.getText().toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", Uname);
params.put("password",pass);
Kumulos.call("user_register", params, new ResponseHandler() {
#Override
public void didCompleteWithResult(Object result) {
// Do updates to UI/data models based on result
ArrayList<LinkedHashMap<String, Object>> objects = (ArrayList<LinkedHashMap<String,Object>>) result;
for (LinkedHashMap<String, Object> item : objects) {
String name = (String) item.get("name");
String password = (String) item.get("password");
if(name.equalsIgnoreCase(Uname) && password.equalsIgnoreCase(pass)){
Intent i=new Intent(Login.this,Home.class);
startActivity(i);
}else{
Toast.makeText(getApplicationContext(),"Please enter valid username and password.",Toast.LENGTH_SHORT).show();
}
}
}
});
}
Please suggest where i am going wrong as requested data inserted in table.
But i want that request data exist or not????
After spending hours, I got solution.
Issue is creating api. In Kumulos you have to create different api.
I was using api "user_register", Now i have create other api call "Select_user".
This api works fine what the result i want.
I hope this question may help some other.
I'm new in Multiplayer programming. How to set String into hashmap value ? I want to call hashmap properties from RoomListActivity and set it's value on QuizMaintain activity and also I want to set hashmap value from QuizMaintain class to textview. Here's my sample code
RoomListActivity
public void onJoinNewRoomClicked(View view){
progressDialog = ProgressDialog.show(this,"","Please wait...");
progressDialog.setCancelable(true);
HashMap<String, Object> properties = new HashMap<String, Object>();
properties.put("timer", "");
properties.put("question", "");
properties.put("answer", "");
properties.put("foulanswer", "");
theClient.createRoom(""+System.currentTimeMillis(), "Yoshua", 2, properties);
}
Then I want to set it's value from QuizMaintain activity
public class QuizMaintain extends Activity implements RoomRequestListener, NotifyListener {
private WarpClient theClient;
private HashMap<String, Object> properties;
private TextView txttimer,txtquestion;
private String roomId = "";
private HashMap<String, User> userMap = new HashMap<String, User>();
String string="5x5#5x4#150:3#500:20#536+59";
String[] questions = string.split("#");
String question1 = questions[0];
String question2 = questions[1];
String question3 = questions[2];
String question4 = questions[3];
String question5 = questions[4];
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_maintain);
txttimer = (TextView)findViewById(R.id.timer);
txtquestion = (TextView)findViewById(R.id.questionview);
try{
theClient = WarpClient.getInstance();
}catch(Exception e){
e.printStackTrace();
}
theClient.getLiveRoomInfo("143680827");
Intent intent = getIntent();
roomId = intent.getStringExtra("roomId");
init(roomId);
//setquestionview();
}
private void init(String roomId){
if(theClient!=null){
theClient.addRoomRequestListener(this);
theClient.addNotificationListener(this);
theClient.joinRoom(roomId);
}
}
#Override
public void onGetLiveRoomInfoDone(LiveRoomInfoEvent event) {
properties = event.getProperties();
properties.put("question", question1);
}
I want to set hashmap value where is the key are "question". And the value that i want to set are from split string.When I ask their support team if I want to get room properties I should call getLiveRoomInfo method and pass roomID as argument. A bit confused here. Thanks.
But it seems my problem are not solved yet. After call method updateRoomProperties but I got another error here. It's say WarpClient.AddZoneRequestListener(this) return null pointer exception
When you are creating a room you are passing a hashmap. This hashmap is stored as a JSON document inside the room on server. AppWarp calls it Room Properties.
Now to retrieve these properties you have to call getLiveRoomInfo method. This will present you the room properties. Here you are adding/changing some key-value again. But you haven't told the server that you are updating these room properties. Therefore your changes remain local and that too limited to the scope of function.
So, when you call the getLiveRoomInfo method, you won't see the changes as you haven't updated them on server. To update on server, you need to call updateRoomProperties method. In this method you can add or change your hashmap.