【问题标题】:I want to get The Spinner Id from the below code not the text我想从下面的代码而不是文本中获取 Spinner Id
【发布时间】:2015-12-18 13:55:20
【问题描述】:

这是我的代码。

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"}]}

【问题讨论】:

  • 您能否提供更多信息,您究竟想要从上面的代码中得到什么?
  • 请更具体。
  • 我想获取所选项目的 id 以备将来使用...你清楚吗...?
  • APIResponse apiResponse = new Gson().fromJson(response, APIResponse.class);工资列表.clear(); //salaryList.addAll(apiResponse.getIndevSalary());工资列表.addAll(apiResponse.getExtraWork()); adapter.notifyDataSetChanged();

标签: android


【解决方案1】:

您需要项目 ID 对吗?意味着如果您点击“ZamZam Chefs1”,您需要 id = 4 Right 。 . ?

 {
  "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;
        }
    }

这是一种方式。另一个当您使“分支名称”字符串数组列表平行时,您需要创建另一个 id 的数组并在微调器的“onItemSelected”中获取该项目。

【讨论】:

  • 感谢您的回答,但是,我在选择项目时遇到错误.. 我选择了 ZamZam Accountant1 ..."java.lang.IndexOutOfBoundsException: Invalid index 6, size is 4"
【解决方案2】:

试试这个代码对你有帮助

如果你想选择 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();
        }
       }

【讨论】:

  • 谢谢...我在这里获取所选项目的文本,但我需要所选项目的 ID
  • 嘿,为 id 添加一个新的数组列表,然后您可以选择 id see here
  • 帮助很大,对我有很大帮助
猜你喜欢
  • 2021-12-21
  • 2021-08-15
  • 2011-07-29
  • 1970-01-01
  • 2020-01-30
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多