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);
本文介绍了一种使用HTTP请求从服务器获取数据,并将其动态填充到Android应用中的Spinner组件的方法。通过解析JSON数据,创建适配器并设置给Spinner,实现了根据服务器返回的数据更新UI的功能。
285

被折叠的 条评论
为什么被折叠?



