sax parsing through url in android - android

I am trying to parse a URL in Android but it gives a null value except category. Can you help me fix it?
//my main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
//sitelist.java
package com.androidpeople.xml.parsing;
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList {
/** Variables */
private ArrayList<String> Product = new ArrayList<String>();
private ArrayList<String> Products = new ArrayList<String>();
private ArrayList<String> PriceSet = new ArrayList<String>();
private ArrayList<String> categoryId = new ArrayList<String>();
private ArrayList<String> id= new ArrayList<String>();
private ArrayList<String> title = new ArrayList<String>();
private ArrayList<String> description = new ArrayList<String>();
private ArrayList<String> manufacturer = new ArrayList<String>();
private ArrayList<String> url = new ArrayList<String>();
private ArrayList<String> Image = new ArrayList<String>();
private ArrayList<String> relevancy = new ArrayList<String>();
private ArrayList<String> minPrice = new ArrayList<String>();
private ArrayList<String> maxPrice = new ArrayList<String>();
private ArrayList<String> stores = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getProduct() {
return this.Product;
}
public void setProduct(String Product) {
this.Product.add(Product);
}
public ArrayList<String> getProducts() {
return this.Products;
}
public void setProducts(String Products) {
this.Products.add(Products);
}
public ArrayList<String> getPriceSet() {
return PriceSet;
}
public void setPriceSet(String PriceSet) {
this.PriceSet.add(PriceSet);
}
public void setcategoryId(String categoryId) {
this.categoryId.add(categoryId);
}
public ArrayList<String> getcategoryId() {
return categoryId;
}
public ArrayList<String> getid() {
return id;
}
public void setid(String id) {
this.id.add(id);
}
public ArrayList<String> gettitle() {
return title;
}
public void settitle(String title) {
this.title.add(title);
}
public ArrayList<String> getdescription() {
return description;
}
public void setdescription(String description) {
this.description.add(description);
}
public ArrayList<String> getmanufacturer() {
return manufacturer;
}
public void setmanufacturer(String manufacturer) {
this.manufacturer.add(manufacturer);
}
public ArrayList<String> geturl() {
return url;
}
public void seturl(String url) {
this.url.add(url);
}
public ArrayList<String> getImage() {
return Image;
}
public void setImage(String Image) {
this.Image.add(Image);
}
public ArrayList<String> getrelevancy() {
return relevancy;
}
public void setrelevancy(String relevancy) {
this.relevancy.add(relevancy);
}
public ArrayList<String> getminPrice() {
return minPrice;
}
public void setminPrice(String minPrice) {
this.minPrice.add(minPrice);
}
public ArrayList<String> getmaxPrice() {
return maxPrice;
}
public void setmaxPrice(String maxPrice) {
this.maxPrice.add(maxPrice);
}
public ArrayList<String> getstores() {
return stores;
}
public void setstores(String stores) {
this.stores.add(stores);
}
public void setWebsite(String currentValue) {
// TODO Auto-generated method stub
}
}
//myxmlhandler.java
package com.androidpeople.xml.parsing;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("ProductResponse"))
{
//** Start *//*
sitesList = new SitesList();
} else if (localName.equals("Products")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("Products");
System.out.println("Data"+attr);
sitesList.setProducts(attr);
}
else if (localName.equals("PriceSet")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("PriceSet");
System.out.println("Data"+attr);
sitesList.setPriceSet(attr);
}
else if (localName.equals("Product")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("categoryId");
System.out.println("Data"+attr);
sitesList.setcategoryId(attr);
/** Get attribute value */
String attr1 = attributes.getValue("id");
System.out.println("Data"+attr);
sitesList.setid(attr);
}else if (localName.equals("title")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("title");
System.out.println("Data"+attr);
sitesList.settitle(attr);
}else if (localName.equals("description")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("description");
System.out.println("Data"+attr);
sitesList.setdescription(attr);
}else if (localName.equals("manufacturer")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("manufacturer");
System.out.println("Data"+attr);
sitesList.setmanufacturer(attr);
}else if (localName.equals("url")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("url");
System.out.println("Data"+attr);
sitesList.seturl(attr);
}else if (localName.equals("Image")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("Image");
System.out.println("Data"+attr);
sitesList.setImage(attr);
}else if (localName.equals("relevancy")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("relevancy");
System.out.println("Data"+attr);
sitesList.setrelevancy(attr);
}else if (localName.equals("minPrice")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("minPrice");
System.out.println("Data"+attr);
sitesList.setminPrice(attr);
}else if (localName.equals("maxPrice")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("maxPrice");
System.out.println("Data"+attr);
sitesList.setmaxPrice(attr);
}else if (localName.equals("stores")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("stores");
System.out.println("Data"+attr);
sitesList.setstores(attr);
}
}
/** Called when tag closing ( ex:- <name>AndroidPeople</name>
* -- </name> )*/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("title"))
sitesList.settitle(currentValue);
else if (localName.equalsIgnoreCase("description"))
sitesList.setdescription(currentValue);
}
/** Called to get tag characters ( ex:- <name>AndroidPeople</name>
* -- to get AndroidPeople Character ) */
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
//myparsingexample.java
package com.androidpeople.xml.parsing;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView Product[];
TextView categoryId[];
TextView id[];
TextView title[];
TextView description[];
TextView manufacturer[];
TextView url[];
TextView Image[];
TextView relevancy[];
TextView minPrice[];
TextView maxPrice[];
TextView stores[];
TextView Products[];
TextView PriceSet[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://catalog.bizrate.com/services/catalog/v1/us/product?publisherId=50085&placementId=1&categoryId=1&keyword=ipod&productId=&productIdType=SZPID&merchantId=&minPrice=&maxPrice=&start=0&results=10&startOffers=0&resultsOffers=0&sort=relevancy_desc&brandId=&attFilter=&showAttributes=&showProductAttributes=&zipCode=&offersOnly=&biddedOnly=&minRelevancyScore=100&apiKey=58f536aa2fab110bbe0da501150bac1e");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
Product = new TextView[sitesList.getProduct().size()];
categoryId = new TextView[sitesList.getcategoryId().size()];
Products = new TextView[sitesList.getProducts().size()];
PriceSet = new TextView[sitesList.getPriceSet().size()];
id = new TextView[sitesList.getid().size()];
title = new TextView[sitesList.gettitle().size()];
manufacturer = new TextView[sitesList.getmanufacturer().size()];
description = new TextView[sitesList.getdescription().size()];
Image = new TextView[sitesList.getImage().size()];
relevancy = new TextView[sitesList.getrelevancy().size()];
minPrice = new TextView[sitesList.getminPrice().size()];
maxPrice = new TextView[sitesList.getmaxPrice().size()];
stores = new TextView[sitesList.getstores().size()];
url = new TextView[sitesList.geturl().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getProduct().size(); i++) {
Product[i] = new TextView(this);
Product[i].setText("Products = "+sitesList.getProducts().get(i));
Products[i] = new TextView(this);
Products[i].setText("Products = "+sitesList.getProducts().get(i));
PriceSet[i] = new TextView(this);
PriceSet[i].setText("PriceSet = "+sitesList.getPriceSet().get(i));
categoryId[i] = new TextView(this);
categoryId[i].setText("categoryId = "+sitesList.getcategoryId().get(i));
id[i] = new TextView(this);
id[i].setText(" id = "+sitesList.getid().get(i));
title[i] = new TextView(this);
title[i].setText("title = "+sitesList.gettitle().get(i));
description[i] = new TextView(this);
description[i].setText("description = "+sitesList.getdescription().get(i));
manufacturer[i] = new TextView(this);
manufacturer[i].setText(" manufacturer = "+sitesList.getmanufacturer().get(i));
url[i] = new TextView(this);
url[i].setText("url = "+sitesList.geturl().get(i));
Image[i] = new TextView(this);
Image[i].setText("Image = "+sitesList.getImage().get(i));
relevancy[i] = new TextView(this);
relevancy[i].setText(" relevancy = "+sitesList.getrelevancy().get(i));
minPrice[i] = new TextView(this);
minPrice[i].setText("minPrice = "+sitesList.getminPrice().get(i));
maxPrice[i] = new TextView(this);
maxPrice[i].setText("maxPrice = "+sitesList.getmaxPrice().get(i));
stores[i] = new TextView(this);
stores[i].setText(" id = "+sitesList.getstores().get(i));
layout.addView(Product[i]);
layout.addView(categoryId[i]);
layout.addView(id[i]);
layout.addView(title[i]);
layout.addView(description[i]);
layout.addView(manufacturer[i]);
layout.addView(url[i]);
layout.addView(Image[i]);
layout.addView(relevancy[i]);
layout.addView(minPrice[i]);
layout.addView(maxPrice[i]);
layout.addView(stores[i]);
layout.addView(description[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}
The value is not coming in ddms also?

check this answer out: Parsing XML
Its a very nice post, explains XML parsing with two approaches, in detail.

Related

Oxford Dictionary Api Search Word Through EditText

MainActivivity.java
package com.example.anubhav.notesapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity2 extends AppCompatActivity {
String url;
EditText et;
TextView t1;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
et = (EditText)findViewById(R.id.editText2);
t1 = (TextView)findViewById(R.id.textView3);
btn = (Button)findViewById(R.id.button);
url = dictionaryEntries();
}
public void requestApiButtonClick(View v)
{
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this,t1);
myDictionaryRequest.execute(url);
}
private String dictionaryEntries() {
final String language = "en";
final String word = et.getText().toString();
final String word_id = word.toLowerCase();
return "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id;
}
}
DictionaryRequest.java
public class MyDictionaryRequest extends AsyncTask<String,Integer,String> {
final String app_id = "your_apiId";
final String app_key = "Your api_key";
String myurl;
TextView t1;
Context context;
Handler h = new Handler();
MyDictionaryRequest(Context context,TextView t1){
this.context = context;
this.t1=t1;
}
#Override
protected String doInBackground(String... strings) {
myurl = strings[0];
try {
URL url = new URL(myurl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setRequestProperty("app_id",app_id);
urlConnection.setRequestProperty("app_key",app_key);
// read the output from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String def;
try{
JSONObject js = new JSONObject(s);
JSONArray results = js.getJSONArray("results");
JSONObject lentries = results.getJSONObject(0);
JSONArray lArray= lentries.getJSONArray("lexicalEntries");
JSONObject entries = lArray.getJSONObject(0);
JSONArray e = entries.getJSONArray("entries");
JSONObject senses = e.getJSONObject(0);
JSONArray sensesArray = senses.getJSONArray("senses");
JSONObject d = sensesArray.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def=de.getString(0);
t1.setText(def);
Toast.makeText(context,def,Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Everthing is working fine in this code except that I can't get the word's meaning through edit text.
To be more specific :
The code works fine when I add
final String word = "car";
in dictionaryEntries() under Mainactivity.java
but nothing is displayed when :
final String word = et.getText().toString();
you have to move one of your code :
public void requestApiButtonClick(View v) {
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this, t1);
url = dictionaryEntries();
myDictionaryRequest.execute(url);
}

App Crashes while switching from one Activity to another

Aim: Building app on Google API to fetch the data about the books the user searches
Problem Explanation:
Whenever I hit the submit Button, my app crashes.
This is my first approach in making a network request app and I need guidance.
MainActivityClass
package com.example.vidit.books;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText query = (EditText) findViewById(R.id.query);
Button submit= (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(MainActivity.this,Request.class);
intent.putExtra ( "text", query.getText().toString() );
startActivity(intent);
}
});
}
}
Second Class
package com.example.vidit.books;
import android.content.Intent;
public class Request {
Intent i = getIntent();
String text = i.getStringExtra ("text");
public static final String LOG_TAG = Request.class.getSimpleName();
String APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
}
public void UpdateUi(Book book)
{
BookAdapter bookAdapter = new BookAdapter(this,book);
ListView listView= (ListView) findViewById(R.id.listview_all);
}
private class BookAsyncTask extends AsyncTask<URL,Void,Book>
{
#Override
protected Book doInBackground(URL... urls) {
URL url = createUrl(APIURL);
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
final Book book = extractFeatureFromJson(jsonResponse);
return book;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if(urlConnection.getResponseCode()==200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private Book extractFeatureFromJson(String bookJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(bookJSON);
JSONArray items = baseJsonResponse.getJSONArray("items");
// If there are results in the features array
for(int i=0;i<10;i++)
{
JSONObject firstFeature = items.getJSONObject(i);
JSONArray author=firstFeature.getJSONArray("author");
for(int j=0;j<author.length();j++)
{
JSONObject authorFeature=author.getJSONObject(j);
}
String title = items.getString(Integer.parseInt("title"));
// Create a new {#link Event} object
return new Book(title,author);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
}
BookAdapter Class:
package com.example.vidit.books;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Activity context, Book book)
{
super(context,0, (List<Book>) book);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book cbook=getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(cbook.getmTitle());
TextView author=(TextView) listItemView.findViewById(R.id.author);
author.setText((CharSequence) cbook.getmAuthor());
return listItemView;
}
}
Showing error in statement:
String text = i.getStringExtra ("text");
Need guidance
I don't know how your code gets compiled when you have overridden onCreate() in Request class and the Request class isn't extending Activity or AppCompatActivity.
Secondly, this line :
Intent i = getIntent();
String text = i.getStringExtra ("text");
should be inside the onCreate() method.
Showing error in statement : String text = i.getStringExtra ("text");
Request for Guidance
Well you need to get the data passed inside onCreate like below.
String APIURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
Bundle bundle = getIntent().getExtras();
String text = bundle.getString("text");
APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
}
And although you have the asyncTask class i can't see where exactly you execute the class. You need to do that inside onCreate as well.
Try moving this code to your onCreate method
Intent i = getIntent();
String text = i.getStringExtra ("text");
The intent extras is not available in the constructor for your Request class.

NullPointException when parsing xml in android

I'm trying to parse xml from the code bellow:
XMLParser xmlParser = new XMLParser();
String xml = xmlParser.getXmlFromUrl(URL2);
Document doc = xmlParser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("item");
Element e = (Element) nl.item(0);
that's working properly when URL2 = http://api.androidhive.info/pizza/?format=xml
But when im using my server: URL2 = http://udios.bugs3.com/test.xml it falls in the last line:
NodeList nl = doc.getElementsByTagName("item");
with the following exception:
NullPointerException
Unexpected token (position:TEXT #1:4 in java.io.StringReader#41391770)
The 2 xml files are identical, and i don't thing that the problem is in the server, maybe encoding problem?
I would appreciate if someone will help me
thanks
i think this link is used full...
check this Link
i have shown with only <name>...</name> tag, do the same with <id>...</id> , <cost>...</cost> and <description>...</description>
TextView name[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(URL2);
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
}
MyXMLHandler.java
/* This file is used to handle the XML tags. So we need to extends with DefaultHandler.
we need to override startElement, endElement & characters method .
startElemnt method called when the tag starts.
endElemnt method called when the tag ends
characres method to get characters inside tag.
*/
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/** Called when tag starts ( ex:- <name>Android</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("menu"))
{
/** Start */
sitesList = new SitesList();
}
}
/** Called when tag closing ( ex:- <name>Android</name>
* -- </name> )*/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("name"))
sitesList.setName(currentValue);
}
/** Called to get tag characters ( ex:- <name>Android</name>
* -- to get Android Character ) */
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
SitesList.java
// Contains Getter & Setter Method
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList {
/** Variables */
private ArrayList<String> name = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getName() {
return name;
}
public void setName(String name) {
this.name.add(name);
}
}
found workaround:
took the xml - open with notepad - save as (ANSI)

How to Display XML-parsing using sax

I want to create xml parsing using SAX of this URL
http://news.google.com/?output=rss
but I got the error please check and let me know where I do mistake or If there is another solutions for my problem.
I got error in GoogleNewsSaxActivity.class at this line
for (int i = 0; i < baseParserData.getTitle().size(); i++) {
My code is as per below.
GoogleNewsSaxActivity.class
public class GoogleNewsSaxActivity extends Activity {
BaseFeedParser baseParserData;
ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
private myAdapter rssadaptor = null;
ListView lview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://news.google.com/?output=rss");
RssHandler myXMLHandler = new RssHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
baseParserData = RssHandler.baseParserData;
/**
* Run a for loop to set All the TextViews with text until
* the size of the array is reached.
*
**/
for (int i = 0; i < baseParserData.getTitle().size(); i++) {
System.out.println("value of i==============>" + i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", baseParserData.getTitle().get(i));
//map.put("Artist", baseParserData.getArtist().get(i));
//map.put("Contry", baseParserData.getCountry().get(i));
items.add(map);
rssadaptor = new myAdapter(GoogleNewsSaxActivity.this, items);
}
lview = (ListView) findViewById(R.id.listView);
// Getting adapter by passing xml data ArrayList
rssadaptor = new myAdapter(this, items);
lview.setAdapter(rssadaptor);
}
}
RssHandler.class
public class RssHandler extends DefaultHandler{
/*private List<BaseFeedParser> messages;
//private Message currentMessage;
private StringBuilder builder;*/
String elementValue = null;
Boolean elementOn = false;
public static BaseFeedParser baseParserData = null;
public static BaseFeedParser getBaseParserData() {
return baseParserData;
}
public static void setBaseParserData(BaseFeedParser baseParserData) {
RssHandler.baseParserData = baseParserData;
}
/*public List<BaseFeedParser> getMessages(){
return this.messages;
}*/
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
elementOn = true;
System.out.println("Hello this is startElement : =========>");
if (localName.equals(BaseFeedParser.CHANNEL))
{
baseParserData = new BaseFeedParser();
} else if (localName.equals(BaseFeedParser.ITEM)) {
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase(BaseFeedParser.TITLE))
baseParserData.setTitle(elementValue);
else if (localName.equalsIgnoreCase(BaseFeedParser.LINK))
baseParserData.setLink(elementValue);
else if (localName.equalsIgnoreCase(BaseFeedParser.PUB_DATE))
baseParserData.setPubDate(elementValue);
else if (localName.equalsIgnoreCase(BaseFeedParser.DESCRIPTION))
baseParserData.setDescription(elementValue);
}
}
And also there are two another class BaseFeedParser.class and myAdapter.class , BaseFeedParser class contain the Getters/Setters metods and myadapter is adapter class for the custom listview.
Thanks.
Display error In LOGCAT
05-31 09:42:25.693: I/System.out(279): java.net.SocketException: Permission denied
05-31 09:42:25.713: D/AndroidRuntime(279): Shutting down VM
05-31 09:42:25.713: W/dalvikvm(279): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-31 09:42:25.752: E/AndroidRuntime(279): FATAL EXCEPTION: main
05-31 09:42:25.752: E/AndroidRuntime(279): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rahul.android.sax/com.rahul.android.sax.GoogleNewsSaxActivity}: java.lang.NullPointerException
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.os.Handler.dispatchMessage(Handler.java:99)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.os.Looper.loop(Looper.java:123)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-31 09:42:25.752: E/AndroidRuntime(279): at java.lang.reflect.Method.invokeNative(Native Method)
05-31 09:42:25.752: E/AndroidRuntime(279): at java.lang.reflect.Method.invoke(Method.java:521)
05-31 09:42:25.752: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-31 09:42:25.752: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-31 09:42:25.752: E/AndroidRuntime(279): at dalvik.system.NativeStart.main(Native Method)
05-31 09:42:25.752: E/AndroidRuntime(279): Caused by: java.lang.NullPointerException
05-31 09:42:25.752: E/AndroidRuntime(279): at com.rahul.android.sax.GoogleNewsSaxActivity.onCreate(GoogleNewsSaxActivity.java:61)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-31 09:42:25.752: E/AndroidRuntime(279): ... 11 more
Use Below Code for that.
SitesList.java
public class SitesList {
/** Variables */
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> website = new ArrayList<String>();
private ArrayList<String> pubdate = new ArrayList<String>();
private ArrayList<String> desc = new ArrayList<String>();
/**
* In Setter method default it will return arraylist change that to add
*/
public ArrayList<String> getName() {
return name;
}
public void setName(String name) {
this.name.add(name);
}
public ArrayList<String> getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website.add(website);
}
public ArrayList<String> getPubdate() {
return pubdate;
}
public void setPubdate(String pubdate) {
this.pubdate.add(pubdate);
}
public ArrayList<String> getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc.add(desc);
}
}
MyXMLHandler.java
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/**
* Called when tag starts ( ex:- <name>AndroidPeople</name> -- <name> )
*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("channel")) {
/** Start */
sitesList = new SitesList();
}
}
/**
* Called when tag closing ( ex:- <name>AndroidPeople</name> -- </name> )
*/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("title")) {
sitesList.setName(currentValue);
} else if (localName.equalsIgnoreCase("link")) {
sitesList.setWebsite(currentValue);
} else if (localName.equalsIgnoreCase("pubDate")) {
sitesList.setPubdate(currentValue);
} else if (localName.equalsIgnoreCase("description")) {
sitesList.setDesc(currentValue);
}
}
/**
* Called to get tag characters ( ex:- <name>AndroidPeople</name> -- to get
* AndroidPeople Character )
*/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
MainActivity.java
public class MainActivity extends Activity {
SitesList sitesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView name[];
TextView website[];
TextView pubdate[];
TextView desc[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://news.google.com/?output=rss");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Exception = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getWebsite().size()];
pubdate = new TextView[sitesList.getPubdate().size()];
desc = new TextView[sitesList.getDesc().size()];
System.out.println("Hello Name size is:- " +sitesList.getName().size());
System.out.println("Hello website size is:- " +sitesList.getWebsite().size());
System.out.println("Hello pubdate size is:- " +sitesList.getPubdate().size());
System.out.println("Hello desc size is:- " +sitesList.getDesc().size());
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name is = " + sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Link is = " + sitesList.getWebsite().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
}
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getPubdate().size(); i++) {
pubdate[i] = new TextView(this);
pubdate[i].setText("Pub date is = "
+ sitesList.getPubdate().get(i));
desc[i] = new TextView(this);
desc[i].setText("Desc is = "
+ sitesList.getDesc().get(i));
layout.addView(pubdate[i]);
layout.addView(desc[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}

Android: parse XML from string problems

I've got a custom contentHandler (called XMLHandler), I've been to a lot of sites via Google and StackOverflow that detail how to set that up.
What I do not understand is how to USE it.
Xml.parse(...,...) returns nothing, because it is a void method.
How do I access my parsed XML data?
I realize this question is probably trivial, but I've been searching for (literally) hours and have found no solution.
Please help.
String result = fetchData(doesntmatter);
Xml.parse(result, new XMLHandler());
Here is one example i hope it will be usefull to understand "SAXParser"
package test.example;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class XMLParsingDemo extends Activity {
private final String MY_DEBUG_TAG = "WeatherForcaster";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
try {
/* Create a URL we want to load some xml-data from. */
DefaultHttpClient hc = new DefaultHttpClient();
ResponseHandler <String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
String response=hc.execute(postMethod,res);
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
/* Parse the xml-data from our URL. */
InputSource inputSource = new InputSource();
inputSource.setEncoding("UTF-8");
inputSource.setCharacterStream(new StringReader(response));
/* Parse the xml-data from our URL. */
xr.parse(inputSource);
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
tv.setText(response + "\n\n\n***************************************" + parsedExampleDataSet.toString());
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
}
/* Display the TextView. */
this.setContentView(tv);
}
public class ExampleHandler extends DefaultHandler {
// ===========================================================
// Fields
// ===========================================================
private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_mytag = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException {
super.startElement(uri, localName, qName, atts);
if (localName.equals("outertag")) {
this.in_outertag = true;
}
else if (localName.equals("innertag")) {
String attrValue = atts.getValue("sampleattribute");
myParsedExampleDataSet.setExtractedString(attrValue);
this.in_innertag = true;
}
else if (localName.equals("mytag")) {
this.in_mytag = true;
}
else if (localName.equals("tagwithnumber")) {
// Extract an Attribute
String attrValue = atts.getValue("thenumber");
int i = Integer.parseInt(attrValue);
myParsedExampleDataSet.setExtractedInt(i);
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = false;
}else if (localName.equals("innertag")) {
this.in_innertag = false;
}else if (localName.equals("mytag")) {
this.in_mytag = false;
}else if (localName.equals("tagwithnumber")) {
// Nothing to do here
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_mytag){
myParsedExampleDataSet.setExtractedString(new String(ch));
}
}
}
public class ParsedExampleDataSet {
private String extractedString = null;
private int extractedInt = 0;
public String getExtractedString() {
return extractedString;
}
public void setExtractedString(String extractedString) {
this.extractedString = extractedString;
}
public int getExtractedInt() {
return extractedInt;
}
public void setExtractedInt(int extractedInt) {
this.extractedInt = extractedInt;
}
public String toString(){
return "\n\n\nExtractedString = " + this.extractedString
+ "\n\n\nExtractedInt = " + this.extractedInt;
}
}
}
You have to access your XML data into handler which you have define by XMLHandler()
you have to override
public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException {
}
#Override
public void endElement(String namespaceURI, String localName, String qName) {
}
and
#Override
public void characters(char ch[], int start, int length) {
}

Categories

Resources