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.setAllowUserInteraction(false);  


                                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);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
                     arrCountries.add(country);
}
                }
} 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) 
                                sb.append(line).append("\n");

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

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

public MyAdapter(ArrayList<Country> data) {  
this.data = data;   
}
@Override

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

@Override

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

@Override

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

@Override

public int getItemViewType(int position) {

        return android.R.layout.simple_spinner_dropdown_item;

@Override  
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;  
}  
@Override  
public int getViewTypeCount() { return 1; }  
@Override  
public boolean hasStableIds() { return false; }  
@Override  
public boolean isEmpty() { return false; }  
@Override  
public void registerDataSetObserver(DataSetObserver observer) {  
// TODO Auto-generated method stub  
}
@Override  
public void unregisterDataSetObserver(DataSetObserver observer) {  
// TODO Auto-generated method stub  
} 
@Override  
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> { 
@Override  
protected void onPreExecute() {  
      super.onPreExecute();  
      try {
         progressDialog = ProgressDialog.show(SignUpActivity.this, "", "Fetching       Countries", true, false);  
       } catch (Exception e) {  
            e.printStackTrace();  
} 
}
@Override   
protected Void doInBackground(Void... params) { 
try {  
       arrayCountries = objwscountry.CountryCode();  
} catch (Exception e) { e.printStackTrace(); }  
 return null;  
}
@Override  
protected void onPostExecute(Void result) {  
super.onPostExecute(result);
progressDialog.dismiss();
 
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. }  
});  
} }



20 comments:

  1. 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

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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

    ReplyDelete
  5. 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

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. 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

    ReplyDelete
  8. 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

    ReplyDelete
  9. 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

    ReplyDelete
  10. 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.. 

    Data Science Training in Chennai | Data Science training in anna nagar
    Data Science training in chennai | Data science training in Bangalore
    Data Science training in marathahalli | Data Science training in btm

    ReplyDelete
  11. 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

    ReplyDelete
  12. 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


    https://simplyaspnet.blogspot.com/2013/08/how-to-save-images-in-database-and.html

    ReplyDelete
  13. Useful information.I am actual blessed to read this article.thanks for giving us this advantageous information.I acknowledge this post.and I would like bookmark this post.Thanks
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete
  14. Does your blog have a contact page? I’m having problems locating it but, I’d like to shoot you an email. I’ve got some recommendations for your blog you might be interested in hearing..thaks for the updation.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  15. ACHESTAH CASINO & SPORTSBOOK - HUBB
    ACHESTAH CASINO & SPORTSBOOK. 887 W BANK BANK BLVD, BLVD, MI 4218. Get Directions. Book Now - http://www.yelp.com/casino › deals/book-and-info/ACHESTAH-ASINO › deals › book-and-info › ACHESTAH-ASINO › 전라북도 출장안마 deals › book-and-info › ACHESTAH-ASINO Sep 24, 2017 — Sep 24, 2017 Book 부천 출장안마 Now. The closest stations are at: Harrah's 평택 출장안마 Cherokee Casino & Racetrack, 34, Lakewood Road, North Carolina. 동두천 출장마사지 Book Now - https://www.yelp.com/  Rating: 3.8 1,021 reviews 고양 출장샵 Price range: $$

    ReplyDelete