Q:

Starting a background service for only once and stop once the task is completed

I am using a auto-complete text view in my activity and i wrote a service to get data from server in the same activity after completing service i have enabled that auto-complete text view because when user start typing in that text view the data i got from server start gets filtering, every thing up to here is working fine but every time i came to same activity my service start executing i just want that my service get call for only once and also the user can search from auto complete text view once my data come from server.
MyActivity Code
@Override
 protected void onStart() {

    if(CarproApp.getInstance().namesList != null) {
    //enable textfield if you have already fetched the data from server :)
        debitornameET.setEnabled(true);
    }else{
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MyService.MY_ACTION);
        registerReceiver(myReceiver, intentFilter);
        //Start our own service

    }

    Intent intent = new Intent(CustomerAccountActivity.this,
            MyService.class);
    //intent.putExtra("INIT_DATA", "Data passed from Activity to Service in startService");
    startService(intent);
    super.onStart();
}

@Override
protected void onStop() {
    unregisterReceiver(myReceiver);
    super.onStop();
}

private class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        namelist = arg1.getStringArrayListExtra("listnames");
        System.out.println("PRINTING" + namelist);
        debitornameET.setEnabled(true);
        Toast.makeText(getApplicationContext(), "BackGround Task   Completed", Toast.LENGTH_SHORT).show();
        CarproApp.getInstance().namesList = namelist;

    }

   debitornameET.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            runOnUiThread(new Runnable() {
                public void run() {

                    //  MyWebRequestService.listVal; 
                    debitorcodeET.setText("");
                    debitorCode = "";
                    Collections.sort(namelist);//here i am getting null when i came back to same activity
                    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line,namelist);
                    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    debitornameET.setThreshold(1);
                    debitornameET.setAdapter(dataAdapter);

                }
            });
        }

Service.Class
 public class MyService extends Service {

    final public static String MY_ACTION = "MY_ACTION";
    //String initData;
    private SendHttpRequest reqService;
    public static ArrayList<String> servicelist;  

    @Override
    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        servicelist = new ArrayList<String>();
    //  initData = intent.getStringExtra("INIT_DATA");

        new AsynchCall().execute();

        return super.onStartCommand(intent, flags, startId);
    }

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

        @Override
        protected String doInBackground(String... params) {
            String qryService = "SELECT DEBITOR_NAME FROM DEBITORS ";
            reqService = new SendHttpRequest(qryService);
            try {
                reqService.ExecuteQuery();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {

                e.printStackTrace();
            }

            for(int i=0;i<reqService.getRowCount();i++)
            {
                servicelist.add(reqService.getRow(i)[1]);
                System.out.println("TEXTVIEWDATAAAAAAAAa" + reqService.getRow(i)[1]);
            }
            Intent intent = new Intent();
            intent.setAction(MY_ACTION);
            intent.putStringArrayListExtra("listnames", servicelist);
            sendBroadcast(intent);
            return null;
        }

    }
}

** CarproApp Class**
        public class CarproApp extends Application {

        private static CarproApp sInstance;
        public ArrayList<String> namesList;

        public static CarproApp getInstance() {
            return sInstance;
        }

        public void onCreate() {
            super.onCreate();
            sInstance = this;

        }

    }

Because the data coming from server is so large i don't want it to store in local database. My code is working but every time i came to activity the service call gets executed which i don't want. Please guide me 

A:

Make use of Application class :) Application class gets executed once for the entire life cycle of your app :) That means onCreate of Application class gets called when you launch app and onDestroy gets called when you kill the app :)
So Application class is persistant for the entire life cycle of your app :) I believe thats what you need :)
Call your service in OnCreate() of your application class :) Once you get the data save it in a property of Application class :) So whenever you come back to the Activity read the data from the property of Application class :)
Here is what you can do :)
public class yourApplicationName extends Application{ 
     private static yourApplicationName sInstance;
     public ArrayList<String> namesList;

     public static yourApplicationName getInstance() {
        return sInstance;
    }

    public void onCreate() {
        super.onCreate();
        sInstance = this;
    }
}

In order to make use of this application class as your application class you will have to specify it in AndroidManifest.xml :)
<application
    android:name=".yourApplicationName"

and in your,
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
    namelist = arg1.getStringArrayListExtra("listnames");
    System.out.println("PRINTING" + namelist);
    debitornameET.setEnabled(true);
    Toast.makeText(getApplicationContext(), "BackGround Task         Completed", Toast.LENGTH_SHORT).show();
    yourApplicationName.getInstance().namesList = nameList;
}

debitornameET.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        runOnUiThread(new Runnable() {
            public void run() {

                //  MyWebRequestService.listVal; 
                debitorcodeET.setText("");
                debitorCode = "";
                Collections.sort(CarproApp.getInstance().namesList);//here i am getting null when i came back to same activity, abhi nai aayega error :P
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line,CarproApp.getInstance().namesList);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                debitornameET.setThreshold(1);
                debitornameET.setAdapter(dataAdapter);

            }
        });
    }

To enable your textfield when you comeback to the MainActivity :) just check if Application instance property is empty or not :)
  @Override
  protected void onStart() {
       if(yourApplicationName.getInstance().namesList != null) {
            //enable textfield if you have already fetched the data from server :)
            debitornameET.setEnabled(true);
       }
       else{
            myReceiver = new MyReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(MyService.MY_ACTION);
            registerReceiver(myReceiver, intentFilter);

            //you dont have to call service very time buddy :D call only once enough :)
            Intent intent = new Intent(CustomerAccountActivity.this,
        MyService.class);
            //intent.putExtra("INIT_DATA", "Data passed from Activity to Service in startService");
            startService(intent);
       }
  }

Hope I was of little help there :) Happy coding buddy :)

