How do I parse a JSON file like the one below containing school names and IDs and use the values in the "Name" field to populate the spinner lables?
I want the spinner to output the selected SchoolID to the next activity. E.g. So you see "Hill View Elementary" and if you select this the value "HVE" is output to the next activity to act on.
{
"schools": [
{
"Name": "Hill View Elementary",
"SchoolID": "HVE"},
{
"Name": "Mill View",
"SchoolID": "MVE"},
{
"Name": "Big School",
"SchoolID": "BSC"},
]
}
Here is the onCreate I'm using to attempt to read the feed...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String readFeed = readFeed();
try {
JSONArray jsonArray = new
JSONArray(readFeed);
Log.i(MainActivity.class.getName(),
"Number of entries " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here instead of Logging I want to use each schools "Name" to
// be put into an array that I can use to populate the strings
// for the spinner
Log.i(MainActivity.class.getName(), jsonObject.getString("schools"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
I'm still coming up to speed on Android so clarity appreciated.
Here is readfeed:
public String readFeed() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
// domain intentionally obfuscated for security reasons
HttpGet httpGet = new HttpGet("http://www.domain.com/schools.php");
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();
}