嘗試使用來自同一類的其他URL時出現問題。我將訪問類似於以下許多次的網頁。如何在Java/Android中的AsyncTask中訪問不同的URL
我查了很多不同的Q/A和教程,似乎無法找到如何傳遞一個URL作爲參數,所以它在doInBackground方法中使用。我調用execute方法,例如:
new RetrieveFeedTask().execute();
private class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
}
protected String doInBackground(Void... urls) {
try {
URL url = new URL(API_URL_COMPETITIONS); // this is url http://api.football-data.org/v1/competitions
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReadelConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
//entire JSON page is saved in response
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
Log.i("INFO", response);
try {
JSONArray comps = new JSONArray(response);
JSONObject second = comps.getJSONObject(1); //this is array element PremierLeague2016/2017
compArray.add("Competition");
compArray.add(second.getString("caption"));
//i then set this to an ArrayAdapter and show the results in a Spinner. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
competition.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
感謝任何幫助!
我很困惑問題是什麼。你需要替換'API_URL_COMPETITIONS'並使用你想要的任何URL –
是的,但是我只需要這個URL用於一個Spinner,然後另一個Spinner用不同的URL,等等。所以我需要創建這個類的實例,但每次都有不同的URL,如果可能的話,但不知道我該怎麼做。 – Lewisfitz07
再次感謝您使用Volley庫和'JsonObjectRequest'或'JsonArrayRequest' –