user3226628
user3226628

Reputation: 119

In which fragment method we need to consume weservice of long run

In which method it will be appropriate to call the web service from an android fragment?

Upvotes: 1

Views: 237

Answers (2)

sjain
sjain

Reputation: 23344

You can call the WebService at onCreateView() method of your fragment like this -

public class MainActivity extends Fragment
{

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
  Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.mainFragment,container ,false);

    new GetWebService().execute();

    return view;
  }

  class GetWebService extends AsyncTask<String, String, String> 
  {

    @Override
    protected void onPreExecute() 
    {
       super.onPreExecute();
    }

    protected String doInBackground(String... args) 
    {

       //Call Webservice here and return the result

       return "";  
    }

    protected void onPostExecute(String result) 
    {
       //Do something with result
    }
}

Upvotes: -1

Devrath
Devrath

Reputation: 42824

Use onStart() method

  • Use an Async Task call in the onStart() mentod and run a background thread
  • In the AsyncTask use doInBackground() to run the methods that take longer time to execute
  • Update the UI thread in onPreExecute(), onPostExecute(), onProgressUpdate()

Async task Example :

public class FrgLatein extends Fragment {
    //New-Instance
    public static FrgLatein newInstance(){
        Log.d("FrgLatein", "newInstance");
        FrgLatein fragment = new FrgLatein();
        return  fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        Log.d("FrgLatein", "onCreateView");
        View view=inflater.inflate(R.layout.frg_latein, container, false);
        setHasOptionsMenu(true);


        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.d("FrgLatein", "onActivityCreated");
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onStart() {
        Log.d("FrgLatein", "onStart");
        super.onStart();
        new LongOperation().execute("");

    }

private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
             // Do the Web service long run here
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
          // Do the UI-task here
        }

        @Override
        protected void onPreExecute() {
          // Do the UI-task here
        }

        @Override
        protected void onProgressUpdate(Void... values) {
          // Do the UI-task here which has to be done during backgroung tasks are running like a downloading process
        }
    }

}

Upvotes: 2

Related Questions