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.
Related
This is my code and I am uploading a student name and batch name to firebase database. This method is excecuted after user created the account successfully.
User is created in Authentication but data is not uploaded to database and the only error in logcat is:
E/SpellCheckerSession: ignoring processOrEnqueueTask due to unexpected mState=TASK_CLOSE scp.mWhat=TASK_CLOSE
private void uploadUserDetails(){
String name = studentName.getText().toString();
String batch = "BCA";
database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference(firebaseAuth.getUid());
Student student = new Student(name,batch);
ref.child("Student Details").setValue(student);
}
public class Student {
public String name;
public String batch;
Student(){
this.name= "Hello";
this.batch="Unspecified";
}
Student(String name,String batch){
this.name=name;
this.batch=batch;
}
}
The following snippet uses a map for storing the student name and his batch, in this map key is string and value is of object type. and putting a value of key "l".
Map<String, Object> updates = new HashMap<>();
updates.put("l", Arrays.asList(student.batch,student.name));
ref.child("Student Details").setValue(updates);
ArrayList<ListingModel> list = new ArrayList<ListingModel>();
list.add(model);
list.add(model2);
list.add(model3);
list.add(model4);
for (ListingModel m : list) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("node");
myRef.push().setValue(m);
}
I am trying to save 4 objects from android app to firebase database. So I am using loop to store data into the node. It should have create 4 different child with auto id and stored the object there . But it's only storing the last model in one unique id like image below :
How can I save all four objects(data in list) with unique id each?
Fully documented at firebase
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);
}
Put your models in a map, put them, and use updateChildren
The best way to do is to use for loop.
ArrayList<ListingModel> list = new ArrayList<ListingModel>();
list.add(model);
list.add(model2);
list.add(model3);
list.add(model4);
for (int i =0; i<list.size();i++){
ListingModel model = list.get(i);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("node");
myRef.child(i).setValue(model);
}
So the problem was with how I set the model (Sorry for partial code in my question)
ListingModel model = new ListingModel();
model.setTitle("test0");
ListingModel model1 = new ListingModel();
model.setTitle("test1");
ListingModel model2 = new ListingModel();
model.setTitle("test2");
ListingModel model3 = new ListingModel();
model.setTitle("test3");
I was instantiating different models, but only altering value of first model.
model1, model2, and model3 was empty hence was not appearing in firebase database for being an empty object.
I think the code only read push once. And when you using the same id to write the data, you will overwrite the previous version.
ArrayList<ListingModel> list = new ArrayList<ListingModel>();
list.add(model);
list.add(model2);
list.add(model3);
list.add(model4);
for (ListingModel m : list) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("node");
String modelID = myRef.push().getKey();
myRef.child(modelID).setValue(m);
}
Try this, I hope it helps.
Btw, practice using updateChildren rather than setValue for saving your data.
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?
Above is my firebase database:
-Ideas
--Key generated by firebase
--uid
--name
--date
--title
Now I want to get all the ideas generated by a particular uid and attach the query to the recycler. Following is my query and adapter but it returns nothing.
DatabaseReference myIdeasReference = FirebaseDatabase.getInstance().getReference();
final Query myideas =myIdeasReference.child("Ideas")orderByKey().equalTo("userUid",userUid);
mAdapter = new FirebaseRecyclerAdapter<Idea, IdeaHolder>(Idea.class, R.layout.listview_feed, IdeaHolder.class, myideas) {
#Override
public void populateViewHolder(IdeaHolder IdeaViewHolder, final Idea ideaObject, int position) {
int voteCountint = ideaObject.getvoteCount();
String voteCount = Integer.toString(voteCountint);
int flagCountint = ideaObject.getflagCount();
String flagCount = Integer.toString(flagCountint);
String title = ideaObject.gettitle();
String body = ideaObject.getBody();
String postDate = ideaObject.getPostDate();
String mfullName = ideaObject.getfullName();
//pass values :key, Ideauid and Userid to setbutton method in ideaviewholder class
DatabaseReference idearef = getRef(position);//get the database reference of the object at selected position
final String key = idearef.getKey();//get key of the idea reference to get the location later in mvote and mflag
String ideaUid = ideaObject.getuid();
P.S. I also tried the following query:
final Query myideas = myIdeasReference.child("Ideas").orderByValue().equalTo("userUid",userUid);
but then also nothing was displayed.
try with this, this should work for you
myideas = myIdeasReference.child("Ideas").orderByChild("userUid").equalTo(userUid);
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.