无法使用动态JSON数据填充Spinner

时间:2016-01-06 13:03:50

标签: android json android-spinner

我正在一个有旋转器的屏幕上工作。我想用包含从服务器接收的熟练度id和名称的json数据填充微调器。我正在存储在Bean_ProficiencyLevel中接收的数据。它包含id和name.I我正在使用一个名为Adapter_Proficiency的自定义数组适配器,它仅使用名称加载文本视图。我正在使用此适配器来填充spinner。我在这里得到了意想不到的结果.Spinner正在显示如下所示的值:

1。截图

Sceenshot

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

2。截图

SceenShot

我无法找到为什么在微调器的列表中我在选择之前得到了不适当的数据。我的代码如下:

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

}

请帮我解决问题。

2 个答案:

答案 0 :(得分:1)

您的ArrayAdapter Adapter_Proficiency非常适合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;
}

答案 1 :(得分:0)

我不会进入具体的细节,而是在适配器的行中

txtProficiency.setText(bean_proficiencyLevel.getProficiencyValue());

您正在将对象名称设置为textView
校验 getProficiencyValue()函数,我很肯定您通过调用Bean_ProficiencyLevel来返回toString()的对象,更改它并使其返回正确的字符串值 我也建议您使用Gson库反序列化数据和RetroFit进行网络调用?您现在使用的方法在Android编程标准中已经过时了