1.導入Gson與okhttp
dependencies {
implementation "com.squareup.okhttp3:okhttp:4.3.1"
implementation "com.google.code.gson:gson:2.8.6"
}
2.程式碼
public class MainActivity extends AppCompatActivity {
private List<String> cities;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AutoCompleteTextView textView = findViewById(R.id.multiAutoCompleteTextView);
cities = new ArrayList<>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1, cities);
textView.setAdapter(arrayAdapter);
Request request = new Request.Builder()
.url("https://api.myjson.com/bins/130mpi")
.build();
new OkHttpClient().newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
String json = response.body().string();
Gson gson = new Gson();
List<CityModel> cityModel = gson.fromJson(json, new TypeToken<List<CityModel>>(){}.getType());
for (CityModel model : cityModel) {
//取得縣市
String cityName = model.getCityName();
for (AreaModel areaModel : model.getAreaList()) {
//取得區域
String areaName = areaModel.getAreaName();
//合成縣市與區域
String cityData = cityName + areaName;
cities.add(cityData);
}
}
}
});
}
}