gpt4 book ai didi

java - 如何在Java/Android中访问AsyncTask中的不同URL

转载 作者:行者123 更新时间:2023-12-01 09:39:13 24 4
gpt4 key购买 nike

尝试使用同一类中的不同 URL 时遇到问题。我会多次访问类似下面的网页。

我查找了许多不同的 Q/As 和教程,但似乎找不到如何将 URL 作为参数传递,因此在 doInBackground 方法中使用它。我这样调用执行方法:

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();
}
}
}

感谢任何帮助!

最佳答案

can't seem find how to pass a URL as a parameter so it is used in the doInBackground method

AsyncTask 类是 AsyncTask<Params, Progress, Result> 。你想要一个String参数,不是 Void范围。

private class RetrieveFeedTask extends AsyncTask<String, Void, String> 

然后你可以使用protected String doInBackground(String... urls) (因为无效网址没有意义)

并更新您的通话

String url1 = "http://...";
String url2 = "http://...";
new RetrieveFeedTask().execute(url1, url2);

在 doInBackground 中

for (String url : urls) {
try {
URL url = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

或者,忘记循环...您可以简单地访问 urls[0]例如,要获取第一个 String 值,只需小心 IndexOutOfBoundsException

关于java - 如何在Java/Android中访问AsyncTask中的不同URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38593648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com