微调饲料类
public class SpinnerFeed {
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
} 从 url 获取记录的函数
public String readFeed() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
// domain intentionally obfuscated for security reasons
HttpGet httpGet = new HttpGet("statesURL");
try
{
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(MainActivity.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return builder.toString();
}
最后我的微调器代码正在工作,
String readFeed = readFeed();
// you can use this array to find the state ID based on name
ArrayList<SpinnerFeed> allStates = new ArrayList<SpinnerFeed>();
// you can use this array to populate your spinner
ArrayList<String> states_array = new ArrayList<String>();
try {
JSONObject json = new JSONObject(readFeed);
JSONArray jsonArray = new JSONArray(json.optString("states"));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SpinnerFeed statespinner = new SpinnerFeed();
statespinner.setName(jsonObject.optString("stateName"));
statespinner.setId(jsonObject.optString("stateID"));
allStates.add(statespinner);
states_array.add(jsonObject.optString("stateName"));
}
} catch (Exception e) {
e.printStackTrace();
}
Spinner spinner = (Spinner) findViewById(R.id.planets_spinner);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, states_array));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object item = parent.getItemAtPosition(position);
int pos = parent.getSelectedItemPosition();
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
我只能弄清楚如何获取所选项目的 ID
parent.getItemAtPosition(position); //gives me name
parent.getSelectedItemPosition(); //gives me position
提前致谢