简体   繁体   中英

Wait for HttpRequest to finish before starting a new activity

so I am trying to learn how to create basic Android applications.

I am stuck on this problem: The Home Activity has a button that once pressed does two things: 1. Call a REST-Api on my backend-server. The server returns JSON-Objects. The JSON objects are mapped to Java Objects. Finally they are added to a static list.

  1. Start a new intent that launches an Activity with a List Layout. OnCreate() the ListLayout is filled with data from the static List obtained in step 1.

The Problem is that step 2 does not work as intended because step 1 is asynchronous. So step 2 runs before step 1 finishes to fill the static list with data from the server, resulting in an empty List being displayed on the ListActivity.

How can I wait for step 1 to finish before starting the new Activity so the data is displayed correctly?

Thanks.

Use AsyncTask .

Inside the method doInBackground() put your code for performing API call. After the API call is completed, the method onPostExecute() gets called where you can put the code to go to the next activity.

Check detailed guide here: https://developer.android.com/reference/android/os/AsyncTask

Create an AsyncTask class and override their method as this example :

 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

  }

}

and to run your class

  new DownloadTask().execute(your_url); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM