Thursday, 7 July 2011

How to parse any string from http or server side in android.

This example will parse any numeric string that is given from server side or by specific url.It make as simple as i can make.
Code is using as:


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 code useful for you.

No comments:

Post a Comment