访问数组Java中对象的字段

时间:2017-05-21 04:34:28

标签: java android firebase android-arrayadapter

我正在从Firebase中检索一些数据,包括name和id,我想将它存储在一个数组中,然后只使用名称值填充一个微调器。

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);

在ArrayAdapter中,我想只显示存储在peopleArray中的名称。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

   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());
    }

设置微调器

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

答案 1 :(得分:0)

试试这个!我希望这可以帮助你

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) {

        }
    });