Search code examples
javaandroidandroid-networking

Where should network related task like api calling be be placed in Activity lifecycle?


I'm creating an android app which has single activity for now. This activity calls an api to get JSON response and populate the Fragments. Once the JSON response is received I am updating the data set and notifying adapter. Currently the JSON request is called in onCreate method.

Similarly in each fragment I need to load image from network so I am wondering will it too should be put in onCreateView or someplace else?

I'm interested in knowing what is the best practice to achieve this.


Solution

  • The best practise is to use an asynchronous event when doing networking stuff, because depending on your server response time andd on your network speed, you will maybe get the response late and that block your UI and that's not good.

    I suggest you integrate AsyncTask when calling your API.

    Here is an example

    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
    
    
    @Override
    protected void onPreExecute() {
      super.onPreExecute();
    
    }
    
    @Override
    protected Boolean doInBackground(String... urls) {
    try {
    
       //here you make your api call and json parsing
    
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
    
        e.printStackTrace();
    }
    return false;
    }
    
    protected void onPostExecute(Boolean result) {
    
    }
    

    And you call your request in your onCreate like this

    JSONAsyncTask task=new JSONAsyncTask();
    task.execute();
    

    Take a look at docs for further information https://developer.android.com/reference/android/os/AsyncTask