Reputation: 439
I have this structure in the database
Categorias_Produtos
- ID
---nome: Nome1
- ID
---nome: Nome2
I'm displaying the data in a Spinner and capturing the name of the returned data. And it's okay.
But I'd like to capture the Id of this returned data, and I do not know how to do that?
Code:
mDatabaseCategorias = FirebaseDatabase.getInstance().getReference().child("Categorias_Produtos");
mResultadoCat = (TextView) findViewById(R.id.tvresultadoSpinnerCat);
mDatabaseCategorias.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> categorias = new ArrayList<>();
for( DataSnapshot categoriasSnapshot: dataSnapshot.getChildren() ){
String nomeCateg = categoriasSnapshot.child("nome").getValue(String.class);
categorias.add(nomeCateg);
}
//spiners resultado
mSpinnerCateg = (Spinner) findViewById(R.id.spinnerCateg);
ArrayAdapter<String> categoriasAdapter = new ArrayAdapter<String>(CadastroServico.this, android.R.layout.simple_spinner_item, categorias);
categoriasAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerCateg.setAdapter(categoriasAdapter);
mSpinnerCateg.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String resultado = parent.getItemAtPosition(position).toString();
mResultadoCat.setText(resultado);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
From what I understand I would need to somehow send the item ID along with his name, to Spinner and from there retrieve that information.
I would like some ideas please !!
Upvotes: 1
Views: 352
Reputation: 1311
I recommend you to store your ID duplicated under the root ID, this will simplify things for you when you want to retrieve data. DENORMALIZATION is the magic word for firebase or any JSON nosql database.
Categorias_Produtos
- 15
---nome: Nome1
---id: 15
- 16
---nome: Nome2
---id: 16
Upvotes: 1
Reputation: 3044
Create a list.
List<SpinnerModel> list;
list = new ArrayList<>();
Query your firebase and add what you have into this list...into a new model.
list.add(new SpinnerModel(objectID, objectName));
Create a model.
public class SpinnerModel {
String objectID;
String objectName;
public SpinnerModel(String objectID, String objectName){
this.objectID = objectID;
this.objectName = objectName;
}
create getters....
}
You can use the list and the getters to fill up your spinner. And then whatever you click, you can use the getObjectID to get the id.
Upvotes: 1