在spinner android中获取所选项的Id

时间:2014-04-17 07:01:09

标签: android

这里,这是我的java文件

public class Create_Event extends SherlockFragment 
implements OnClickListener {

    class Organizer extends AsyncTask<Void, Void, Object> {

        private ProgressDialog pdia;

        protected void onPreExecute() {
            super.onPreExecute();
            pdia = new ProgressDialog(getActivity());
            pdia.setMessage("Loading...");
            pdia.show();
        }

        @Override
        protected Object doInBackground(Void... params) {

            try {
                HttpClient httpclient1 = new DefaultHttpClient();
                HttpPost httppost1 = new HttpPost(Constants.BASE_URL
                        + "mobile_logins/all_my_event");
                List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(1);
                nameValuePairs1.add(new BasicNameValuePair("id", Constants.id));
                httppost1.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
                HttpResponse response1 = httpclient1.execute(httppost1);
                String _response1 = EntityUtils.toString(response1.getEntity());
                Log.e("test", _response1); 
                jsobj1 = new JSONObject(_response1);
                orr = jsobj1.getJSONArray("organizers");
                String orggg = orr.toString();
                Log.e("Organization", orggg);
                return jsobj1;

            } catch (Exception e) {
                e.printStackTrace();
                Log.e("Fail 1", e.toString());
                return e;
            }
        }

        protected void onPostExecute(Object jsobj) {
            pdia.dismiss();

            String post = jsobj.toString();
            Log.e("event_rese", post);
            int len = orr.length();

            Log.e("json_posexe", orr.toString());
            Log.e("Onpostexe_arrlength", String.valueOf(len));

            try {
                JSONArray JA = orr;
                JSONObject json1 = null;
                final String[] host1 = new String[orr.length()]; 
                final String[] host_id=new String[orr.length()];

                for(int i = 0; i < len; i++) {
                    json1 = JA.getJSONObject(i);
                    host1[i] = json1.getString("name");
                    host_id[i] = json1.getString("id");
                }

                List<String> list = new ArrayList<String>();
                for(int i = 0; i < host1.length; i++) {
                    list.add(host1[i]);
                }
                Log.e("onpostexe_list",list.toString());

                ArrayAdapter<String> adapter = 
                        new ArrayAdapter<String>(getActivity().getApplicationContext(),
                                 android.R.layout.simple_spinner_item,list);
                adapter.setDropDownViewResource(
                        android.R.layout.simple_spinner_dropdown_item);
                sp.setAdapter(adapter);
                sp.setOnItemSelectedListener(new OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> arg0, View arg1,
                            int position, long id) {
                        organization=sp.getSelectedItem().toString();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub
                    }
                });


            } catch(Exception e) {
                Log.e("Fail 3", e.toString());
            }


            if (json instanceof JSONObject) {
                asyncrun = true;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

                } else {
                    ExecptionHandler.register(getActivity(), (Exception) jsobj);
                }
            }

        }

    }
}

在这里,我需要来自微调器的所选组织的id。 id和组织名称来自Jsonobject(这里是jsobj1)。如何从jsonobject获取所选项目的ID?可能吗??请帮忙......

3 个答案:

答案 0 :(得分:0)

mSpinner.getSelectedItemId(); // here is your selected item's Id.
首先是BTW谷歌,稍后再问:)

答案 1 :(得分:0)

是的,可能,请尝试如下。

HashMap<String,String> map_values = new HashMap<String,String>();
for(int i = 0; i < len; i++) {
      json1 = JA.getJSONObject(i);
      host1[i] = json1.getString("name");
      host_id[i] = json1.getString("id");
      map_values.put(host1[i],host_id[i]);
}

和spinner

  sp.setOnItemSelectedListener(new OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int position, long id) {
                    String value = sp.getSelectedItem().toString();
                    String id = map_values.get(value);

                    Log.v("id",""+id);
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub
                }
            });

答案 2 :(得分:0)

使用方法Organization如下创建一个@Override toString() bean

public class Organization {

    private Integer orgId; // Long etc.

    private String orgName;

    // more properties if you need


    @Override  // Mandatory
    public String toString() {
        return orgName; // Return anything, what you want to show in spinner
    }

    // Getter & Setter
}

然后根据您的java.util.List<Organization> organizationList;响应API或其他任何方式创建一个JSONArray。并设置并设置ArrayAdapter<Organization>来加载Spinner选项。

List<Organization> organizationList = ... // init using JSON Data OR any how;

ArrayAdapter<Organization> orgAdapter = new ArrayAdapter<Organization>(this, android.R.layout.simple_spinner_item, organizationList);
orgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Spinner mySpinner = findViewById(R.id.orgSpinner);
mySpinner.setAdapter(orgAdapter);

现在在如下所示的任何Click / Change事件中获取选定的组织及其属性

// In any OnClick / OnSelect event
Organization selectedOrganization = (Organization) mySpinner.getSelectedItem();
Integer orgId = selectedOrganization.getOrgId();
String orgName = selectedOrganization.getOrgName();
// and if you have more properties
相关问题