I'm working on a project where there's an activity which contains 3 spinners( Nested). I need the 2nd spinner to have the data based on the selected item of the 1st spinner and the data is retrieved from Firebase
The 1st spinner is going to have all "Gouv" values , the 2nd one is going to have the "Deleg" values where "Gouv" value is equal to the selected item "Gouv" of the 1st spinner .
Here is the code that i tried and i keep get in the log Null .
public class RechCode extends AppCompatActivity {
DatabaseReference spinnerRef;
Query spinnerRefG;
Spinner spinnerG;
Spinner spinnerD;
Spinner spinnerL;
ArrayAdapter<String> adapterG;
ArrayAdapter<String> adapterL;
ArrayAdapter<String> adapterD;
ArrayList<String> spinnerDList;
ArrayList<String> spinnerGList;
ArrayList<String> spinnerLOList;
Query spinnerRefD;
private String ChoixG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rech_code);
spinnerG = findViewById(R.id.SpinnerGouv);
spinnerD = findViewById(R.id.SpinnerDeleg);
spinnerL = findViewById(R.id.SpinnerLoc);
spinnerRef = FirebaseDatabase.getInstance().getReference().child("CodePostale");
//Query queryD = spinnerG.("state", "CA");
spinnerGList = new ArrayList<>();
spinnerDList = new ArrayList<>();
spinnerLOList = new ArrayList<>();
adapterD= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerDList);
adapterL= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerLOList);
adapterG= new ArrayAdapter<String>( RechCode.this, android.R. layout. simple_spinner_dropdown_item,spinnerGList);
spinnerG.setAdapter(adapterG);
spinnerD.setAdapter(adapterD);
spinnerL.setAdapter(adapterL);
ShowdataGouv();
spinnerRefG= FirebaseDatabase.getInstance().getReference("CodePostale").child("Deleg").orderByChild("Gouv").equalTo(ChoixG);
ShowdataDeleg();
spinnerG.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ChoixG = spinnerGList.get(i);
Toast.makeText(getApplicationContext(), "Gouvernorat:" + ChoixG, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {}
});
Button retour = (Button) findViewById(R.id.return_btn);
retour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetourMenu();
}
});
}
private void ShowdataLoc(String text) {
spinnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
for (DataSnapshot item:snapshot1.getChildren()){
spinnerLOList.add(item.child("Loc").getValue().toString());
}
adapterD.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ShowdataDeleg() {
spinnerRefG.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot2) {
for (DataSnapshot item:snapshot2.getChildren()){
spinnerDList.add(item.child("Deleg").getValue().toString());
}
Log.d("Value","BBBBBBBB"+ snapshot2);
adapterD.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void ShowdataGouv() {
spinnerRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot3) {
for (DataSnapshot item:snapshot3.getChildren()){
spinnerGList.add(item.child("Gouv").getValue().toString());
Log.d("Value","AAAAAAAAA"+ snapshot3);
}
adapterG.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
private void RetourMenu() {
Intent intent = new Intent(getApplicationContext(), Menus.class);
startActivity(intent);
}
}
The problem is in the way you construct the query here:
spinnerRefG= FirebaseDatabase.getInstance()
.getReference("CodePostale")
.child("Deleg")
.orderByChild("Gouv")
.equalTo(ChoixG);
You're asking to load child nodes of /CodePostale/Deleg that have a Gouv property with a value of ChoixG. But if we check the screenshot of the data, there is no /CodePostale/Deleg, so no data is returned.
What you want instead is to check the child nodes of /CodePostale and return the ones where their Deleg/Gouv property has a value of ChoixG, which you can do with:
spinnerRefG= FirebaseDatabase.getInstance()
.getReference("CodePostale")
.orderByChild("Deleg/Gouv")
.equalTo(ChoixG);
Related
I have an algorithm looking for Firebase data but it doesn't work and records an error to me, I want to register into Edittext Value and it will bring me the appropriate card
I use the recylerView
recyclerView= findViewById(R.id.recycleview);
getmRootFLY = FirebaseDatabase.getInstance().getReference("FLY");
list = new ArrayList<>();
arrayList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myAdapter = new MyAdapter(this,list);
recyclerView.setAdapter(myAdapter);
getmRootFLY.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren())
{
Fly fly = dataSnapshot.getValue(Fly.class);
list.add(fly);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
databaseReference = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
mRootRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid()).child("First Name");
mRootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue().toString();
TextView myLoginTextFromDB = (TextView)findViewById(R.id.hello_name_from_db);
myLoginTextFromDB.setText(name);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
EditText editTextTextPersonName = (EditText) findViewById(R.id.editTextTextPersonName);
editTextTextPersonName.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
Query query = databaseReference.child("FLY").equalTo(editable.toString());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
{
list.clear();
for (DataSnapshot dss: snapshot.getChildren())
{
final Fly fly = dss.getValue(Fly.class);
list.add(fly);
}
MyAdapter myAdapter1 = new MyAdapter(getApplicationContext(),list);
recyclerView.setAdapter(myAdapter1);
myAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
It is important to note Getmrootfly adds the card to the array and basically shows me the data available in Firebase
And all code that appears as an edittexttexteonname is a code that needs to look for the data
I'm currently making a booking app for some football fields. I have two recycler views: active bookings and cancelled bookings. I also have a custom recycler view adapter. Both of the recycler views use the same adapter.
What I want to do: if I click on a button inside my active bookings recycler view, I want to remove the booking from the active bookings and put it into my cancelled bookings. I'm gonna leave my custom adapter with the mention that I use Firebase in order to get my booking status (active or cancelled).
public class RecyclerViewAdapterRezervare extends RecyclerView.Adapter<RecyclerViewAdapterRezervare.RecycleViewHolder> {
private List<Rezervare> rezervari;
private Context context;
private LayoutInflater inflater;
private String numeUtilizator;
private String status;
private Rezervare rezervare = new Rezervare();
private DatabaseReference reff;
public RecyclerViewAdapterRezervare(List<Rezervare> rezervari, Context context, String numeUtilizator) {
this.rezervari = rezervari;
this.context = context;
this.numeUtilizator = numeUtilizator;
this.inflater = LayoutInflater.from(context);
}
#NonNull
#Override
public RecycleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.rezervari_layout, parent, false);
return new RecycleViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecycleViewHolder holder, int position) {
rezervare = rezervari.get(position);
reff = FirebaseDatabase.getInstance().getReference();
List<String> listaOre = rezervare.getOre();
Map<String, Object> mapOre = new HashMap<>();
for(String ora : listaOre){
mapOre.put(ora, false);
}
// this will return the status ("activa" is the booking is active, or "anulata" is it's cancelled)
getStatus(rezervare, new StatusCallback() {
#Override
public void onCallback(String value) {
status = value;
holder.btn_anuleaza.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("status", status);
new AlertDialog.Builder(view.getContext()).setTitle("Anulare rezervare").setMessage("Sunteti sigur ca doriti anularea rezervarii?")
.setPositiveButton(R.string.da, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// if the cancel button is clicked, i update my database so the status of the booking will be "anulata" - cancelled reff.child("Users").child(numeUtilizator).child("rezervari").child(rezervare.getData()).child(rezervare.getNumeTeren()).child("status").setValue("anulata");
reff.child("Rezervari").child(rezervare.getData()).child("Fotbal").child(rezervare.getNumeTeren()).updateChildren(mapOre);
rezervare.setEsteAnulata(false);
Toast.makeText(view.getContext(), "Anulare cu succes!", Toast.LENGTH_LONG).show();
}
}).setNegativeButton(R.string.nu, null).show();
}
});
}
});
}
#Override
public int getItemCount() {
return rezervari.size();
}
// i have updated my code with the delete and insert a booking
public void stergeRezervare(int position){
rezervari.remove(position);
notifyDataSetChanged();
}
public void adaugaRezervare(Rezervare rezervare){
rezervari.add(rezervare);
notifyDataSetChanged();
}
This is the function that gets me the bookings from firebase
i have 3 separate lists for active bookings, cancelled and past bookings.
public interface RezervariListCallback {
void onCallback(List<Rezervare> rezervariActuale, List<Rezervare> rezervariTrecute, List<Rezervare> rezervariAnulate);
}
public void getRezervari(String nume, RezervariListCallback myCallback){
reff.child("Users").child(nume).child("rezervari").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot data : snapshot.getChildren()){
String dataRezervare = data.getKey();
dateRezervari.add(dataRezervare);
reff.child("Users").child(nume).child("rezervari").child(dataRezervare).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot data : snapshot.getChildren()){
String numeTeren = data.getKey();
reff.child("Users").child(nume).child("rezervari").child(dataRezervare).child(numeTeren).child("ore").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<String> ore = new ArrayList<>();
for(DataSnapshot data : snapshot.getChildren()){
String ora = data.getKey();
ore.add(ora);
}
getAdresa(nume, dataRezervare, numeTeren, new AdresaCallback() {
#Override
public void onCallbackAdresa(String value) {
Rezervare rezervare = new Rezervare(numeTeren, ore, dataRezervare, value);
String dataAzi = getDataAzi();
reff.child("Users").child(nume).child("rezervari").child(dataRezervare).child(numeTeren).child("status").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String status = (String) snapshot.getValue();
if(comparaData(dataAzi, rezervare.getData())){
if(status.equals("activa")){
rezervariActive.add(rezervare);
} else {
rezervariAnulate.add(rezervare);
}
} else {
rezervariTrecute.add(rezervare);
}
myCallback.onCallback(rezervariActive, rezervariTrecute, rezervariAnulate);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
and this is where i set the adapters
public void updateRezervari(View view, RecyclerView activeBookingsRecycler, RecyclerView pastBookingsRecycler, RecyclerView cancelledBookingsRecycler){
AsyncTask.execute(new Runnable() {
#Override
public void run() {
getRezervari(numeUtilizator, new RezervariListCallback() {
#Override
public void onCallback(List<Rezervare> rezervariActuale, List<Rezervare> rezervariTrecute, List<Rezervare> rezervariAnulate) {
if(rezervariActuale.size()>0){
tvFaraRezervariActive.setEnabled(false);
tvFaraRezervariAnulate.setEnabled(false);
tvFaraRezervariTrecute.setEnabled(false);
}
Log.v("rezAc", rezervariActuale.toString());
Log.v("rezTr", rezervariTrecute.toString());
RecyclerViewAdapterRezervare adapter = new RecyclerViewAdapterRezervare(rezervariActuale, view.getContext(), numeUtilizator);
activeBookingsRecycler.setAdapter(adapter);
adapter = new RecyclerViewAdapterRezervare(rezervariTrecute, view.getContext(), numeUtilizator);
pastBookingsRecycler.setAdapter(adapter);
adapter = new RecyclerViewAdapterRezervare(rezervariAnulate, view.getContext(), numeUtilizator);
cancelledBookingsRecycler.setAdapter(adapter);
}
});
}
});
}
Can you give me a few tips on how to move from one recycler view to another? Thank you!
Since you are using Firebase to fetch status of a booking, you can update the status to cancelled in your firebase database and then you will get a callback from your firebase listener where you can update your arraylists and call notifyDataSetChanged().
In my firebase I have questions and their answers stored. Each answer has an id, which it got from push(). But I am unable to show the list of all the users who have answered the question. Please help.
Here is the code:
ListView listView;
ArrayList<String> answerers = new ArrayList<>();
ArrayAdapter arrayAdapter;
String askedBy, question, likes;
FirebaseAuth mAuth;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_answers);
listView = findViewById(R.id.answersListView);
Intent intent = getIntent();
askedBy = intent.getStringExtra("askedBy");
question = intent.getStringExtra("question");
likes = intent.getStringExtra("numberOfLikes");
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("questions").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
if (dataSnapshot.child("question").getValue().toString().equals(question) && dataSnapshot.child("askedBy").getValue().toString().equals(askedBy)
&& dataSnapshot.child("likes").getValue().toString().equals(likes)) {
dataSnapshot.child("answers").getRef().addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshots) {
if (snapshots.exists()){
for (DataSnapshot dataSnapshots : snapshots.getChildren()){
String id = dataSnapshot.getRef().push().getKey();
answerers.add(dataSnapshots.child(id).child("answeredBy").getValue().toString());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
arrayAdapter = new ArrayAdapter<>(ViewAnswersActivity.this, android.R.layout.simple_list_item_1, answerers);
listView.setAdapter(arrayAdapter);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent1 = new Intent(ViewAnswersActivity.this, AnswerActivity.class);
intent1.putExtra("askedBy", askedBy);
intent1.putExtra("answeredBy", answerers.get(i));
intent1.putExtra("question", question);
intent1.putExtra("numberOfLikes", likes);
startActivity(intent1);
}
});
}
When I am running the app, the listView is coming empty, indicating value hasn't been stored.
Try to set adapter within onDataChange()
#Override
public void onDataChange(#NonNull DataSnapshot snapshots) {
if (snapshots.exists()){
for (DataSnapshot dataSnapshots : snapshots.getChildren()){
String id = dataSnapshot.getRef().push().getKey();
answerers.add(dataSnapshots.child(id).child("answeredBy").getValue().toString());
}
arrayAdapter = new ArrayAdapter<> (ViewAnswersActivity.this, android.R.layout.simple_list_item_1, answerers);
listView.setAdapter(arrayAdapter);
}
}
I have a problem clearing list in fragments. I need to clear the list when happening update in fragment. I already put it in different places but it does not help me.
When an update happens in fragment it shows the same list but that list also add elements from the previous list. If I put list.clear(); in the moment when it rakes arguments from firebase it did not give me needed effect, when I put it in onCreate() method then app gives me error.
public class Favourite extends Fragment {
private RecyclerView recyclerView;
private ArrayList<TourReader1> artistList;
private ToursAdapter1 adapter1;
private DatabaseReference reference,reference2;
String uid;
public Favourite() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
//Get current user id
uid = user.getUid();
//Connect to specific point in database Tours
reference = FirebaseDatabase.getInstance().getReference("Tours");
//Create add to method valuelistener or reference which is specific point in database
reference2 = FirebaseDatabase.getInstance().getReference("user").child(uid);
reference.addValueEventListener(valueEventListener);
reference.keepSynced(true);
}
ValueEventListener valueEventListener = (new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot1) {
//get all information from specific point of database
for (DataSnapshot datasnapshot : snapshot1.getChildren()) {
//get current name of starting point from where we recive information from database
String firstname = datasnapshot.getKey();
//valuelistener for another point from database
reference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dSnapshot2:snapshot.getChildren()){
String seconame = dSnapshot2.getKey();
Boolean control = dSnapshot2.child("like").getValue(Boolean.class);
if(control != null&&firstname.equals(seconame) &&control.equals(true)) {
TourReader1 artist = datasnapshot.getValue(TourReader1.class);
artistList.add(artist);
}
}
adapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
artistList = new ArrayList<>();
View rootview = inflater.inflate(R.layout.favourite, container, false);
recyclerView = rootview.findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter1 = new ToursAdapter1(getContext(), artistList);
recyclerView.setAdapter(adapter1);
GridLayoutManager mGridLayoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(mGridLayoutManager);
return rootview;
}
}
You should clear the artistList using artistList.clear() before your for loop in onDataChangeas this list is having the data from the last callback triggered.
Ok, I found the answer myself, I clear my list in the adapter by tourlist.clear() and remove userpoints.keepSynced(true); when like icon is false.
holder.sparkButton.setEventListener(new SparkEventListener() {
#Override
public void onEvent(ImageView button, boolean buttonState) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
DatabaseReference userpoints = FirebaseDatabase.getInstance().getReference("user").child(uid);
ToursLike registerDatabase = new ToursLike(true);
if(buttonState){
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(tour.Name)) {
userpoints.child(tour.Name).setValue(registerDatabase);
userpoints.keepSynced(true);
tourList.clear();
}
else{
userpoints.child(tour.Name).child("like").setValue(true);
userpoints.keepSynced(true);
tourList.clear();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
else{
userpoints.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userpoints.child(tour.Name).child("like").setValue(false);
tourList.clear();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onEventAnimationEnd(ImageView button, boolean buttonState) {
}
#Override
public void onEventAnimationStart(ImageView button, boolean buttonState) {
}
});
}
I'm trying to get the key of a certain child value by allowing the user to choose from a Spinner.
The Spinner has "Product_Name" values as its choices. By choosing one, the program should get its key and use it to get another child value for other uses.
Example:
PRODUCTS->
-LoUXnfUCEj4k4A3dkte->
Product_Name:"Steak"
By choosing "Steak" in the Spinner, I have to get "-LoUXnfUCEj4k4A3dkte"
databaseRefSelectItem = FirebaseDatabase.getInstance().getReference("PRODUCTS");
final DatabaseReference mDatabase = databaseRefSelectItem;
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot) {
//We create an array list to hold the values brought from the database and show them in the spinner
final List<String> titleList = new ArrayList<String>();
for(final DataSnapshot snapshot : dataSnapshot.getChildren()) {
titleProduct = snapshot.child("Product_Name").getValue(String.class);
//populate the spinner with that array list
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(AddTransactionActivity.this, android.R.layout.simple_spinner_item, titleList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectProduct.setAdapter(arrayAdapter);
titleList.add(titleProduct);
//Click event for each spinner element
selectProduct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//pass the reference from that value into another snapshot in order to query those values, here you need to get your node id and inside just get your number , name and so on
selectItem = titleList.get(i);
mDatabase.child(selectItem).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot2) {
key = dataSnapshot2.getKey();
currentItemStock = dataSnapshot2.child(key).child("Current_Stock").getValue(String.class);
currentStk.setText(key);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
How can I get "-LoUXnfUCEj4k4A3dkte"?
Notes:
-LoUXnfUCEj4k4A3dkte is randomly generated.
Use .getKey() to get the key of the snapshot like:
for(final DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.child("Product_Name").getValue(String.class).equals("Steak")){
String theKey = snapshot.getKey(); //This will return -LoUXnfUCEj4k4A3dkte
}
}
Will return key of the snapshot at that reference.
Found a solution.
Thank you as well to Yash Krishan for the code snippet :).
databaseRefSelectItem = FirebaseDatabase.getInstance().getReference("PRODUCTS");
final DatabaseReference mDatabase = databaseRefSelectItem;
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot) {
//We create an array list to hold the values brought from the database and show them in the spinner
final List<String> titleList = new ArrayList<String>();
for(final DataSnapshot snapshot : dataSnapshot.getChildren()) {
titleProduct = snapshot.child("Product_Name").getValue(String.class);
//populate the spinner with that array list
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(AddTransactionActivity.this, android.R.layout.simple_spinner_item, titleList);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selectProduct.setAdapter(arrayAdapter);
titleList.add(titleProduct);
//Click event for each spinner element
selectProduct.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//pass the reference from that value into another snapshot in order to query those values, here you need to get your node id and inside just get your number , name and so on
selectItem = titleList.get(i);
if (titleProduct.equals(selectItem)){
key = dataSnapshot.child(selectItem).getKey(); //This will return -LoUXnfUCEj4k4A3dkte
}
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot2) {
for(final DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.child("Product_Name").getValue(String.class).equals(selectItem)){
key = snapshot.getKey().toString();
}
keyholder = dataSnapshot.child(key).child("Current_Stock").getValue(String.class);
}
currentStk.setText(keyholder);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});