Skip to content

Instantly share code, notes, and snippets.

@aibolik
Created June 20, 2016 09:54
Show Gist options
  • Save aibolik/5471b1f34743366c57b56551e92fb730 to your computer and use it in GitHub Desktop.
Save aibolik/5471b1f34743366c57b56551e92fb730 to your computer and use it in GitHub Desktop.
Getting list of cities. [for M-Tender project]
public void getRegionsList() {
Log.d("mtender", "ProfilePresenter > getRegionsList");
final LinkedHashMap<Integer, List<SpinnerItem>> regionsWithCities = new LinkedHashMap<>();
final List<SpinnerItem> regionsList = new ArrayList<>();
String USER_REGIONS_URL = "http://46.101.144.46/frontend/web/api/v1/region/list";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(USER_REGIONS_URL)
.addHeader("Content-Type", "application/json")
.get()
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
int statusCode = response.code();
String body = response.body().string();
Log.d("mtender", "Code > " + statusCode);
Log.d("mtender", "Body > " + body);
try {
JSONArray regions = new JSONArray(body);
for (int i = 0; i < regions.length(); i++) {
String name = regions.getJSONObject(i).getString("name");
int id = regions.getJSONObject(i).getInt("id");
regionsList.add(new SpinnerItem(id, name));
List<SpinnerItem> citiesList = new ArrayList<>();
citiesList.add(new SpinnerItem(0, "Не задано"));
JSONArray cities = regions.getJSONObject(i).getJSONArray("cities");
for(int j = 0; j < cities.length(); j++) {
citiesList.add(new SpinnerItem(
cities.getJSONObject(j).getInt("id"),
cities.getJSONObject(j).getString("name")
));
}
regionsWithCities.put(
id,
citiesList
);
}
} catch (JSONException e) {
e.printStackTrace();
}
if(isViewAttached()) {
getView().fillRegionsWithCities(regionsWithCities, regionsList);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment