Pages

Saturday 27 August 2011

How to parse a string from server side or by specific url in android

This giving example will help to parse a string from server side or by specific url.
Code is given as below:


import android.app.Activity;
import android.os.Bundle;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class httpparsing extends Activity {
    //http://maps.google.com/maps/geo?q=chandigarh&output=csv
    //    http://feeds.feedburner.com/AndroidCoding
 final String httpPath = "http://maps.google.com/maps/geo?q=chandigarh&output=csv";
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       TextView text = (TextView)findViewById(R.id.text);
      
       HttpClient httpclient = new DefaultHttpClient();
       HttpGet httpget = new HttpGet(httpPath);
       try {

   HttpEntity httpEntity = httpclient.execute(httpget).getEntity();
   
   if (httpEntity != null){
    InputStream inputStream = httpEntity.getContent();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
      
    String line = null;
       String ss = null;
    while ((line = bufferedReader.readLine()) != null) {
     stringBuilder.append(line + "\n");
     ss=line;
    
    }
   
   
    StringTokenizer st = new StringTokenizer (ss,",");
    while(st.hasMoreTokens()){
        Log.d("cccccccccccccc","ccccccccccccccccc"+st.nextToken());
    }

//    for(int i=0;i<ss.length();i++){
//         Log.d("cccccccccccccc","ccccccccccccccccc"+ss.indexOf(i));
//    }
   
   
    inputStream.close();
      
  
   
    text.setText(stringBuilder.toString());
   }
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(httpparsing.this, e.toString(), Toast.LENGTH_LONG).show();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(httpparsing.this, e.toString(), Toast.LENGTH_LONG).show();
  }
   }
}

Hope this blog helpful for you.

By : Parmil.S&Vkhooda

No comments:

Post a Comment