我可以使用下面的代码使用 1 个 URL 的 downloadJSON 类下载数据没问题,但我想获取另一组数据,以便它可以与其他数据一起显示。我尝试了几种不同的方法,但都无济于事。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_json);
TextView textView = (TextView)findViewById(R.id.JSONTextView);
textView.setText("Downloading JSON!");
new downloadJSON().execute("www.exampleURL.com/data1");
//new downloadJSON().execute(url2??);
}
private class downloadJSON extends AsyncTask<String, String, String>
{
protected String doInBackground(String... args) {
String result = "";
String formattedResult = "";
try {
InputStream stream = (InputStream)new URL(args[0]).getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = "";
while (line != null) {
result += line;
line = reader.readLine();
}
JSONObject json = new JSONObject(result);
formattedResult = "Downloadable Puzzles\r\n--------------\r\n";
JSONArray puzzles = json.getJSONArray("PuzzleIndex");
for (int i = 0;i < puzzles.length(); ++i) {
formattedResult += puzzles.get(i) + "\r\n";
}
} catch (Exception e) {
e.printStackTrace();
}
return formattedResult;
}
protected void onPostExecute(String pResult) {
TextView textView = (TextView)findViewById(R.id.JSONTextView);
textView.setText(pResult);
}
}
编辑:我的问题不是下面发布的链接的副本,因为涉及 JSON 和 URL 的事实使我的问题更加重要。该链接绝不是针对我的问题的,对问题没有帮助。
最佳答案
Async 任务不会将控制返回给调用方法。它仅在后台线程上完成 doInBackground() 后在主线程中运行 onPostExecute()。
将控制权转移回调用方法的一种方法是使用接口(interface)。
public class DownloadJSON extends AsyncTask<String, String, String> {
private AsyncCallback mCallback;
public DownloadJSON(AsyncCallback callback) {
mCallback = callback;
}
protected String doInBackground(String... args) {
// process background task
}
protected void onPostExecute(String result) {
if (mCallback != null)
mCallback.onComplete(result);
}
public interface AsyncCallback {
void onComplete(String result);
}
}
然后使用启动asynctask
new DownloadJSON(new DownloadJSON.AsyncCallback() {
@Override
public void onComplete(String result) {
textView.setText(result);
}
}).execute("www.exampleURL.com/data1");
关于java - Android Studio - 在一个异步任务中从 2 个 url 下载 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117176/