Search code examples
androidandroid-studiospinnerandroid-spinner

Value not displaying Correctly in Spinner Android


I have a Spinner in which I want value from Firebase Database. I try what I Know since I am new to Android but the value in Spinner is not coming as i want it is coming like this.

Spinner Image enter image description here

When i am passing String Array directly it is coming Properly but it is doing problem when the String Array fill with the Firebase data.Here is also my Database.

final String[] batcht = {"1903f","343","33323"};

enter image description hereenter image description here

XML

    <Spinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/stubatch"
    />

JAVA

public class Student extends AppCompatActivity {
 DatabaseReference ref;
 Spinner spinner;
 List<String> store;
 String[] batchlist;
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_student);
   spinner = findViewById(R.id.stubatch);

    store =new ArrayList<>();

    Student_ID =getIntent().getStringExtra("Student_Id");
    ref = FirebaseDatabase.getInstance().getReference("Batch");

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot batches : dataSnapshot.getChildren()){
                    String a= batches.getValue().toString();
                    store.add(a);
                }

            batchlist = new String[store.size()];

            for(int i=0;i<batchlist.length;i++){
                batchlist[i]=store.get(i);

            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String> 
            (getApplicationContext(),android.R.layout.simple_spinner_item,batchlist);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
            spinner.setAdapter(adapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}}

I don't know what I am doing wrong.


Solution

  • When you are fetching data you are doing some mistake. You are not fetching according to ur insertion technique try this In for loop of datasnapshot use this code:

    String a = batches.child("1710f").getValue().toString()
    

    By doing this only data with the 1710f key will be picked for other values you have listed out all the keys. Hopefully, this will workout