Translate

Tuesday, 9 October 2012

Consuming webservice using JSONObject in android

Fetching response data  in JSONObject

Here is the simple example for consuming webservice in android Using Json object. JSON is nothing but "JAVA SCRIPT OBJECT NOTATION ". Here i simply access the service which is written in .Net which gives response in JSON format.

Here is the Response from service:

{"d":{"__type":"Customer:#WcfService1","Address":"Pune","Name":"Shailesh"}}
 
 
Android Code: 
public class AndroidJsonActivity extends Activity {
    Button send;
      URI uri;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
send=(Button) findViewById(R.id.btnSend);
       
            
  send.setOnClickListener(new OnClickListener() {
   
public void onClick(View v) {
      
try {
     
 String Address,Name;
     
 DefaultHttpClient httpClient = new DefaultHttpClient();
 uri = new URI("http://192.168.1.2:90/Service1.svc/getcustomer");
     
 HttpGet httpget = new HttpGet(uri);
 httpget.setHeader("Accept", "application/json");
 httpget.setHeader("Content-type", "application/json; charset=utf-8");

 HttpResponse response = httpClient.execute(httpget);
  HttpEntity responseEntity = response.getEntity();
               
          
 long intCount = responseEntity.getContentLength();

 char[] buffer = new char[(int)intCount];
 InputStream stream = responseEntity.getContent();
 InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
              
              
 reader.read(buffer);
 String dataresponse = new String(buffer);
                   
          
                   
 JSONObject jsonObject = new JSONObject(new String(buffer));
                
 JSONObject idObject =   jsonObject.getJSONObject("d");
                
  Name = (String) idObject.get("Name");
 Address=idObject.getString("Address");
                
           
               
 Toast.makeText(getApplicationContext(), "Name-"+Name+"\nAddress-"+Address,Toast.LENGTH_LONG).show();
     
 } catch (URISyntaxException e) {
 Log.e("log_tag", "Error URI SYNTAX EXCEPTION "+e.toString());
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (ClientProtocolException e) {
 Log.e("log_tag", "Error CLIENT PROTOCOL EXCEPTION "+e.toString());
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IOException e) {
 Log.e("log_tag", "Error in IOEXCEPTION "+e.toString());
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (JSONException e) {
 Log.e("log_tag", "Error JSON EXCEPTION "+e.toString());
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
    
          
}
});
                                         
   }
} 
Output:- 



No comments:

Post a Comment