populating recyclerview from nested table Firebase database - android

I have this structure in my Database inside the UserID I have this random ID which I declared when adding data to database I don't know how to call that to display the info inside to recycler view. Actually I can display the info in Recyclerview if the declared pushid is not there but I need that push ID to work on other modules. I am still learning so I get easily confused with this kind of thing. Any help would be so much appreciated.
This is the line which is calling the table.
mToolsDatabase = FirebaseDatabase.getInstance().getReference().child("toolHistory");
mToolsDatabase.child(list_user_id).child(mCurrentUser.getUid()).addValueEventListener(new ValueEventListener(){
public void onDataChange(DataSnapshot dataSnapshot) {
final String toolName = dataSnapshot.child("name").getValue().toString();
final String toolUser = dataSnapshot.child("user").getValue().toString();
final String toolBorrow = dataSnapshot.child("dateTimeBorrowed").getValue().toString();
final String toolReturn = dataSnapshot.child("dateTimeReturn").getValue().toString();
final String toolStatus = dataSnapshot.child("status").getValue().toString();
final String toolId = dataSnapshot.child("logId").getValue().toString();
viewHolder.setName(toolName);
viewHolder.setUser(toolUser);
viewHolder.setDateTimeBorrowed(toolBorrow);
viewHolder.setDateTimeReturn(toolReturn);
viewHolder.setStatus(toolStatus);
viewHolder.setLogId(toolId);
}

Firebase has its inbuilt method FirebaseRecyclerAdapter for display items in RecyclerView
Also, you can follow this link for more info
https://grokonez.com/android/firebase-realtime-database-display-list-of-data-firebaserecycleradapter-android-development

Related

How can i populate a string value to a realtime firebase database with out creating a child nodes from android?

I wanted to add a string values to a realtime firebase database with the firebase UID being the name and the string being the value. When I use the below code it makes the UID a parent node and set the value to a child node.
ReferralCode referralCode = new ReferralCode(refCode); databaseReference.child("referralCodes").child(userId).setValue(referralCode);
I wanted the values to be populated as the second one. But with the above code,i get the first result. I'm going to search for the referral codes afterwards,so i think it would be faster if the values are populated as the second one to avoid accessing a child node which will be time consuming for large database entities.
When you are using a Model like you created ReferralCode and using it to with .setValue(referralCode) then Firebase will automatically create it as the child with attributes your ReferralCode.java has. Example below:
public class Restaurant {
private int code;
private int type;
private String name;
}
So if I create a variable Restaurant tempRest = new Restaurant(111, "Restoran DM", 0) and use it like this:
database.child("restaurants").child("1st restaurant").setValue(tempRest);
Firebase will create something like this:
restaurants
1st restaurant:
code: 111
name: "Restoran DM"
type: 0
But if you use String in setValue() like this:
String someValue = "some value";
database.child("restaurants").child("awpjawpdaw").setValue(someValue);
it will give you what you want. Example, I used this:
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
String refCode = "1231231";
database.child("restaurants").child("wadawdapwodawp").setValue(refCode);
and here is what happened in database:

how to add data to the existing database in a firebase realtime database?

my code:
lateadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String anahtar=databaseReference.getKey().toString();
final String kisiId = user.getUid().toString().trim();
final String kisiAd = user.getDisplayName().toString().trim();
final String yayinlananYorum = edituruneYorumyap.getText().toString();
List<Urun> urunListesi = new ArrayList<>();
Urun urunler = new Urun(kisiId, kisiAd, yayinlananYorum, urununAdi.getText().toString());
urunListesi.add(urunler);
String key = databaseReference.push().getKey();
databaseReference.child(anahtar).child("urunYorum").setValue(urunler);
}
});
databaseReference.child(anahtar).child("urunYorum").setValue(urunler);
->i think i need a change here but i don't know.
I want to add data to the child's pre-existing reference.
when I run this encoding, it creates a new reference. Unfortunately, it adds a new record.
How can I fix?
This line String key = databaseReference.push().getKey(); creates a new unique reference, that you then write to. If you want to write to an existing reference, you'll need to know the key of that reference, typically by reading it from the UI item that the user clicked on.
Note that calling setValue() replaces all data at the location. If you want to update a subset of the data, or add new properties, you will either have to call setValue() on a lower level, or call updateChildren().
So for example:
databaseReference.child(anahtar).child("urunYorum/newProperty").setValue(urunler);
Or:
Map<String,Object> values = new HashMap<String,Object>();
values.put("kisiId", kisiId);
values.put("kisiAd", kisiAd);
databaseReference.child(anahtar).child("urunYorum").updateChildren(values);

Saving data in Firebase using delimiter in Android

I am trying to save data in my firebase such that it appear like this:
I know that the way to input it manually in firebase is ["marie", "femmehacks"]
But how to I input it from android using delimiter..Note that I need to use Java 7 and String.join is not the solution in android.
Here are my codes:
StringBuilder newstring = new StringBuilder();
for (String movie: movies){
newstring.append(movie);
newstring.append(",");
}
String all = newstring.toString();
all = all.substring(0, all.length() - ",".length());
The output as per this code is now:
["marie,femmehacks"]
but I want it to appear like
["marie", "femmehacks"]
such that it is saved in firebase as per the image above. Any help?
Use this function TextUtils.join(CharSequence delimiter, Iterable tokens).
I got this from here https://developer.android.com/reference/android/text/TextUtils#join(java.lang.CharSequence,%20java.lang.Iterable)
android.text.TextUtils
public static String join(#NonNull CharSequence delimiter,
#NonNull Iterable tokens)
External annotations available:
Parameter delimiter: #android.support.annotation.NonNull
Parameter tokens: #android.support.annotation.NonNull
You may try like this. its works for me.
List<String> stringList = new ArrayList<>();
private String membersName = "";
for (UserInfo userInfo : userInfoList) {
stringList.add(userInfo.getUsername());
}
membersName = TextUtils.join(", ", stringList);
you can save like :
FirebaseDatabase.getInstance().getReference().child(“ChildName”).setValue(membersName);
You should push data as ArrayList<String>
ArrayList<String> movies = <enter code to get list>
FirebaseDatabase.getInstance().getReference().child(“yourChild”).setValue(movies);

Firebase databaste structure advice

I need some advice on how to structure my database in order to query it correctly. From what I've understood the structure of the database is everything, but I am not sure I am using it correctly.
Basically my app is supposed to retrive data from an api and display that in a listview. Every item (newspost) in the listview can have comments from firebase users.
So I have "NewsPost" , "User" and "Comment" models that looks like this.'
NewsPost.class
private String id;
private String date;
private String title;
private String commentsNumber;
private List<Comment> comments;
private String imageUrl;
User.class
private String userName;
private String userAvatar;
private String firstName;
private String lastName;
private String eMail;
Comment.class
private UUID uuid;
private String postId;
private String message;
private String postDate;
private String userAvatar;
private String userName;
So this is how I tried to store it:
AND this is how I try to get the comments when a user clicks to read the comments for the specific newsPostItem in the listView with the newsPostId as a query param.
public void getComments(String postId) {
comments = new ArrayList<>();
Query query = databaseReference.child("comments").orderByChild(postId).equalTo(postId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
Comment comment = issue.getValue(Comment.class);
comments.add(comment);
}
Log.d("GETCOMMENTS", "SNAPSHOT EXISTS");
view.onCommentsLoaded(comments);
}
else{
view.onCommentsLoaded(comments);
Log.d("GETCOMMENTS", "SNAPSHOT NOT EXISTS");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
view.onCommentsLoaded(comments);
Log.d("GETCOMMENTS", databaseError.getMessage());
}
});
}
My Question is, amidoinitrite?
I got a firebase downloaded limit for this month warning (10 GB) which shouldn't happen because I am the only user right now.
Any help is appreciated!
Sidenote: The userAvatar is stored in a byte[] in the database, no good?
When using Firebase, there are a few rules that we need to keep in mind. In your particular case, i recomand you using denormalization and to change the database to be as flatten as possible. For a better understanding, i recomand you see this video, Denormalization is normal with the Firebase Database. Because Firebase Realtime Database cannot query over multiple properties, it ussaly involves duplication data. So this things are normal when it comes to Firebase. In your particular case, i recomand you doing both things.
I also recomand you read this post, Structuring your Firebase Data correctly for a Complex App. It's very well explained and will help you take the best decision.
You need to know that there is no perfect sturcture for a database. You need to structure your database in a way that allows you to read/write data very easily and in a very efficient way. If you don't know yet, Firebase has launched a new product named Cloud Firestore. Realtime Database does not scale automatically while the new Firestore does.
Currently you are adding "NewsPostID" as root node inside "comments".
This structure will consume more storage size because every new comments is added as new root inside "comments" node.
Suppose we wants to query that : Specific user's all comments for any single date. so, in this case current structure is complex to apply query.
You can change structure like :
"comments"
-"userEmail"
- "NewPostDate"
- "NewpostID:15478"
-KHZzTwazaSd (this is random id)
-"message: hey.."
-"postDate: Date + 12:10PM"
-KHZzTwazaSd (this is random id)
-"message: Nice post.."
-"postDate: Date + 12:22PM"
- "NewpostID:54478"
-KHZzTwazaSd (this is random id)
-"message: Nice day"
-"postDate: Date + 10:45PM"
You can get all user related details from user table using "userEmail" from "comments". this will decrease node size and also will be helpful to query.

How to get array data on Firebase?

I have this Firebase:
I'm trying to get all the questions data with this code:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference questionsRef = database.getReference("questions");
questionsRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
HashMap question = dataSnapshot.getValue(HashMap.class);
System.out.println(question.get("0"));
}
}
But I get the error:
com.google.firebase.database.DatabaseException: Class
java.util.HashMap has generic type parameters, please use
GenericTypeIndicator instead
I tried few ways but this is last error. How I can get each question data and all the options of the questions?
Options looks like a numbered list to me, so don't have to use a Map to get it's contents.
GenericTypeIndicator<List<String>> gti = new GenericTypeIndicator<List<String>>() {};
String question = dataSnapshot.child("question").getValue(String.class);
List<String> questionOptions = dataSnapshot.child("options").getValue(gti);
Map<String, String> question = dataSnapshot.child("options").getValue(Map.class);
Take Array of this question..
First, you should change question type to Map, not HashMap (like #varjo mentioned)
Second, in your code you get the value is 1 step above where it should be. So it should be like this:
Map<String, String> question = dataSnapshot.child("options").getValue(Map.class);
Hope this helps
EDIT
To get question text, use this:
String questionText = dataSnapshot.child("question").getValue(String.class);
Note: for best practice, I think you should create a custom object
that combine the question and options together
"options" is not a map, it is a list or an array. Do something like this
GenericTypeIndicator<List<String>> genericTypeIndicator = new GenericTypeIndicator<List<String>>() {};
List<String> list = dataSnapshot.child("options").getValue(genericTypeIndicator);

Categories

Resources