我想从下面的代码而不是文本中获取Spinner Id

时间:2015-12-17 13:17:05

标签: android

这是我的代码。

public class EmployeeProfile extends AppCompatActivity {

    Spinner spinnerbranches;

    ArrayList<String> branchnames;

    JSONArray branches=new JSONArray();

    Integer branchid=0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_employee_profile);

        ColorDrawable colorDrawable = new 
        ColorDrawable(Color.parseColor("#f43f10"));
        getSupportActionBar().setBackgroundDrawable(colorDrawable);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        spinnerbranches = (Spinner) findViewById(R.id.EmpbranchesSpinner);
      getBrach();
    }

      private void getBrach(){
        // Spinner spinnerbranches;
        // ArrayList<String> branchnames;
        // JSONArray branches;
        //Creating a string request
        StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://zamzamapp.azurewebsites.net/api/Branches",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {



                            //Parsing the fetched Json String to JSON Object
                            JSONObject j = new JSONObject(response);

                            //Storing the Array of JSON String to our JSON Array
                            branches = j.getJSONArray("DDL");

                            //Calling method getStudents to get the students from the JSON Array
                            getBranchs(branches);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        //Creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //Adding request to the queue
        requestQueue.add(stringRequest);
    }

    private void getBranchs(JSONArray jsonArray){
        //Traversing through all the items in the json array
        branchnames=new ArrayList<String>();
        for(int i=0;i<jsonArray.length();i++){
            try {
                //Getting json object
                JSONObject json = jsonArray.getJSONObject(i);

                //Adding the name of the student to array list
                branchnames.add(json.getString("name"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        spinnerbranches.setAdapter(new ArrayAdapter<String>(EmployeeProfile.this, android.R.layout.simple_spinner_dropdown_item, branchnames));
       // spinnerbranches.setSelection(Integer.parseInt(branch));
        spinnerbranches.setSelection(((ArrayAdapter<String>) spinnerbranches.getAdapter()).getPosition(branch));
        spinnerbranches.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                branchid = (int) id + 1;


            }

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

            }
        });
    }

这是我的Json数组

{"DDL":[{"Id":1,"name":"ZamZam Managers1"},{"Id":3,"name":"ZamZam Managers2"},{"Id":4,"name":"ZamZam Chefs1"},{"Id":7,"name":"ZamZam Chefs2"},{"Id":8,"name":"ZamZam Waiting staff1"},{"Id":10,"name":"ZamZam Waiting staff2"},{"Id":11,"name":"ZamZam Accountant1"}]}

2 个答案:

答案 0 :(得分:1)

你需要物品ID吗?意味着如果你点击'ZamZam Chefs1'你需要id = 4对。 。 ?

 {
  "Id": 4,
  "name": "ZamZam Chefs1"
}

如果你需要同样的东西?然后你可以做一件事,当'onItemSelected'你可以做

        String name = branchnames.get(position);
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject obj = jsonArray.optJSONObject(i);
        if (obj.optString("name").equalsIgnoreCase(name)) {
            requiredID = obj.optInt("name");
            break;
        }
    }
这是一种方式。另一个当你将'branchnames'字符串数组列表并行时,你需要创建另一个id的数组,并在你的微调器的'onItemSelected'中获得该位置。

答案 1 :(得分:0)

试试这段代码帮助你

如果你想选择id那么

        public void onResponse(String response) {
           try {
            jsonarray = jsonobject.getJSONArray("data");
            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);
                Json_Data opt_code = new Json_Data();
                opt_code.setName(jsonobject.optString("name"));
                opt_code.setId(jsonobject.optString("ID"));
                json_data.add(opt_code);
                datalist.add(jsonobject.optString("ID"));

                }
              }
               catch (Exception e) {
               Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
       }