2015-06-22 102 views
-4

我正在开发一个带有微调器的android应用程序。 微调项目和微调值是不同的。我想从包括微调框中收集所有的值,并设置一个休息api服务到web后端。这里是响应数组。在Android中使用自定义适配器为Spinner设置值

{"Status":true,"errorType":null,"countryList":[{"Code":"US","Name":"United States"},{"Code":"CA","Name":"Canada"},{"Code":"AU","Name":"Australia"},{"Code":"GB","Name":"United Kingdom"}]} 

我成功绑定的名称的JSONObject来微调器,但我不能添加代码

这是我的代码。

JSONObject responseObject = new JSONObject(res); 
      String status=responseObject.getString("Status"); 
      JSONArray JA = responseObject.getJSONArray("countryList"); 
      JSONObject json= null; 


      if(status.equals("true")) { 

       final String[] str2 = new String[JA.length()]; 
       for (int i=0;i<JA.length();i++) 
       { 
        json = JA.getJSONObject(i); 
        str2[i] = json.getString("Name"); 
       } 

       sp = (Spinner) findViewById(R.id.citnzshp_field); 
       list = new ArrayList<String>(); 

       for(int i=0;i<str2.length;i++) 
       { 
        list.add(str2[i]); 

       } 
       Collections.sort(list); 

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

       sp.setAdapter(adp); 


      } 

我如何可以将绑定在代码的JSONObject来微调器的表单提交后服用。

任何人都可以请分享我制作自定义适配器绑定数据到微调和选择价值也的优势。

+1

退房:http://stackoverflow.com/questions/24712540/set-key-and-value-in-spinner/24712664#24712664 –

回答

2

@Haresh Chhelana示例很好,但是如果您想在选择后在微调器中显示名称和代码,请检查此项。

List<Map<String, String>> items = new ArrayList<Map<String, String>>(); 

    for (int i = 0; i < JA.length(); i++) { 
     json = JA.getJSONObject(i); 
     mapData = new HashMap<String, String>(); 
     mapData.put("name", json.getString("Name")); 
     mapData.put("code", json.getString("Code")); 
     items.add(mapData); 
    } 

    SimpleAdapter adapter = new SimpleAdapter(this, items, android.R.layout.simple_list_item_2, new String[] { 
      "name", "code" }, new int[] { android.R.id.text1, android.R.id.text2 }); 
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    spinner.setAdapter(adapter); 

和微调框所选项目的回调

spinner.setOnItemSelectedListener(new OnItemSelectedListener() { 

      @Override 
      public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 
       Map<String, String> selectedItem = (Map<String, String>) parent.getSelectedItem(); 
       String name=selectedItem.get("name"); 
       String code=selectedItem.get("code"); 
      } 

      @Override 
      public void onNothingSelected(AdapterView<?> parent) { 
      } 
     }); 
+0

@ barath,工作正常...真棒..谢谢 – Jishad

+0

欢迎...快乐编码 – Bharatesh

+0

@bharath,为什么此代码不适用于autocompleteTextView – Jishad

相关问题