How do I populate an Android spinner using a JSON web service?

后端 未结 1 896
花落未央
花落未央 2021-01-03 16:09

How do I parse a JSON file like the one below containing school names and IDs and use the values in the \"Name\" field to populate the spinner lables?

I want the sp

1条回答
  •  时光取名叫无心
    2021-01-03 16:41

    I would do something like this:

    public class School {
        private String name;
        private String id;
    
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
    }
    

    On create:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);  
    
        String readFeed = readFeed();
    
        // you can use this array to find the school ID based on name
        ArrayList schools = new ArrayList();
        // you can use this array to populate your spinner
        ArrayList schoolNames = new ArrayList();
    
        try {
          JSONObject json = new JSONObject(readFeed);
          JSONArray jsonArray = new JSONArray(json.optString("schools"));
          Log.i(MainActivity.class.getName(),
              "Number of entries " + jsonArray.length());
    
          for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
    
            School school = new School();
            school.setName(jsonObject.optString("Name"));
            school.setId(jsonObject.optString("SchoolID"));
            schools.add(school);
            schoolNames.add(jsonObject.optString("Name"));
    
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
        Spinner mySpinner = (Spinner)findViewById(R.id.my_spinner);
        mySpinner.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, schoolNames));
    }
    

    In your main_activity.xml you need a Spinner. The code above would work with a Spinner named like below:

    
    

    0 讨论(0)
提交回复
热议问题