Рекомендуется использовать веб-фреймворк, такой как OkHttp, но если вы настаиваете на использовании AsyncTask + HttpURLConnection здесь, вот фрагмент кода:
TextView textViewGMT;
TextView textViewCET;
TextView textViewCN;
TextView textViewKR;
TextView textViewIST;
String[] cities = {"London","Paris","Beijing","Seoul","Delhi"};
List<GetTime> tasks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewGMT = findViewById(R.id.textViewGMT);
textViewCET = findViewById(R.id.textViewCET);
textViewCN = findViewById(R.id.textViewCN);
textViewKR = findViewById(R.id.textViewKR);
textViewIST = findViewById(R.id.textViewIST);
tasks = new ArrayList<>(cities.length);
String cityURL;
for ( int i=0; i<cities.length; i++) {
cityURL = "https://www.amdoren.com/api/timezone.php?"+cities[i];
GetTime readerTask = new GetTime();
readerTask.execute(cityURL, positionToTextView(i), positionToCountry(i));
}
}
private String positionToCountry(int i) {
switch(i){
case 0: return "London ";
case 1: return "France ";
case 2: return "China ";
case 3: return "Korea";
case 4: return "India";
}
return null;
}
private TextView positionToTextView(int index) {
switch(index){
case 0: return textViewGMT;
case 1: return textViewCET;
case 2: return textViewCN;
case 3: return textViewKR;
case 4: return textViewIST;
}
return null;
}
@Override
protected void onStop(){
super.onStop();
Log.i("In onsStop()", "Executing finish()");
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
for (GetTime getTime: tasks) {
getTime.cancel(false);
}
}
public static class GetTime extends AsyncTask<Object, Void, String> {
private String countryPrefix;
private TextView textView;
@Override
protected String doInBackground(Object... objects) {
String urlStr = (String) objects[0];
textView = (TextView) objects[1];
countryPrefix = (String) objects[2];
HttpURLConnection urlConnection;
URL url;
String result = "";
try {
url = new URL(urlStr);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while ( data != -1 ) {
char current = (char) data;
result += current;
data = reader.read();
}
return ( result );
} catch (MalformedURLException e) {
e.printStackTrace();
return ( "***Failed in AsyncTask MalforemedURL***");
} catch (IOException e) {
e.printStackTrace();
return ( "***Failed in AsyncTask IOException***");
}
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i("WEBSITE CONTENT: ", result);
List<String> arrayList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(result);
System.out.println("Before String");
System.out.println("After String");
String main = jsonObject.getString("time");
arrayList.add("Date: " );
String[] arrOfStr = main.split(" ");
arrayList.add(arrOfStr[0]);
arrayList.add(" ");
arrayList.add("Time:");
arrayList.add(arrOfStr[1]);
String desc = jsonObject.getString("timezone");
Log.i("***main: ", main);
Log.i("***description: ", desc);
arrayList.add(" " );
arrayList.add(desc);
arrayList.add("\n");
String textOut = "";
for ( String each: arrayList ){
System.out.println(each);
textOut = textOut + each + "\n";
}
if (textView != null) textView.setText(countryPrefix + textOut);
System.out.println("TEXTOUT" + textOut);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Используйте OkHttp для упрощения сетевых запросов:
TextView textViewGMT;
TextView textViewCET;
TextView textViewCN;
TextView textViewKR;
TextView textViewIST;
String[] cities = {"London","Paris","Beijing","Seoul","Delhi"};
List<Call> calls;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewGMT = findViewById(R.id.textViewGMT);
textViewCET = findViewById(R.id.textViewCET);
textViewCN = findViewById(R.id.textViewCN);
textViewKR = findViewById(R.id.textViewKR);
textViewIST = findViewById(R.id.textViewIST);
OkHttpClient client = new OkHttpClient();
String cityURL;
calls = new ArrayList<>(cities.length);
for ( int i=0; i<cities.length; i++) {
cityURL = "https://www.amdoren.com/api/timezone.php?"+cities[i];
Request request = new Request.Builder()
.url(cityURL)
.build();
Call call = client.newCall(request);
final TextView textView = positionToTextView(i);
final String countryPrefix = positionToCountry(i);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!call.isCanceled()) {
if (textView != null)
textView.setText(countryPrefix + bodyToTextOut(response.body().toString()));
}
}
});
calls.add(call);
}
}
private String positionToCountry(int i) {
switch(i){
case 0: return "London ";
case 1: return "France ";
case 2: return "China ";
case 3: return "Korea";
case 4: return "India";
}
return null;
}
private TextView positionToTextView(int index) {
switch(index){
case 0: return textViewGMT;
case 1: return textViewCET;
case 2: return textViewCN;
case 3: return textViewKR;
case 4: return textViewIST;
}
return null;
}
private String bodyToTextOut(String body) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(body);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonObject == null) return "";
StringBuilder textOutSb = new StringBuilder();
System.out.println("Before String");
System.out.println("After String");
String main = jsonObject.optString("time");
textOutSb.append("Date: \n");
String[] arrOfStr = main.split(" ");
textOutSb.append(arrOfStr[0]) .append('\n')
.append(" \n")
.append("Time:\n")
.append(arrOfStr[1]).append('\n');
String desc = jsonObject.optString("timezone");
Log.i("***main: ", main);
Log.i("***description: ", desc);
textOutSb.append(" \n")
.append(desc)
.append("\n\n");
System.out.println("TEXTOUT" + textOutSb.toString());
return textOutSb.toString();
}
@Override
protected void onDestroy() {
super.onDestroy();
for (Call call: calls) {
call.cancel();
}
}
Не забудьте добавить зависимость от ohttp в build.grade:
implementation 'com.squareup.okhttp3:okhttp:3.12.0'