简体   繁体   中英

Access fields of an object in an array Java

I am retrieving some data from Firebase, both name and id and I want to store that in an array and afterwards populate a spinner only with the name value.

for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    People p = snapshot.getValue(People.class);
                    peopleArray.add(new String[]{p.name, String.valueOf(p.id)});
                }

                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, (List<String>) peopleArray);
                spinner.setAdapter(dataAdapter);

In the ArrayAdapter I want to show only the names stored in peopleArray. How can I do that?

   List<People > people = new ArrayList<>();  
   List<String> peoplename = new ArrayList<>();       
   for(People people : people) {
        System.out.println(people.getName());
       // add name in separate list then assign to spinner.
       peoplename.add(people.getName());
    }

Set spinner

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line, peoplename);

Try this! I hope this helps you

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line);

    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
        People p = snapshot.getValue(People.class);

        //just adding id in list use later
        peopleArray.add(String.valueOf(p.id));

        //adding each name to your adapter
        dataAdapter.add(p.name);
    }


    spinner.setAdapter(dataAdapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            // get pID from peopleArray when item is selected 
            String pId = peopleArray.get(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM