Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragment : which life cycle method to use for web service call

I am developing an application in which several fragments are involved. In each fragment I have to call web service to fetch data.

Currently I am calling web service from onCreateView() method of Fragment. Issue i am getting that whenever web service call is in progress and if device orientation is changed then new web service call starts invoking.

I think this might be because onCreateView() method gets called on configuration change.

How can I solve this. and which Life cycle method should I use to call web service so that it will be get called only once

like image 479
silwar Avatar asked Nov 01 '22 05:11

silwar


1 Answers

I have resolved this by following workaround

  1. Create an operation identifier for each web service call method. E.g. for example "Authentication" for login call

  2. Create one object of ArrayList say currentTasks

    ArrayList<String> currentTasks = new ArrayList<String>();
    
  3. In every method where I am calling web service, check if operation identifier of corresponding method is already present in ArrayList. If not then start operation.

    String operationId = "Authentication";
    if(currentTasks.indexOf(operationId) == -1)
    {
      <do web service call operation here>
       currentTasks.add(operationId);
    }
    
  4. Method in which above operation's response is receiving, remove operation identifier from ArrayList

     if(currentTasks.indexOf("Authentication") != -1){
        currentTasks.remove("Authentication");
     }
    

This will ensure that call will not go to web method which is currently in progress.

I know this is not the best way to achieve it and this might not the best practice to follow but for now this works for me.

like image 153
silwar Avatar answered Nov 15 '22 04:11

silwar