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);
Related
I am trying to add schema where i have list of ids and value as a date. but I am getting the schema like this:
.
But I want in place of 0 is userID and date as a object. Please have a look over my code:
final String idGroup = (StaticConfig.UID + System.currentTimeMillis()).hashCode() + "";
final String currentDate = DateFormat.getDateInstance().format(new Date());
Room room = new Room();
for (String id : listIDChoose) {
AddGroupUser addGroupUser = new AddGroupUser();
addGroupUser.date = currentDate;
addGroupUser.user = id;
room.member.add(addGroupUser);
}
room.groupInfo.put("name", gName);
room.groupInfo.put("admin", StaticConfig.UID);
room.groupInfo.put("avatar",image);
FirebaseDatabase.getInstance().getReference().child("group/" + idGroup).setValue(room).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
ToastMessage("Group Created");
}
});
How to change my object so that i can get the following result. Any help will be very grateful. Thanks!!
In your Room class you have a List< AddGroupUser>. And Firebase translates a List to zero-based indexes in the JSON format.
To be able to control the key, the list needs to become a Map<String, AddGroupUser>. Then you can set the key of each AddGroupUser that you put in the map.
room.members.put(id, addGroupUser);
I am new to firebase so, please bear with me. I am making a registration using firebase realtime database in android studio. What I want to do is that when the user enters her firstname and lastname, the system will set the username for them by taking the first character of the firstname and concatenate it with the lastname.
Example:
Name: John Smith
Username: jsmith
There are cases that there would be a duplication for the username because there are so many names that starts with J with the lastname Smith. So what I want is to add an integer if the username already exist.
jsmith, jsmith1, jsmith2, etc...
I know I needed to add a loop but I just don't know how to construct it. Here is my code:
public void insertAccount(){
acctstatus.setText("Active");
accttype.setText("Employee");
final String status = acctstatus.getText().toString();
final String type = accttype.getText().toString();
final String lname = empLname.getText().toString();
final String fname = empFname.getText().toString();
final String newfname = fname.substring(0,1).toLowerCase();
final String newuname = newfname+lname.toLowerCase();
// empuname.setText(newuname);
// final String uname = empuname.getText().toString();
// String passw = UUID.randomUUID().toString().substring(0,5);
// emppassw.setText(passw);
// String newpassw = emppassw.getText().toString();
String newpassw = newuname;
//
final int num = 0;
accountFirebaseReference.orderByChild("acct_uname").equalTo(newuname)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String username = newuname+num+1;
empuname.setText(username);
final String acctuname = empuname.getText().toString();
Toast.makeText(getApplicationContext(), "Username: "+acctuname, Toast.LENGTH_LONG).show();
}else{
String username = newuname;
empuname.setText(username);
Toast.makeText(getApplicationContext(), "Username: "+empuname, Toast.LENGTH_LONG).show();
}
}
final String acctuname = empuname.getText().toString();
final String acctpassw = empuname.getText().toString();
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//addAccount(newuname, newpassw, type, status);
}
merely a suggestion. If a username exists, add a 01, like this jDoe01,jDoe02.... then jDoe011, etc.
Then, if a document exists, get the index of that zero, (it will always exist)
you can use something like int index = yourUserNameFromFirebase.indexOf('0');
then, you can use that index to get the number from the document, through doing a substring:
String numberValue = yourUserNameFromFirebase.substring(index);
int countOfDuplicateNames = Integer.valueOf(numberValue);
then, you can simply increment countOfDuplicateNames and make a new user, just remember to always ensure that the 0 is there, as this is the only way to get a reference to the number.
to pseudo code it, your new username will be something like this:
initial + surname + '0' + countOfDuplicateNames+1
Note
Sorry this answer does not cater for starting at an index of 1 :D
I used hashmap to get the data from Filter data fragment that the user wants
to display, and I want to build a dynamic Firestore fetch query, but I'm
not sure if this is the right way to do it.
I'm new to firestore query but I’ve tried to setup build a dynamic query by store the variables into the query using foreach, in the code explain I transform this code
Query filterQuery= db.collection("Property").
.whereEqualTo("noBathrooms", "5")
.whereEqualTo("noRooms", "2");
to this.
for(Map.Entry<String, Object> entry : list.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
filterQuery=propertyRef.whereEqualTo(key,value);
}
here where I setup the query
public void filterData(){
Query filterQuery =null;
for(Map.Entry<String, Object> entry : list.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
Log.i(key,value);
filterQuery=propertyRef.whereEqualTo(key,value);
}
dataFetch(filterQuery,R.id.rentRV);
}
and here where i am bulidng it
private void dataFetch(Query query,int rvView){
FirestoreRecyclerOptions<Property> options = new
FirestoreRecyclerOptions.Builder<Property>()
.setQuery(query, Property.class)
.build();
mAdapter = new DiscoverAdapter(options);
RecyclerView recyclerView = root.findViewById(rvView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new
LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false));
recyclerView.setAdapter(mAdapter);
mAdapter.startListening();
mAdapter.setOnItemClickListener((documentSnapshot, position) -> {
Property property = documentSnapshot.toObject(Property.class);
String id = documentSnapshot.getId();
Bundle mBundle = new Bundle();
mBundle.putString("id", id);
Toast.makeText(getContext(), id, Toast.LENGTH_SHORT).show();
});
}
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.
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.