I'm working my way through Head First Android Development, and I am having an issue. I'm trying to use the following code and populate the listview with an array returned from a method in another class, but I am getting errors and don't understand why. It only seems to give me errors if I try and call the method in the new ArrayAdapter, like so....
public class ListBikeStands extends ListActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView listStands = getListView();
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
BikesStands.getStandName());
listStands.setAdapter(listAdapter);
}
The class/method it's calling is as follows...
public class BikeStands {
private static OkHttpClient client = new OkHttpClient();
private static final String key = "key";
private static final String contract = "contract";
public static String getJSON(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
return response.body().string();
}
private static String[] getStandName() {
String json = null;
try {
json = getJSON("https://api.jcdecaux.com/vls/v1/stations?contract=" + contract + "&apiKey=" + key);
} catch (IOException e) {
e.printStackTrace();
}
Gson gson = new Gson();
DBikesStation[] bikesAPI = gson.fromJson(json, DBikesStation[].class);
String[] bikeStands = new String[bikesAPI.length];
for (int i = 0; i < bikesAPI.length; ++i) {
bikeStands[i] = bikesAPI[i].getName();
}
;
return bikeStands;
}
I'm getting the following error...
java.lang.RuntimeException: Unable to start activity ComponentInfo{package......dublinbikes.ListBikeStands}: android.os.NetworkOnMainThreadException
I do have ListBikeStands as an activity in the AndroidManifest.xml.
Any help is much appreciated. Thanks.