Recycler View Retrieving Childs of different Nodes - android

[
I am planning to retrieve data for a recycler view from the node "movies" and "tickets". I am using Android Studio.
Till now I have a code to retrieve data just from the node "movies".
Is there a possibility to add something to the code to be able to retrieve data from "tickets" also in the same RecycleView?
Thanks for your help :)
RecyclerView mRecyclerView;
FirebaseDatabase mFirebaseDatabase;
DatabaseReference mRef;
// send query to firebaseDatabase
mFirebaseDatabase = FirebaseDatabase.getInstance();
// the following line i suppose needs to change to "Cities"
mRef = mFirebaseDatabase.getReference().child("Cities/movies");
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Movie, MovieViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Movie, MovieViewHolder>(
Movie.class,
R.layout.movies_all,
MovieViewHolder.class,
mRef
){
#Override
protected void populateViewHolder(MovieViewHolder viewHolder, Movie movie, int position){
viewHolder.setDetails(getApplicationContext(),
// the following line(s) again needs to change, but I don't know to what
movie.getTickets(),
movie.getKino(),
movie.getTime();
}
Edit: Or do I need a second "ViewHolder.class" and a second "FirebaseRecyclerAdapter" to retrieve from different nodes?

Related

Can i get documents from collecions i have on Firestore

I have my fire store set up and connected to my app. There are these categories and I want when I click on one category to fetch all subcategory from that category. Can someone explain to me step by step how to do that?
public class BeautyIzbornik extends Activity {
ImageButton imageButton;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference firemRef = db.collection("beauty");
private FirmeAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firmeinfo);
setUpRecyclerView();
}
private void setUpRecyclerView(){
Query query= firemRef.orderBy("logo",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Firme> options = new FirestoreRecyclerOptions.Builder<Firme>()
.setQuery(query,Firme.class)
.build();
adapter= new FirmeAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view2);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
my Fire store looks like this
This is my main category and subcategories:
This are subcollection from one subcategory:
And now in my Main activity, I open the main category and I want when I press on subcategory(whic are all displeyed in my main activity) I want to open new activity and fill it with items from that subcategory... I have more subcategories and items but I hope you understand what I want to show.
so i want to have my Main activity filled with categoriys,secnd activity to fill with subcategorys and third activity where i will display data of some items that is clicked in secnd activity i hope you understand me my englis is bad :D
It would be more useful if you provided the database schema. But the idea is the same on all schemas.
Query query= firemRef.document("myDocumentHERE");
...
You can get the collection of the "myDocumenthere" by doing the following
Query query= firemRef.document("myDocumentHERE").collection("myCollection");
I'd recommend reading the official documentation, there's code examples there and its explained much better.
Source
Can i get documents from collecions i have on Firestore
yes you can! do you want to display your data in recycler?
Try this. Watch Now
to retrieve your beauty in document table, please use this:
firebaseFirestore...
String postId = doc.getDocument().getId(); //retrieving 'beauty` in document table
MyContent myContent = doc.getDocument().toObject(MyContent.class.withId(postId));
in Adapter class you will retrieve it again using this:
final String postId = contentList.get(position).PostId;
firebaseFirestore.collection("kategorije").document(postId).collection("beauty").addSnapshotListener(new EventListener<QuerySnapshot>() ...
please see his videos for details.

Get the data from the Firebase in limit to perform pull to refresh and load more functionality

Yet now i am getting the all data from the FireBase at one time.What i want to do that getting data in LIMITS like 15 records at a time. Like in first time user get the 15 records from the Firebase and when user load more data at the bottom/TOP of the screen than 15 more records should come from Firebase and added to the bottom/TOP of the list.
I have implemented the logic to get the 15 records at a top OR bottom of the database from Firebase like below:-
public class ChatActivity extends AppCompatActivity implements FirebaseAuth.AuthStateListener {
private FirebaseAuth mAuth;
private DatabaseReference mChatRef;
private Query postQuery;
private String newestPostId;
private String oldestPostId;
private int startAt = 0;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mAuth = FirebaseAuth.getInstance();
mAuth.addAuthStateListener(this);
mChatRef = FirebaseDatabase.getInstance().getReference();
mChatRef = mChatRef.child("chats");
/////GETTING THE VIEW ID OF SWIPE LAYOUT
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
/////GETTING FIRST 10 RECORDS FROM THE FIREBASE HERE
mChatRef.limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
oldestPostId = child.getKey();
System.out.println("here si the data==>>" + child.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//////FOR THE PULL TO REFRESH CODE IS HERE
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Refresh items
System.out.println("Here==>>> "+oldestPostId);
///HERE "oldestPostId" IS THE KEY WHICH I GET THE LAST RECORDS FROM THE FIREBASE
mChatRef.startAt(oldestPostId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
System.out.println("here AFTER data added==>>" + child.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
I have searched here on SO for it , but did not get the expected result, below link which i have searched for it
1. First Link
2. Second Link
3. Third Link
4. Forth Link
Please look at my firebase data structure in image.
I have implemented the logic for the getting 15 OR 10 records at first time and it works..and also implemented the logic for loading more records in limits but not getting proper solution (NOT WORKING) , please help and let me know where am i doing wrong..Thanks :)
EDIT SOLUTION
:- I have implemented the load more or pull to refresh functionality on this link:- Firebase infinite scroll list view Load 10 items on Scrolling
You are missing orderByKey(). For any filtering queries you must use the ordering functions. Refer to the documentation
In your onRefresh method you need to set the limit:
public void onRefresh() {
// Refresh items
///HERE "oldestPostId" IS THE KEY WHICH I GET THE LAST RECORDS FROM THE FIREBASE
mChatRef.orderByKey().startAt(oldestPostId).limitToFirst(10).addListenerForSingleValueEvent(new ValueEventListener() {
.....
So the data you retrieve is the only 10 new records after you got your first 10 records.
Make sure to save the oldest key of the newly retrieved data so that on next refresh new data from this key is only retrieved.
Suggestion: Instead of adding a child value listener to find the last key, you can just use the value listener and get the last data snapshot with the size to get the last record's key.
restructure your database, set a new child id which is incremental like 0,1,2,3... etc
"chats": {
"-KZLKDF": {
"id": 0,
"message": "Hi",
"name":"username"
},
then make a method for query
public void loadFromFirebase(int startValue,int endValue){
mChatRef.orderByChild(id).startAt(startValue).endAt(endValue).addListenerForSingleValueEvent(this);
}
make sure you have implemented addListenerForSingleValueEvent then do adapter related task.
Initially call from onCreate method:
loadFromFirebase(0,10);
NB: loading new content in the list you have to be aware with adapter.

How to display records from a Firebase database using a condition with Android?

I have the following Firebase database:
All i want to do, is to display all the lists that belong to a specific user. In this case, i want to display List aaa and List bbb that belong to gmail#gmail,com user. With this query:
databaseReference = FirebaseDatabase.getInstance().getReference();
Query query = databaseReference.child("Lists").orderByChild("ListName");
firebaseListAdapter = new FirebaseListAdapter<ListModel>(this, ListModel.class, android.R.layout.simple_list_item_1, query) {
#Override
protected void populateView(View v, ListModel slm, int position) {
((TextView)v.findViewById(android.R.id.text1)).setText(slm.getListName());
}
};
I achieve to display all the lists but i want to display only the lists that belong to a single user and has the value of true. How can i do that?
Thanks in advance!
There are two ways to achieve this behaviour.
Query query = DatabaseRef.getReference().child("Lists").orderByChild("Users").equals("gmail#gmail,com")
Then add the ChildEventListener to this reference
In Firebase data structure, make the email id parent and add all the childs under it, like
Lists
\gmail#gmail,com
\listName aaa
\listName bbb
You can get data from this structure from below reference:
Query query = DatabaseRef.getInstance().child("Lists").child("gmail#gmail,com")
Then add ChildEventListener listener with your ref object.
Hope this will work for you..
--- Edited ----
Try using this:
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = firebaseDatabase.getReference().child("Lists").orderByChild("Users").equalTo("gmail#gmail,com");
ref.addChildEventListener(New ChildEventListener......);

How to show single value if multiple duplicate values exists?

I am using firebase database for storing data and firebase recycler adapter for showing the data.
RecyclerView recyclerView;
static String SelectedCode;
DatabaseReference root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_get_data);
Firebase.setAndroidContext(this);
recyclerView=(RecyclerView)findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
root = FirebaseDatabase.getInstance().getReference();
Query query = root.child("download").orderByChild("subjectCode");
FirebaseRecyclerAdapter<CourseStorage, GetData.MessageViewHolder> adapter = new FirebaseRecyclerAdapter<CourseStorage, GetData.MessageViewHolder>(
CourseStorage.class,
android.R.layout.two_line_list_item,
GetData.MessageViewHolder.class, query
) {
#Override
protected void populateViewHolder(MessageViewHolder viewHolder, final CourseStorage model, int position) {
viewHolder.textView.setText(model.getSubjectCode());
}
};
recyclerView.setAdapter(adapter);
}
public static class MessageViewHolder extends RecyclerView.ViewHolder{
TextView textView;
View mview;
public MessageViewHolder(View itemView) {
super(itemView);
textView=(TextView)itemView.findViewById(android.R.id.text1);
mview=itemView;
}
}
The getSubjectCode function in CourseStorage class is
public String getSubjectCode () {
return subjectCode;
}
My database is
I am getting output as
I dont want same subjectCode to be displayed twice. How can i achieve it?
There is no GROUP BY clause in the Firebase Database query language. As is quite often the case when using a NoSQL database, the solution is to store the data in the way your app wants to access it.
In your case, since you're showing a list of subject codes, I'd store a list of subject codes in the database (in addition to your current data). For example:
latestItemKeyPerSubjectCode
"COEG301": "-KM...38N"
"COEG341": "-KM...vd-"
...
The exact value that you store really depends on your needs. In this case I stored the key of the most recent item with that subject code, but you could also store the file name (if you'd like to display that in your app) or simply true if you have no need for a meaningful value.

Firebase query result in ListView UI and RecyclerView UI

I am trying to create a Firebase database to store employee information and then when an address is queried, all the employees staying in that particular area should be displayed in a ListView or a RecyclerView however, I am having the following problem:
I am unable to populate the ListView.
ArrayList<String> mItems = new ArrayList<>();
ArrayAdapter mAdapter;
ListView mRecyclerView;
FirebaseListAdapter<String> fireAdapter = new FirebaseListAdapter<String>() {
#Override
protected void populateView(View view, String s) {
//populate view
}
};
In the above code, I am unable to write the constructor so that it becomes,
FirebaseListAdapter<String> fireAdapter = new FirebaseListAdapter<String>(this,String.class,
android.R.layout.simple_list_item_1,mEmployRef) {
#Override
protected void populateView(View view, String s) {
//populate view
}
};
When I write the above code with the constructor, it says,
Cannot resolve constructor 'FirebaseListAdapter(anonymous android.view.View.OnClickListener, java.lang.Class, int, com.google.firebase.database.DatabaseReference)'
How do I resolve this? A similar problem occurs when I try to use a RecyclerView.
You're creating the adapter inside an OnClickListener(), which means that this points to that listener. You need to pass in the Activity to FirebaseListAdapter, which you can get with MainActivity.this.
I was having this problem when Firebase upgraded and what i did to get out of the constructor error was change this:
Firebase rootRef = new Firebase("https://<your-app>.firebaseio.com/");
to this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
then use the rootRef as the fourth parameter on the constructor.
here is a link for upgrading from the previous firebase to the current:
https://firebase.google.com/support/guides/firebase-android#import_your_project_to_the_new_firebase_console_numbered
Also, upgrade your sdk. Hope this solves your problem

Categories

Resources