android从网站获取json接口数据并放置到spinner
程序员文章站
2022-07-04 18:50:50
...
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/android/classname_spinner.php");
try{
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,responseHandler);
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("output");
arr = new String[jArray.length()+1];
arr[0] = "-select-";
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String sclass = json_data.getString("spinner");
arr[i+1] = sclass;
}
}catch (Exception e) {
Log.e("log_tag","Error parsing classname data"+e.toString());
}
}catch (Exception e) {
Log.e("log_tag","Request failed"+e.toString());
}
在activity的create方法中进行初始化
classSpinner = (Spinner) findViewById(R.id.editClass);
ArrayAdapter<String> classNameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,arr);
classNameAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
classSpinner.setAdapter(classNameAdapter);
下一篇: jdbc原生