![](/img/trans.png)
[英]Wait for rotation animation to finish in android before opening new activity?
[英]Wait for HttpRequest to finish before starting a new activity
所以我想學習如何創建基本的Android應用程序。
我堅持這個問題:Home Activity有一個按鈕,按下后會做兩件事:1。在我的后端服務器上調用REST-Api。 服務器返回JSON-Objects。 JSON對象映射到Java對象。 最后,它們被添加到靜態列表中。
問題是步驟2不能按預期工作,因為步驟1是異步的。 因此,步驟2在步驟1完成之前運行,以使用來自服務器的數據填充靜態列表,從而導致ListActivity上顯示空List。
如何在開始新活動之前等待步驟1完成,以便正確顯示數據?
謝謝。
使用AsyncTask
。
在方法內部, doInBackground()
將您的代碼用於執行API調用。 API調用完成后,調用onPostExecute()
方法,您可以將代碼放到下一個活動中。
請查看詳細指南: https : //developer.android.com/reference/android/os/AsyncTask
創建一個AsyncTask類並覆蓋它們的方法,如下例所示:
public class DownloadTask extends AsyncTask<String,String,String>{
@Override
public void onPreExecute()
super.onPreExecute();
{
/// initialize loading animation if you want
}
@Override
public String doInbackGround(String... params)
{
///call your rest request
return resulofyourrequest;
}
@Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
// stop loading animation if you already started one in onPreExecute
///do the stuff you need after you get the result and start your activity here
}
}
並運行你的課程
new DownloadTask().execute(your_url);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.