Thursday, June 28, 2012

Fetching Data from Server And Setting Custom Spinner

Create Country model with required fields and set getter and setter properties.

public class Country {
private String countryCode;
private String countryName; 
public String getCountryCode() {
      return countryCode;
public void setCountryCode(String string) {
      this.countryCode = string;
public String getCountryName() {
      return countryName;
public void setCountryName(String countryName) {
      this.countryName = countryName;

Fetching Country Details from Server

First create class that deal with webserver, do URL connection and get JSON response, then parse JSON response using JSON object and save it in arrayList  of Country class.
public class WSCountry {
     Context mContext;
      WebServiceUtil webserviceutil;
public WSCountry(Context context) {
mContext = context;
public ArrayList<Country> CountryCode() {
ArrayList<Country> arrCountries = new ArrayList<Country>();
String parsedString = "";
try {
URL url = new URL("your url");
URLConnection conn = url.openConnection();
                             HttpURLConnection httpConn = (HttpURLConnection) conn;  


                                httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect();

InputStream is = httpConn.getInputStream();
parsedString = convertinputStreamToString(is);
} catch (Exception e) { e.printStackTrace(); }
arrCountries = ParseJson(parsedString); 
return arrCountries; }
public static ArrayList<Country> ParseJson(String jsonstring) {
ArrayList<Country> arrCountries = new ArrayList<Country>();
String status;
String message = "";
                      try {
JSONObject json = new JSONObject(jsonstring); 
status = json.getString("result"); if (status.equalsIgnoreCase("success")) {
                         // [{"countryCode":"00","countryName":"World Wide"},                                               {"countryCode":"kr","countryName":"Korea, Republic of"},{"countryCode":"us","countryName":"United States"}]
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
                      JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
} catch (JSONException e) {
                               Log.e("JSON", "There was an error parsing the JSON", e); 
return arrCountries;

public static String convertinputStreamToString(InputStream ists) throws IOException {         
       if (ists != null) {
               StringBuilder sb = new StringBuilder();
               String line;
               try {
                     BufferedReader r1 = new BufferedReader(new InputStreamReader( ists, "UTF-8")); 
                     while ((line = r1.readLine()) != null) 

                } finally {
                return sb.toString();
      } else {
                return "";

Create Custom Spinner Adapter class.
private class MyAdapter implements SpinnerAdapter {  
          ArrayList<Country> data;

public MyAdapter(ArrayList<Country> data) { = data;   

public int getCount() { return data.size(); }


public Object getItem(int position) { return data.get(position); }


public long getItemId(int position) { return position; }


public int getItemViewType(int position) {

        return android.R.layout.simple_spinner_dropdown_item;

public View getView(int position, View convertView, ViewGroup parent) {  
TextView v = new TextView(getApplicationContext()); v.setTextColor(Color.BLACK); v.setText(data.get(position).getCountryName()); return v;  
public int getViewTypeCount() { return 1; }  
public boolean hasStableIds() { return false; }  
public boolean isEmpty() { return false; }  
public void registerDataSetObserver(DataSetObserver observer) {  
// TODO Auto-generated method stub  
public void unregisterDataSetObserver(DataSetObserver observer) {  
// TODO Auto-generated method stub  
public View getDropDownView(int position, View convertView, ViewGroup parent) {  
return this.getView(position, convertView, parent);  
} }

Create AsyncTask to fetch country details in background and Setting the Spinner adapter in postExecute class.

private class CountryService extends AsyncTask<Void, Void, Void> { 
protected void onPreExecute() {  
      try {
         progressDialog =, "", "Fetching       Countries", true, false);  
       } catch (Exception e) {  
protected Void doInBackground(Void... params) { 
try {  
       arrayCountries = objwscountry.CountryCode();  
} catch (Exception e) { e.printStackTrace(); }  
 return null;  
protected void onPostExecute(Void result) {  
MyAdapter adapter = new MyAdapter(arrayCountries); spinCountry.setAdapter(adapter);  
spinCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {   
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {  
       Country country = (Country) parent.getItemAtPosition(pos);  
       countryCode = country.getCountryCode();  
public void onNothingSelected(AdapterView parent) { // Do nothing. }  
} }


  1. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.Best Android Training in Velachery | android development course fees in chennai

  2. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this app development training in chennai|Android Training institute in chennai with placement | Best Android Training in velachery

  3. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune

    rpa online training

  4. This comment has been removed by the author.

  5. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.

    Data Science with Python training in chenni
    Data Science training in chennai
    Data science training in velachery
    Data science training in tambaram
    Data Science training in OMR
    Data Science training in anna nagar
    Data Science training in chennai
    Data science training in Bangalore

  6. This is a good post. This post give truly quality information. I’m definitely going to look into it. Really very useful tips are provided here. thank you so much. Keep up the good works.

    java training in tambaram | java training in velachery

    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

  7. This is beyond doubt a blog significant to follow. You’ve dig up a great deal to say about this topic, and so much awareness. I believe that you recognize how to construct people pay attention to what you have to pronounce, particularly with a concern that’s so vital. I am pleased to suggest this blog.
    python training in tambaram
    python training in annanagar
    python training in OMR
    python training in chennai

  8. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    DevOps online Training|DevOps Training in USA
    Devops Training in Chennai
    Devops Training in Bangalore

  9. This comment has been removed by the author.

  10. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    Blueprism training in annanagar

    Blueprism training in velachery

    Blueprism training in marathahalli

  11. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in chennai | best rpa training in chennai | rpa training in chennai | rpa training in bangalore
    rpa training in pune | rpa online training

  12. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    angularjs Training in bangalore

    angularjs Training in bangalore

  13. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
    java training in chennai | java training in bangalore

    java online training | java training in pune

  14. I am sure this post has helped me save many hours of browsing other related posts just to find what I was looking for. Many thanks!
    online Python certification course
    python training in OMR
    python training course in chennai

  15. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
    Best Devops Training in pune
    Devops interview questions and answers

  16. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    selenium training in chennai
    selenium training in bangalore
    selenium training in Pune
    selenium training in pune
    Selenium Online Training

  17. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.

    AWS Training in Bangalore | Amazon Web Services Training in bangalore , india

    AWS Training in pune | Amazon Web Services Training in Pune, india

    AWS Training in Chennai|Amazon Web Services Training in Chennai,India

    aws online training and certification | amazon web services online training ,india