Pages

Wednesday, 23 May 2012

Sample Sax Handler

public class CarDetailsHandler extends DefaultHandler {

private Company company = null;
private Category category = null;
private Model model = null;
private ModelInfo modelInfo = null;
private EngineInfo engineInfo = null;
private BreakInfo breakInfo = null;
private StringBuffer buffer = null;
private List<Model> models = null;
private List<Category> categories = null;
private StandardFeatures standardFeatures;
private static CarDetailsHandler carDetailsHandler = null;

private CarDetailsHandler() {

}

public static CarDetailsHandler getInstance() {
if (carDetailsHandler == null) {
carDetailsHandler = new CarDetailsHandler();
}

return carDetailsHandler;
}

public Company getDetails() {

return company;
}

@Override
public void startDocument() throws SAXException {
company = new Company();
categories = new ArrayList<Category>();
}

@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
buffer = new StringBuffer();
System.out.println("now it's in start menthd");
if (localName.equalsIgnoreCase("category")) {
category = new Category();
models = new ArrayList<Model>();

} else if (localName.equalsIgnoreCase("model")) {
model = new Model();

} else if (localName.equalsIgnoreCase("info")) {
modelInfo = new ModelInfo();

} else if (localName.equalsIgnoreCase("engine")) {
engineInfo = new EngineInfo();

} else if (localName.equalsIgnoreCase("break")) {
breakInfo = new BreakInfo();

} else if (localName.equalsIgnoreCase("standardfeatures")) {
 standardFeatures = new StandardFeatures();

}

// Get the number of attribute
int length = attributes.getLength();

// Process each attribute
for (int i = 0; i < length; i++) {
// Get names and values for each attribute
String name = attributes.getQName(i);
String value = attributes.getValue(i);

if (localName.equalsIgnoreCase("company")
&& name.equalsIgnoreCase("name")) {
company.setName(value);

} else if (localName.equalsIgnoreCase("category")
&& name.equalsIgnoreCase("name")) {
category.setName(value);

} else if (localName.equalsIgnoreCase("model")
&& name.equalsIgnoreCase("name")) {
model.setName(value);

} else if (localName.equalsIgnoreCase("engine")) {
if (name.equalsIgnoreCase("type")) {
engineInfo.setEngineType(value);

} else if (name.equalsIgnoreCase("cc")) {
engineInfo.setEngineCC(value);

} else if (name.equalsIgnoreCase("fuelefficiency")) {
engineInfo.setFuelEfficiency(value);

}
} else if (localName.equalsIgnoreCase("break")) {
if (name.equalsIgnoreCase("front")) {
breakInfo.setFront(value);

} else if (name.equalsIgnoreCase("rear")) {
breakInfo.setRear(value);

}
}

}
}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {

if (buffer != null) {
buffer.append(ch, start, length);

}
}

@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("company")) {
company.setCategories(categories);
} else if (localName.equalsIgnoreCase("category")) {
category.setModels(models);
models = null;
categories.add(category);
category = null;

} else if (localName.equalsIgnoreCase("model")) {
System.out.println("model going to end");
models.add(model);
model = null;

} else if (localName.equalsIgnoreCase("description")) {
category.setDescription(buffer.toString());
} else if (localName.equalsIgnoreCase("image")) {
model.setImage(buffer.toString());

} else if (localName.equalsIgnoreCase("price")) {
model.setPrice(buffer.toString());

} else if (localName.equalsIgnoreCase("info")) {
model.setModelInfo(modelInfo);
modelInfo = null;

} else if (localName.equalsIgnoreCase("engine")) {
modelInfo.setEngineInfo(engineInfo);
engineInfo = null;

} else if (localName.equalsIgnoreCase("transmission")) {
modelInfo.setTransmission(buffer.toString());

} else if (localName.equalsIgnoreCase("steering")) {
modelInfo.setSteering(buffer.toString());

} else if (localName.equalsIgnoreCase("doors")) {
modelInfo.setDoors(buffer.toString());

} else if (localName.equalsIgnoreCase("break")) {
modelInfo.setBreakesInfo(breakInfo);

} else if (localName.equalsIgnoreCase("highlights")) {
model.setHighlights(buffer.toString());
} else if (localName.equalsIgnoreCase("standardfeatures")) {
model.setStandardFeatures(standardFeatures);
standardFeatures = null;


} else if (localName.equalsIgnoreCase("exterior")) {
standardFeatures.setExterior(buffer.toString());
} else if (localName.equalsIgnoreCase("interior")) {
standardFeatures.setInterior(buffer.toString());
} else if (localName.equalsIgnoreCase("comfort")) {
standardFeatures.setComfort(buffer.toString());
} else if (localName.equalsIgnoreCase("safety")) {
standardFeatures.setSafety(buffer.toString());
}

}
}

Intializing Sax parser

sax parsing initialization
// create the factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
SAXParser parser = factory.newSAXParser();
// create the reader (scanner)(
XMLReader xmlreader = parser.getXMLReader);
// instantiate our handler
CarDetailsHandler handler = CarDetailsHandler.getInstance();
// assign our handler
xmlreader.setContentHandler(handler);
// get our data through the url class

 InputSource is = new InputSource(url);
// perform the synchronous parse
xmlreader.parse(is);

consuming the restful webservice result as json object


package com.ravinder;

import java.io.IOException;
import java.util.Scanner;

import org.apache.http.HttpResponse;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class CallingRestActivity extends Activity {
private ListView listView = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listView1);
new CallServiceTask().execute();
        }

class CallServiceTask extends AsyncTask<Void, Void, HttpResponse> {

@Override
protected HttpResponse doInBackground(Void... params) {
String url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=India%20Prime%20Minester";
//String url="http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=hyderabad%20population";
HttpGet get = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
try {
response = client.execute(get);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return response;
}

@Override
protected void onPostExecute(HttpResponse result) {
super.onPostExecute(result);
Scanner sc = null;
try {
sc = new Scanner(result.getEntity().getContent(), "UTF-8");
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

StringBuffer buffer = new StringBuffer();
while (sc.hasNext()) {
buffer.append(sc.next());
}
System.out.println("final output:" + buffer);

try {
// creating json object with string
JSONObject jsonObject = new JSONObject(buffer.toString());
// /getting the json object of responseData
JSONObject json = (JSONObject) jsonObject.get("responseData");
System.out.println("json is:" + json);
// getting the Json arrays where key is results
JSONArray array = json.getJSONArray("results");
System.out.println("arrray size is:" + array.length());
String[] results = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
results[i] = object.getString("content");
}
listView.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,results));  

} catch (JSONException e1) {
e1.printStackTrace();
}
}

}
}