【发布时间】:2020-11-26 23:14:37
【问题描述】:
我需要按一个按钮从大约 50 个不同的 URL 中检索一些数据。
代码一次一个地遍历它们,虽然不需要那么长时间,但大约需要 20 秒,而且我将所有这些代码都运行在一个按钮内。
我希望我可以在访问不同网站之间更新一个 TextView 或者说“正在加载第 1 页,共 50 页”然后“正在加载第 2 页,共 50 页”等。
下面的代码可以正常工作,只是按钮被卡住了一段未知的时间,我希望用户能够了解加载的进度。
btnGetData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//regionRetrieve 1 page of auction data, so we know how many future pages to retrieve. -P
String auctionURL = "https://api.hypixel.net/skyblock/auctions?page=";
String firstPage = null;
try {
firstPage = new RetrieveData().execute(auctionURL + "0").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
auctionInfo = new JSONObject(firstPage);
} catch (JSONException e) {
e.printStackTrace();
}
//endregion
//regionRetrieve the remaining pages
int totalPages = 0;
try {
totalPages = auctionInfo.getInt("totalPages");
} catch (JSONException e) {
e.printStackTrace();
}
//Place to put the rest of the pages
ArrayList<String> remainingPages = new ArrayList<>();
//Starts at 1, because we already retrieved the 0 page as the first page.
//Also, I checked, and you do need to retrieve the 52nd page if there are say, 52 pages.
for (int i = 1; i <= totalPages; ++i) {
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//ADD SOME KIND OF NOTIFICATION HERE
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
String newPage = null;
try {
newPage = new RetrieveData().execute(auctionURL + i).get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
remainingPages.add(newPage);
}
Toast.makeText(getApplicationContext(),"All data received.",Toast.LENGTH_SHORT).show();
tvLoading.setVisibility(View.GONE);
//endregion
//stuff below this point is irrelevant to the question
}
});
我尝试将上面的所有代码包装在 AsyncTask 中,并使用“onProgressUpdate”,但这不起作用。此外,我听说现在 AsyncTask 已被弃用,并且有更好的方法来做到这一点。
我也尝试过使用 Toast 消息,但它们都显示在最后,这有点违背目的。
我什至将 Toast 消息放入我调用的 AsyncTasks 中以获取数据,但这也不起作用。 (RetrieveData() 是一个 AsyncTask,它从 URLS 中读取所有信息,并将其作为字符串返回。我知道您不应该使用 get,但在这种情况下,重要的是数据以正确的顺序到达。除非,在检索到第一个,并且知道有多少页之后,我可以同时启动 50 个线程来检索数据?但是,您仍然受到 Internet 连接的限制,用户仍然坐在那里感到困惑。 )
有没有合适的方法来做到这一点?
任何帮助将不胜感激!
【问题讨论】:
标签: android download progress-bar loading