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. }  
});  
} }



18 comments:

  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

    ReplyDelete
  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 topic.android app development training in chennai|Android Training institute in chennai with placement | Best Android Training in velachery

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete