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



2 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