tacos_tacos_tacos
tacos_tacos_tacos

Reputation: 10585

Populate Spinner with async call to Web Service only when clicked

I have a few spinners in my Android Activity class that need to be populated with data from a web service. I have already set up methods that invoke the web service call. Once the web service returns data and it is parsed, I populate the respective data into an ArrayList member of my class. The problem is that I do not know how to invoke these calls only upon a user selecting a particular spinner. For instance, I use the following code to bind countrySpinner:

    countrySpinner = (Spinner) findViewById(R.id.spinner_country);

    List<String> list= new ArrayList<String>();

    list.add("All"); // <-- initial/default content

    countryAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
    countryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    countrySpinner.setAdapter(countryAdapter);

The default value is "All" which is fine because that is the default behavior of the web service. However, I want to invoke the method callSpinnerWS() when a user touches the spinner, then populate its data again by modifying the member countryAdapter to have a list more to my liking by countryAdapter.clear() and then iterating over a different arraylist to add items.

Where do I put the call to the web service? What is the appropriate binding event for accomplishing this?

Upvotes: 0

Views: 1767

Answers (1)

marcinj
marcinj

Reputation: 50016

I suggest using AsyncTask, you put webservice code inside doInBackground, it should return reference to collection of list elements, it will be returned to onPostExecute which will clear and repopulate adapters collection. Actually using worker thread is a mandatory to avoid ANR (android not responding) exception. In onPreExecute() you can show progress dialog, and close it in onPostExecute.

Calling AsyncTask execute should be placed in the spinner click listener. You can initialize instance of your AsyncTask with reference to given spinner, or with reference of its adapter.

Upvotes: 1

Related Questions