2016-01-06 136 views
0

我正在使用spinner.I想使用包含熟练ID和从服务器接收的名称的json数据填充微调器。我将接收的数据存储在Bean_ProficiencyLevel它包含id和name.I使用一个名为Adapter_Proficiency的自定义数组适配器,它只加载文本视图的名称。我使用此适配器来填充spinner.I在这里得到意外的结果.Spinner显示如下所示的值:无法使用动态JSON数据填充微调器

1.截图

Sceenshot

点击任何项目后,我得到预期的价值。优秀如下图:

2.截图

SceenShot

我无法找出为什么在转我得到不适当的数据之前上市下面给出selection.My码:

Adapter_Proficiency.java

public class Adapter_Proficiency extends ArrayAdapter<Bean_ProficiencyLevel> { 
private ArrayList<Bean_ProficiencyLevel> items; 
private ArrayList<Bean_ProficiencyLevel> itemsAll; 
private ArrayList<Bean_ProficiencyLevel> suggestions; 
private int viewResourceId; 

public Adapter_Proficiency(Context context, int viewResourceId, ArrayList<Bean_ProficiencyLevel> items) { 
    super(context, viewResourceId, items); 
    this.items = items; 
    this.itemsAll = (ArrayList<Bean_ProficiencyLevel>) items.clone(); 
    this.suggestions = new ArrayList<Bean_ProficiencyLevel>(); 
    this.viewResourceId = viewResourceId; 
} 

public View getView(int position, View v, ViewGroup parent) { 
    if (v == null) { 
     LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = inflater.inflate(viewResourceId,parent,false); 
    } 
    Bean_ProficiencyLevel bean_proficiencyLevel = items.get(position); 
    if (bean_proficiencyLevel != null) { 
     TextView txtProficiency = (TextView) v.findViewById(R.id.txtProficiency); 
     if (txtProficiency != null) { 
      txtProficiency.setText(bean_proficiencyLevel.getProficiencyValue()); 
     } 
    } 
    return v; 
} 

@Override 
public Filter getFilter() { 
    return nameFilter; 
} 

Filter nameFilter = new Filter() { 
    @Override 
    public String convertResultToString(Object resultValue) { 
     String str = ((Bean_ProficiencyLevel) (resultValue)).getProficiencyValue(); 
     return str; 
    } 

    @Override 
    protected FilterResults performFiltering(CharSequence constraint) { 
     if (constraint != null) { 
      suggestions.clear(); 
      for (Bean_ProficiencyLevel bean_proficiencyLevel : itemsAll) { 
       if (bean_proficiencyLevel.getProficiencyValue().toLowerCase().startsWith(constraint.toString().toLowerCase())) { 
        suggestions.add(bean_proficiencyLevel); 
       } 
      } 
      FilterResults filterResults = new FilterResults(); 
      filterResults.values = suggestions; 
      filterResults.count = suggestions.size(); 
      return filterResults; 
     } else { 
      return new FilterResults(); 
     } 
    } 

    @Override 
    protected void publishResults(CharSequence constraint, FilterResults results) { 
     ArrayList<Bean_ProficiencyLevel> filteredList = (ArrayList<Bean_ProficiencyLevel>) results.values; 
     if (results != null && results.count > 0) { 
      clear(); 
      for (Bean_ProficiencyLevel c : filteredList) { 
       add(c); 
      } 
      notifyDataSetChanged(); 
     } 
    } 
}; 
} 

Tab_TechnicalSkills.java

public class Tab_TechincalSkills extends Activity { 

private ListView lv_technicalSkills; 
String URL_GetAllSkillDetails, URL_GetAllProficiencyLevel; 
private APIConfiguration apiConfiguration; 
private SharedPreferences prefs; 
private ArrayList<Bean_Skill> arrayList; 
private ArrayList<Bean_ProficiencyLevel> arrayListProficiency; 
private Adapter_Skill adapter_skill; 
AutoCompleteTextView actv_skill, actv_proficiency; 
HttpRequestProcessor httpRequestProcessor; 
Bean_Skill bean_skill; 
Spinner sp_proficiency; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.tab_technical_skill); 
    //findViewByID 
    actv_skill = (AutoCompleteTextView) findViewById(R.id.actv_skillName); 
    //actv_proficiency = (AutoCompleteTextView) findViewById(R.id.actv_proficiency); 
    sp_proficiency = (Spinner) findViewById(R.id.sp_proficiency); 
    arrayList = new ArrayList<Bean_Skill>(); 
    arrayListProficiency = new ArrayList<Bean_ProficiencyLevel>(); 
    httpRequestProcessor = new HttpRequestProcessor(); 
    lv_technicalSkills = (ListView) findViewById(R.id.lv_Technical_Skills); 
    prefs = getApplicationContext().getSharedPreferences(Prefs_Registration.pacakgename, Context.MODE_PRIVATE); 
    //Get userID 
    String userID = prefs.getString(Prefs_Registration.get_user_id, ""); 
    //Get Access token 
    String accessToken = prefs.getString(Prefs_Registration.get_AccessToken, ""); 
    //Get Api_end_point 
    apiConfiguration = new APIConfiguration(); 
    String api = apiConfiguration.getApi(); 
    URL_GetAllSkillDetails = api + "/webservice/getAllSkills?user_id=" + userID + "&access_token=" + accessToken; 
    URL_GetAllProficiencyLevel = api + "/webservice/getProficiencyLevels?user_id=" + userID + "&access_token=" + accessToken; 
    //Get listing of skills 
    new SkillDetailsTask().execute(); 
    //Get all proficiency levels 
    new ProficiencyLevelDetailsTask().execute(); 
} 

//Get list of all skills 
class SkillDetailsTask extends AsyncTask<String, String, String> { 
    @Override 
    protected String doInBackground(String... strings) { 
     String response = httpRequestProcessor.gETRequestProcessor(URL_GetAllSkillDetails); 
     return response; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     Log.e("JSONARRAY", s); 
     try { 
      JSONArray jsonArray = new JSONArray(s); 
      for (int i = 0; i < jsonArray.length(); i++) { 
       JSONObject jsonObject = jsonArray.getJSONObject(i); 
       String id = jsonObject.getString("id"); 
       String text = jsonObject.getString("text"); 

       // Adding data to Bean 
       bean_skill = new Bean_Skill(); 
       bean_skill.setSkill_id(id); 
       bean_skill.setSkill_name(text); 

       //Adding bean object to array 
       arrayList.add(bean_skill); 
      } 
      Adapter_Skill adapter_skill = new Adapter_Skill(Tab_TechincalSkills.this, R.layout.single_row_skill, arrayList); 
      actv_skill.setAdapter(adapter_skill); 
      actv_skill.setThreshold(2); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

class ProficiencyLevelDetailsTask extends AsyncTask<String, String, String> { 
    @Override 
    protected String doInBackground(String... strings) { 
     String response = httpRequestProcessor.gETRequestProcessor(URL_GetAllProficiencyLevel); 
     Log.e("ResponseProficiency", response); 
     return response; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     try { 
      JSONArray jsonArray = new JSONArray(s); 


      for (int i = 0; i < jsonArray.length(); i++) { 
       JSONObject jsonObject = jsonArray.getJSONObject(i); 
       String id = jsonObject.getString("id"); 
       Log.e("idProficiency", id); 
       String name = jsonObject.getString("name"); 
       Bean_ProficiencyLevel bean = new Bean_ProficiencyLevel(); 

       //Adding data to Bean 
       bean.setId(id); 
       bean.setProficiencyValue(name); 

       //Adding bean to ArrayList 
       arrayListProficiency.add(bean); 
      } 
      Adapter_Proficiency adapter_proficiency = new Adapter_Proficiency(Tab_TechincalSkills.this, R.layout.single_row_proficiency, arrayListProficiency); 
      sp_proficiency.setAdapter(adapter_proficiency); 
      /*actv_proficiency.setAdapter(adapter_proficiency); 
      actv_proficiency.setThreshold(0);*/ 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
} 


} 

Bean_ProficiencyLevel.java

public class Bean_ProficiencyLevel { 
String id, proficiencyValue; 

public String getId() { 
    return id; 
} 

public void setId(String id) { 
    this.id = id; 
} 

public String getProficiencyValue() { 
    return proficiencyValue; 
} 

public void setProficiencyValue(String proficiencyValue) { 
    this.proficiencyValue = proficiencyValue; 
} 

}

HttpRequestProcessor.java

public class HttpRequestProcessor { 
String jsonString, requestMethod, requestURL, jsonResponseString, responseCode; 
StringBuilder sb; 
Response response; // Response class will store http JSON Response string and Response Code 

// This method will process POST request and return a response object containing Response String and Response Code 
public Response pOSTRequestProcessor(String jsonString, String requestURL) { 
    sb = new StringBuilder(); 
    response = new Response(); 
    try { 
     // Sending data to API 
     URL url = new URL(requestURL); 
     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 
     httpURLConnection.setDoInput(true); 
     httpURLConnection.setDoOutput(true); 
     httpURLConnection.setRequestMethod("POST"); 
     httpURLConnection.setRequestProperty("Content-Type", "application/json"); 
     httpURLConnection.setReadTimeout(15000); 
     httpURLConnection.setConnectTimeout(15000); 
     OutputStreamWriter out = new OutputStreamWriter(httpURLConnection.getOutputStream()); 
     out.write(jsonString); // Transmit data by writing to the stream returned by getOutputStream() 
     out.flush(); 
     out.close(); 
     // Read the response 
     InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream()); 
     InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
     BufferedReader br = new BufferedReader(inputStreamReader); 
     String responseData = br.readLine(); 
     while (responseData != null) { 
      sb.append(responseData); 
      responseData = br.readLine(); 
     } 
     // Reading the response code 
     int responseCode = httpURLConnection.getResponseCode(); 
     // Log.e("Response Code", String.valueOf(responseCode)); 
     response.setResponseCode(responseCode); 
     br.close(); 
     httpURLConnection.disconnect(); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    jsonResponseString = sb.toString(); 
    response.setJsonResponseString(jsonResponseString); 
    return response; //return response object 
} 

// This method will process http GET request and return json response string 
public String gETRequestProcessor(String requestURL) { 
    sb = new StringBuilder(); 
    try { 
     URL url = new URL(requestURL); 
     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
     urlConnection.setRequestMethod("GET"); 
     urlConnection.setRequestProperty("Content-Length", "0"); 
     int status = urlConnection.getResponseCode(); 
     Log.e("Status", String.valueOf(status)); 
     InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream()); 
     BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 
     String responseData = br.readLine(); 
     while (responseData != null) { 
      sb.append(responseData); 
      responseData = br.readLine(); 
     } 
     br.close(); 
     urlConnection.disconnect(); 
    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (ProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    jsonResponseString = sb.toString(); 
    return jsonResponseString; 
} 

public String pUTRequestProcessor(String jsonString, String requestURL) { 
    sb = new StringBuilder(); 
    try { 
     //sending data to API 
     URL urlMobileUser = new URL(requestURL); 
     HttpURLConnection urlConnection = (HttpURLConnection) urlMobileUser.openConnection(); 
     urlConnection.setDoInput(true); 
     urlConnection.setDoOutput(true); 
     urlConnection.setRequestMethod("PUT"); 
     urlConnection.setRequestProperty("Content-Type", "application/json"); 
     urlConnection.setReadTimeout(15000); //Sets the maximum time to wait for an input stream read to complete before giving up 
     urlConnection.setConnectTimeout(15000); //Sets the maximum time in milliseconds to wait while connecting 
     OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); 
     out.write(jsonString); 
     out.flush(); 
     out.close(); 
     //getting response from API 
     InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream()); 
     BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); 
     String responseData = br.readLine(); 
     while (responseData != null) { 
      sb.append(responseData); 
      responseData = br.readLine(); 
     } 
     br.close(); 
     urlConnection.disconnect(); 
    } catch (Exception ex) { 
     Log.e("Connection error", ex.toString()); 
    } 
    jsonResponseString = sb.toString(); 
    // Log.e("JSON Response String", jsonResponseString); 
    return jsonResponseString; 
} 

}

请帮我解决这个问题。

回答

1

您的ArrayAdapter适配器__适用于ListView,但对于spinners您需要另一种方法。为了微调,以显示正确的价值观,你需要重写的另一种方法,该方法getDropDownView不管你做什么在getView方法,像这样:

@Override  
public View getDropDownView(int position, View v, ViewGroup parent) { 
    if (v == null) { 
     LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = inflater.inflate(viewResourceId,parent,false); 
    } 
    Bean_ProficiencyLevel bean_proficiencyLevel = items.get(position); 
    if (bean_proficiencyLevel != null) { 
     TextView txtProficiency = (TextView) v.findViewById(R.id.txtProficiency); 
     if (txtProficiency != null) { 
      txtProficiency.setText(bean_proficiencyLevel.getProficiencyValue()); 
     } 
    } 
    return v; 
} 
+0

user3597165,这意味着,我必须同时使用getView()和getDropDownView()方法。当我只使用getDropDownView()方法,下拉显示的是正确的值,但在选择后在视图上设置了十六进制值。当我同时使用getView()和getDropDownView()方法时,其工作良好,但需要一些时间进行选择。感谢您的帮助user3597165。 –

0

我不是在适配器进入的具体细节,但在该行

txtProficiency.setText(bean_proficiencyLevel.getProficiencyValue()); 

你对象名称设置为TextView的
检查 getProficiencyValue()功能,我肯定你是返回一个Bean_ProficiencyLevel的对象通过调用toString(),将其更改并使其返回正确的字符串值 也可以建议您使用Gson库来反序列化数据和RetroFit网络调用?您使用的方法在android编程标准中已经过时了

+0

bean_proficiencyLevel。getProficiencyValue()是给我的字符串data.So txtProficiency.setText(bean_proficiencyLevel.getProficiencyValue());正在设置字符串值。我检查了它。 –

+0

你也可以发布功能代码吗? – insomniac

+0

哪些功能代码?你可以指定吗? –