Can i get documents from collecions i have on Firestore - android

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.

Related

Recycler View Retrieving Childs of different Nodes

[
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?

Loading values from Firebase database into drop down Textviews in Android

I require help in implementing data from a secondary Firebase database into autocomplete TextViews in my android application. I have a database containing data on cars (Make of car, model of car, engine size).
I have attached an image displaying how my data is set in the database.
Database image
I would like to have one TextView that will only display all the "make" attributes, another TextView to display only "model" attributes depending on which "make of car" the user picked. (eg. if the user picks Audi, models displayed would be A4, A6, A3 only. if the user picks Volkswagen, models displayed would be Golf, Jetta, Passat only) and then the final TextView to display only the "engine size" that corresponds to the chosen "make" and "model" as each model of car has different engine sizes.
Any help would be greatly appreciated as I have been stuck on this element of my app for several weeks now and have tried countless different approaches.
Below is my class and code. The application runs with no errors but will not retrieve the data from the database.
public class VehicleSpec extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Sets the layout according to the XML file
setContentView(R.layout.activity_vehicle_spec);
//FirebaseDatabase database = FirebaseDatabase.getInstance();
//
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("com.example.user.vel")
.setApiKey("AIzaSyBvBtL81H7aiUK90c3QfVccoU1CowKrmAA")
.setDatabaseUrl("https://finalyearproject-vel1-aac42.firebaseio.com/")
.build();
//
FirebaseApp.initializeApp(this, options, "secondary");
//
FirebaseApp app = FirebaseApp.getInstance("secondary");
FirebaseDatabase database2 = FirebaseDatabase.getInstance(app);
DatabaseReference dbref = database2.getReference();
DatabaseReference dbref2 = database2.getReference();
DatabaseReference dbref3 = database2.getReference();
//
dbref.child("Cars").addValueEventListener(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
final List<String> Cars = new ArrayList<String>();
for ( DataSnapshot suggestionSnap : dataSnapshot.getChildren() )
{
String suggestion = suggestionSnap.child("Make").getValue(String.class);
Cars.add(suggestion);
}//End For()
//XML TextView variable
AutoCompleteTextView actv = (AutoCompleteTextView) findViewById(R.id.auto);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(VehicleSpec.this, android.R.layout.simple_list_item_1, Cars);
actv.setAdapter(adapter);
}//End onDataChange()
public void onCancelled(DatabaseError databaseError)
{
}//End onCancelled()
});//End dbref ValueEventListener()
//
dbref2.child("Cars").addValueEventListener(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
final List<String> Cars = new ArrayList<String>();
for ( DataSnapshot suggestionSnap : dataSnapshot.getChildren() )
{
String suggestion = suggestionSnap.child("Model").getValue(String.class);
Cars.add(suggestion);
}//End for()
//XML TextView variable
AutoCompleteTextView actv1 = (AutoCompleteTextView) findViewById(R.id.auto1);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(VehicleSpec.this, android.R.layout.simple_list_item_1, Cars);
actv1.setAdapter(adapter1);
}//End onDataChange()
public void onCancelled(DatabaseError databaseError)
{
}//End onCancelled()
});//End dbref2 ValueEventListener()
//
dbref3.child("Cars").addValueEventListener(new ValueEventListener()
{
public void onDataChange(DataSnapshot dataSnapshot)
{
final List<String> Cars = new ArrayList<String>();
for (DataSnapshot suggestionSnap : dataSnapshot.getChildren())
{
String suggestion = suggestionSnap.child("Engine Size").getValue(String.class);
Cars.add(suggestion);
}//End for()
//XML TextView variable
AutoCompleteTextView actv2 = (AutoCompleteTextView) findViewById(R.id.auto2);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(VehicleSpec.this, android.R.layout.simple_list_item_1, Cars);
actv2.setAdapter(adapter2);
}//End onDataChange()
public void onCancelled(DatabaseError databaseError)
{
}//End onCancelled()
});//End dbref3 ValueEventListener()
}//End onCreate()
I Don't really understand exactly what are you trying to achieve, but let's assume you want one of the followings:
Display a list of cars in a list with 3 sections , Make , Model and a drop down list for Engine Size:
i Suggest using RecyclerView with 2 TextViews (1 for Make, and the second for Model) and an AppCompatSpinner that will be populated from the Engine Size node. You can use these Libraries as your adapter :
FirebaseUI
Infinite-Fire i personaly like this one because it has a built in loadMore when you reach last the item.
Display a list of car Brands (Make in this case) and when a user selects an item, an other list with Models and Engine Sizes Appears : i Suggest using RecyclerView with A TextViews for Make and when the user clicks an item, you save the item name in your SharedPrefrances and open a new activity that displays only models from the selected Make using Firebase databaseRef.child("Cars").orderByChild("Make").equalesTo(getSelectedMake());
or just display them in an AlertDialog instead with a costume layout using the same methods...for displaying DATA You can use the above Libraries as well.
if This isn't what are you looking for , please explain your problem with details and i will update my answer.
Edit : using SharedPreferences to save a reference of the item is nonsense, it's a result of my low experience with android, instead you can use intent.putExtra()
Example
//Start your activity like this
intent.putExtra("itemId", itemId)
startService(intent)
//On your new activity's onCreate() get the itemId as the following
String itemId = intent.getStringExtra("itemId")
Item item = firebaseRef.child("cars")....getValue(Item:class)

How to bind live data to array adapter android

I have a simple application while I'm trying to understand android/room. I would like to have my query from room to be placed into my list view.
PersonDao.class
#Query("Select name from People limit 3")
LiveData<List<String>> getThreeNames();
AvtivityMain.class
private ArrayAdapter<String> adapter;
private PersonDatabase db;
private EditText age;
private EditText name;
Person person;
private DatabaseRepository rDb;
private PersonViewModel personViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
age = findViewById(R.id.age);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
ListView lvPerson = findViewById(R.id.lv3Poeple);
lvPerson.setAdapter(adapter);
personViewModel = ViewModelProviders.of(this).get(PersonViewModel.class);
}
public void addPerson(View view){
int sAge = Integer.parseInt(age.getText().toString());
String sName = name.getText().toString();
person = new Person(sName, sAge);
personViewModel.insert(person);
System.out.println(personViewModel.getmAllPeople());
System.out.println(personViewModel.getm3People());
//List<String> names = personViewModel.getm3People();
//adapter.add(personViewModel.getm3People());
}
I have commented out the code I am having problems with. I want to be able to use my query from PersonDao and have my list view show 3 names from my Room database.
You need to do a few things, the first is make sure your adapter can take new input. I would suggest creating your own custom one. When you do create it, be sure to include a method that takes your person strings as input and notifies the adapter of the change, like so:
//you need to add an update method to your adapter, so it can change it's data as your
//viewmodel data changes, something like this:
public void setPersons(List<String> personNames) {
//myPersons should be a variable declared within your adapter that the views load info from
myPersons = personNames;
notifyDataSetChanged();
}
Then in your activity you should set the Adapter as a global variable so it can be accessed by multiple methods, such as your view model observer method and it's initial setup in onCreate().
//need to set up adapter variable to access in other methods to keep view model observer
//off the main thread
private ArrayAdapter myAdapter;
After that you can set up the following observer method for your ViewModel (assuming you created the ViewModel Class properly with a return method called getThreeNames() and that isn't just within your DAO as you showed above.
//set up the view model observer to be off the main thread so it isn't tied to your main
//activity lifecyle (which is the whole point/beauty of the ViewModel), you can call this
//method in your onCreate() method and should stay until onDestroy() is called
private void setupPersonViewModel() {
PersonViewModel viewModel
= ViewModelProviders.of(this).get(PersonViewModel.class);
viewModel.getThreeNames().observe(this, new Observer<List<String>>() {
#Override
public void onChanged(#Nullable List<String> persons) {
//so you can see when your app does this in your log
Log.d(TAG, "Updating list of persons from LiveData in ViewModel");
mAdapter.setPersons(persons);
}
});
}
Hope that answers your question. Let me know if you need any further clarification.

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