Android database insert throws NULLPointerException while XML parsing - android

I am trying to insert data of Books by parsing XML file. It allows me to parse the file but throws me error java.lang.NullPointerException on getWritableDatabase.
It throws me error in MyXMLHandler.java file at line:
xmDB = new XMLDatabaseManager(context);
xmDB.insertFeed(currentValue);
I have my code below which I use to develop it. I have been working on this for a long time today but cannot figure out the error. It will be really helpful if you can help me here.
package org.database.databasemanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class XMLDatabaseManager {
// the activity or appliation that is creating an object
Context context;
private SQLiteDatabase db;
private final String DATABASE_NAME = "Main.db";
private final int DATABASE_VERSION = 1;
// Table name
public final String TABLE = "events";
// Columns
public static final String TIME = "time";
public final String TITLE = "title";
private final String TAG = "MyActivity";
public XMLDatabaseManager(Context context){
this.context = context;
EventDataSQLHelper helper = new EventDataSQLHelper(context);
this.db = helper.getWritableDatabase();
}
public class EventDataSQLHelper extends SQLiteOpenHelper {
public EventDataSQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + "( " + BaseColumns._ID
+ " integer primary key autoincrement, "
+ TITLE + " text not null);";
Log.d("EventsData", "onCreate: " + sql);
db.execSQL(sql);
Log.v(TAG, "secondnameText");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public boolean insertFeed( String title) {
ContentValues values = new ContentValues();
values.put("title", title);
return (this.db.insert(TABLE, null, values) > 0);
}
}
The following code used for Parsing XML file and inserting at the end of the element.
package org.database.databasemanager;
import org.database.databasemanager.XMLDatabaseManager;
import org.database.databasemanager.XMLDatabaseManager.EventDataSQLHelper;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.util.Log;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
Context context;
private SQLiteDatabase db;
private XMLDatabaseManager xmDB;
public static SitesList sitesList = null;
private final String TAG = "KEY";
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("Books"))
{
sitesList = new SitesList();
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("title")){
// Get the value here
Log.d(TAG, currentValue);
ERROR THROWN HERE
--------------------------
xmDB = new XMLDatabaseManager(context);
xmDB.insertFeed(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;
}
}
}
Activity class :
package org.database.databasemanager;
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.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class DatabaseManagerActivity extends Activity {
XMLDatabaseManager db;
private final String TAG = "SIZE";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new XMLDatabaseManager(this);
SitesList sitesList = null;
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
//xr.parse(new InputSource(sourceUrl.openStream()));
xr.parse(new InputSource(getAssets().open("Books1.xml")));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
e.printStackTrace();
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Set the layout view to display */
setContentView(layout);
}
catch (Exception e)
{
Log.e("ERROR", e.toString());
e.printStackTrace();
}
}
}

Your MyXMLHandler has the context member, but I don't see anywhere it gets updated. Make sure you supply a valid value for that before trying to create the database.
Also, you should only create the database once and keep a handle to it rather than creating a new handle at the end of every element. Inserts are already slow, no need to make them slower!

Related

can't retrieve data with SAX Parser

I'am trying to parse an XML file from server, i fellowed this tutorial but I couldn't retrieve Data in activity either in Logcat!
It's showing a NullPointerException at this line
for(int i = 0; i < data.getTitle().size(); i++)
Based to the tutorial i don't know if I intialised the variable data correctly in the activity .
so This is my MainActivity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView title[];
TextView artist[];
TextView country[];
TextView company[];
TextView price[];
TextView year[];
public static XMLGettersSetters data ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View layout = findViewById(R.id.layout);
for (int i = 0; i < data.getTitle().size(); i++) {
title[i] = new TextView(this);
title[i].setText("Title= " + data.getTitle().get(i));
artist[i] = new TextView(this);
artist[i].setText("Artist=" + data.getArtist().get(i));
company[i] = new TextView(this);
company[i].setText("Company=" + data.getCompany().get(i));
country[i] = new TextView(this);
country[i].setText("Country=" + data.getCountry().get(i));
price[i] = new TextView(this);
price[i].setText("Price=" + data.getPrice().get(i));
year[i] = new TextView(this);
year[i].setText("Year=" + data.getYear().get(i));
((ViewGroup) layout).addView(title[i]);
((ViewGroup) layout).addView(artist[i]);
((ViewGroup) layout).addView(company[i]);
((ViewGroup) layout).addView(country[i]);
((ViewGroup) layout).addView(price[i]);
((ViewGroup) layout).addView(year[i]);
}
}
}
XMLHandler class
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class XMLHandler extends DefaultHandler {
String elementValue = null;
Boolean elementOn = false;
public static XMLGettersSetters data = null;
public static XMLGettersSetters getXMLData() {
return data;
}
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
/**
* This will be called when the tags of the XML starts.
**/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
if (localName.equals("CATALOG")) {
data = new XMLGettersSetters();
} else if (localName.equals("CD")) {
/**
* We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> )
* we can get the value "band". Below is an example of how to achieve this.
*
* String attributeValue = attributes.getValue("attr");
* data.setAttribute(attributeValue);
*
* */
try {
/**
* Create a new instance of the SAX parser
**/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml"); // URL of the XML
/**
* Create the Handler to handle each of the XML tags.
**/
XMLHandler myXMLHandler = new XMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
// View layout = findViewById(R.id.layout);
} catch (Exception e) {
System.out.println(e);
}
}
}
/**
* This will be called when the tags of the XML end.
**/
#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("title"))
data.setTitle(elementValue);
else if (localName.equalsIgnoreCase("artist"))
data.setArtist(elementValue);
else if (localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
else if (localName.equalsIgnoreCase("company"))
data.setCompany(elementValue);
else if (localName.equalsIgnoreCase("price"))
data.setPrice(elementValue);
else if (localName.equalsIgnoreCase("year"))
data.setYear(elementValue);
}
/**
* This is called to get the tags value
**/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
XmlGettersSetters
import android.util.Log;
import java.util.ArrayList;
public class XMLGettersSetters {
//company
private ArrayList<String> company = new ArrayList<String>();
public ArrayList<String> getCompany() {
return company;
}
public void setCompany(String company) {
this.company.add(company);
Log.i("This is the company:", company);
}
//title
private ArrayList<String> title = new ArrayList<String>();
public ArrayList<String> getTitle() {
return title;
}
public void setTitle(String title) {
this.title.add(title);
Log.i("This is the title:", title);
}
//artist
private ArrayList<String> artist = new ArrayList<String>();
public ArrayList<String> getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist.add(artist);
Log.i("This is the artist:", artist);
}
//country
private ArrayList<String> country = new ArrayList<String>();
public ArrayList<String> getCountry() {
return country;
}
public void setCountry(String country) {
this.country.add(country);
Log.i("This is the country:", country);
}
//price
private ArrayList<String> price = new ArrayList<String>();
public ArrayList<String> getPrice() {
return price;
}
public void setPrice(String price) {
this.price.add(price);
Log.i("This is the price:", price);
}
//year
private ArrayList<String> year = new ArrayList<String>();
public ArrayList<String> getYear() {
return year;
}
public void setYear(String year) {
this.year.add(year);
Log.i("This is the Year:", year);
}
}
As far as I can tell, you never initialized the data field in MainActivity. Also, making it static seems like a bad idea. Java statics are almost always a bad idea unless you really know you need one.

How to parse xml for HTTPS url using SAXParser in Android

URL url = new URL("https://www.setindia.com");
URLConnection urlConnectionObject = url.openConnection();
xmlHandlerObject = new XMLHandler();
xmlReaderObject.setContentHandler(xmlHandlerObject);
xmlReaderObject.parse(new InputSource(urlConnectionObject.getInputStream()));
// error on the last line please get me an explanation (new to android) and is this right
MAIN ACTIVITY:
package com.example.testparser;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
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.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends Activity {
public static String TAG = "MYParser";
GettersSetters getData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate");
View layout = findViewById(R.id.layout);
TextView tittle[];
TextView country[];
XMLHandler xmlHandlerObject = null;
try{
Log.d(TAG, "try");
SAXParserFactory saxParserFactoryObject = SAXParserFactory.newInstance(); //obtain and configure a SAX based parser
SAXParser saxParserObject = saxParserFactoryObject.newSAXParser(); //obtaining object for SAX parser
XMLReader xmlReaderObject = saxParserObject.getXMLReader();
URL url = new URL("https://www.setindia.com/setindia_api/episode/1?date=22-10-2013&hd=1");
URLConnection urlConnectionObject = url.openConnection();
xmlHandlerObject = new XMLHandler();
xmlReaderObject.setContentHandler(xmlHandlerObject);
Log.d(TAG, "about to get an error");
xmlReaderObject.parse(new InputSource(urlConnectionObject.getInputStream()));
Log.d(TAG, "try end");
}
catch (Exception e) {
Log.e(TAG, e.getMessage());
}
Log.d(TAG, "OnCreate fetching the data from the xml");
getData = xmlHandlerObject.getXMLData();
tittle = new TextView[getData.getTittle().size()];
country = new TextView[getData.getCountry().size()];
for (int i = 0; i < getData.getTittle().size(); i++) {
tittle[i] = new TextView(this);
tittle[i].setText("ITEM is : " + getData.getTittle().get(i));
country[i] = new TextView(this);
country[i].setText("Country is :" + getData.getTittle().get(i));
((ViewGroup) layout).addView(tittle[i]);
((ViewGroup) layout).addView(country[i]);
setContentView(R.layout.main);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
GettersSetters :
package com.example.testparser;
import java.lang.reflect.Array;
import java.util.ArrayList;
import android.util.Log;
public class GettersSetters {
private ArrayList<String> tittle = new ArrayList<String>();
private ArrayList<String> country = new ArrayList<String>();
public ArrayList<String> getCountry(){
return country;
}
public ArrayList<String> getTittle(){
return tittle;
}
public void setCountry(String country){
this.country.add(country);
Log.i("This is the country : ",country);
}
public void setTittle(String tittle){
this.tittle.add(tittle);
Log.i("This is the tittle : ",tittle);
}
}
XMLHandler:
package com.example.testparser;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHandler extends DefaultHandler {
public static String TAG = "MYParser";
public static GettersSetters data = null;
String elementValue = null ;
Boolean elementOn = false;
public GettersSetters getXMLData(){
Log.e(TAG, "getXMLdata -> "+data.toString());
return data;
}
public void setXMLData(GettersSetters data){
XMLHandler.data = data;
Log.e(TAG, "setXmldata");
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
elementOn = true;
Log.d(TAG, "Checking the first element"+localName.equalsIgnoreCase("item"));
if(localName.equalsIgnoreCase("item"))
{
Log.d(TAG, "Creating a new getter setter instance");
data = new GettersSetters();
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if(elementOn)
{
elementValue = new String(ch,start,length);
elementOn =false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
super.endElement(uri, localName, qName);
if(localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
if(localName.equalsIgnoreCase("tittle"))
data.setTittle(elementValue);
}
}
MAIN.Xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SAGAR HERE"
android:textSize="20dp"
android:gravity="center_horizontal"
android:id="#+id/layout"
/>
</LinearLayout>
Don't do network operations on UI Thread (main).
You can use AsyncTask which enables proper and easy use of the UI thread. it allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers (It uses an inner thread pool). See more at: AsyncTask API

XML parsing from local xml

I'm parsing XML from URL. What changes has been made to parse same XML file from raw folder. Have any idea to how to reduce code ?
This my xml file :umesh.xml
<?xml version="1.0" encoding="utf-8"?>
<appdata>
<brand name="Lovely Products">
<product>Hat</product>
<product>Gloves</product>
</brand>
<brand name="Great Things">
<product>Table</product>
<product>Chair</product>
<product>Bed</product>
</brand>
</appdata>
Below is my java file :
DataHandler.java
package com.umesh.xmlparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.util.Log;
import android.widget.TextView;
public class DataHandler extends DefaultHandler{
//list for imported product data
private ArrayList<TextView> theViews;
//string to track each entry
private String currBrand = "";
//flag to keep track of XML processing
private boolean isProduct = false;
//context for user interface
private Context theContext;
//constructor
public DataHandler(Context cont) {
super();
theViews = new ArrayList<TextView>();
theContext = cont;
}
//start of the XML document
public void startDocument () { Log.i("DataHandler", "Start of XML document"); }
//end of the XML document
public void endDocument () { Log.i("DataHandler", "End of XML document"); }
//opening element tag
public void startElement (String uri, String name, String qName, Attributes atts)
{
//handle the start of an element
//find out if the element is a brand
if(qName.equals("brand"))
{
//set product tag to false
isProduct = false;
//create View item for brand display
TextView brandView = new TextView(theContext);
brandView.setTextColor(Color.rgb(73, 136, 83));
//add the attribute value to the displayed text
String viewText = "Items from " + atts.getValue("name") + ":";
brandView.setText(viewText);
//add the new view to the list
theViews.add(brandView);
}
//the element is a product
else if(qName.equals("product"))
isProduct = true;
}
//closing element tag
public void endElement (String uri, String name, String qName)
{
//handle the end of an element
if(qName.equals("brand"))
{
//create a View item for the products
TextView productView = new TextView(theContext);
productView.setTextColor(Color.rgb(192, 199, 95));
//display the compiled items
productView.setText(currBrand);
//add to the list
theViews.add(productView);
//reset the variable for future items
currBrand = "";
}
}
//element content
public void characters (char ch[], int start, int length)
{
//process the element content
//string to store the character content
String currText = "";
//loop through the character array
for (int i=start; i<start+length; i++)
{
switch (ch[i]) {
case '\\':
break;
case '"':
break;
case '\n':
break;
case '\r':
break;
case '\t':
break;
default:
currText += ch[i];
break;
}
}
//prepare for the next item
if(isProduct && currText.length()>0)
currBrand += currText+"\n";
}
public ArrayList<TextView> getData()
{
//take care of SAX, input and parsing errors
try
{
//set the parsing driver
System.setProperty("org.xml.sax.driver","org.xmlpull.v1.sax2.Driver");
//create a parser
SAXParserFactory parseFactory = SAXParserFactory.newInstance();
SAXParser xmlParser = parseFactory.newSAXParser();
//get an XML reader
XMLReader xmlIn = xmlParser.getXMLReader();
//instruct the app to use this object as the handler
xmlIn.setContentHandler(this);
//provide the name and location of the XML file **ALTER THIS FOR YOUR FILE**
URL xmlURL = new URL("http://mydomain.com/umesh.xml");
//open the connection and get an input stream
URLConnection xmlConn = xmlURL.openConnection();
InputStreamReader xmlStream = new InputStreamReader(xmlConn.getInputStream());
//build a buffered reader
BufferedReader xmlBuff = new BufferedReader(xmlStream);
// uuu XmlResourceParser todolistXml = getResources().getXml(R.raw.c4mh_clinics);
//parse the data
xmlIn.parse(new InputSource(xmlBuff));
}
catch(SAXException se) { Log.e("AndroidTestsActivity",
"SAX Error " + se.getMessage()); }
catch(IOException ie) { Log.e("AndroidTestsActivity",
"Input Error " + ie.getMessage()); }
catch(Exception oe) { Log.e("AndroidTestsActivity",
"Unspecified Error " + oe.getMessage()); }
//return the parsed product list
return theViews;
}
}
XMLParsing.java
package com.umesh.xmlparsing;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsing extends Activity {
TextView tv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get a reference to the layout
LayoutInflater inflater = getLayoutInflater();
LinearLayout mainLayout = (LinearLayout) inflater.inflate(R.layout.main,null);
try
{
//create an instance of the DefaultHandler class
//**ALTER THIS FOR YOUR CLASS NAME**
DataHandler handler = new DataHandler(getApplicationContext());
//get the string list by calling the public method
ArrayList<TextView> newViews = handler.getData();
//convert to an array
Object[] products = newViews.toArray();
//loop through the items, creating a View item for each
for(int i=0; i<products.length; i++)
{
//add the next View in the list
mainLayout.addView((TextView)products[i]);
}
}
catch(Exception pce) { Log.e("AndroidTestsActivity", "PCE "+pce.getMessage()); }
setContentView(mainLayout);
}
}
Please See below link of my answer, it will solve your problem.
Local XML Parsing

How to read weather data through google weather API

I am developing weather sample application by using Google weather API for android and so far I have developed(You can see image below)
I have problem how to read the data as shown in the red rectangle below. Now what changes do I needed in the source code to read the data.
My main activity
package org.anddev.android.weatherforecast;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.anddev.android.weatherforecast.views.SingleWeatherInfoView;
import org.anddev.android.weatherforecast.weather.GoogleWeatherHandler;
import org.anddev.android.weatherforecast.weather.WeatherCurrentCondition;
import org.anddev.android.weatherforecast.weather.WeatherForecastCondition;
import org.anddev.android.weatherforecast.weather.WeatherSet;
import org.anddev.android.weatherforecast.weather.WeatherUtils;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
public class WeatherForecast extends Activity
{
private final String DEBUG_TAG = "WeatherForcaster";
private CheckBox chk_usecelsius = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius);
Button cmd_submit = (Button) findViewById(R.id.cmd_submit);
cmd_submit.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
URL url;
try {
/* Get what user typed to the EditText. */
String cityParamString = ((EditText) findViewById(R.id.edit_input)).getText().toString();
String queryString = "http://www.google.com/ig/api?weather=Peshawar, Khyber Pakhtunkhwa"; //Lincoln,Nebraska
/* Replace blanks with HTML-Equivalent. */
url = new URL(queryString.replace(" ", "%20"));
/* 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
*/
GoogleWeatherHandler gwh = new GoogleWeatherHandler();
xr.setContentHandler(gwh);
/* Parse the xml-data our URL-call returned. */
xr.parse(new InputSource(url.openStream()));
/* Our Handler now provides the parsed weather-data to us. */
WeatherSet ws = gwh.getWeatherSet();
/* Update the SingleWeatherInfoView with the parsed data. */
updateWeatherInfoView(R.id.weather_today, ws.getWeatherCurrentCondition());
updateWeatherInfoView(R.id.weather_1, ws.getWeatherForecastConditions().get(0));
updateWeatherInfoView(R.id.weather_2, ws.getWeatherForecastConditions().get(1));
updateWeatherInfoView(R.id.weather_3, ws.getWeatherForecastConditions().get(2));
updateWeatherInfoView(R.id.weather_4, ws.getWeatherForecastConditions().get(3));
}
catch (Exception e)
{
resetWeatherInfoViews();
Log.e(DEBUG_TAG, "WeatherQueryError", e);
}
}
});
}
private void updateWeatherInfoView(int aResourceID,WeatherForecastCondition aWFIS)
throws MalformedURLException
{
/* Construct the Image-URL. */
URL imgURL = new URL("http://www.google.com" + aWFIS.getIconURL());
((SingleWeatherInfoView) findViewById(aResourceID)).setRemoteImage(imgURL);
int tempMin = aWFIS.getTempMinCelsius();
int tempMax = aWFIS.getTempMaxCelsius();
/* Convert from Celsius to Fahrenheit if necessary. */
if (this.chk_usecelsius.isChecked())
{
((SingleWeatherInfoView) findViewById(aResourceID)).setTempCelciusMinMax(tempMin, tempMax);
}
else
{
tempMin = WeatherUtils.celsiusToFahrenheit(tempMin);
tempMax = WeatherUtils.celsiusToFahrenheit(tempMax);
((SingleWeatherInfoView) findViewById(aResourceID)).setTempFahrenheitMinMax(tempMin, tempMax);
}
}
private void updateWeatherInfoView(int aResourceID,
WeatherCurrentCondition aWCIS) throws MalformedURLException
{
/* Construct the Image-URL. */
URL imgURL = new URL("http://www.google.com" + aWCIS.getIconURL());
((SingleWeatherInfoView) findViewById(aResourceID)).setRemoteImage(imgURL);
/* Convert from Celsius to Fahrenheit if necessary. */
if (this.chk_usecelsius.isChecked())
{
((SingleWeatherInfoView) findViewById(aResourceID)).setTempCelcius(aWCIS.getTempCelcius());
}
else
{
((SingleWeatherInfoView) findViewById(aResourceID)).setTempFahrenheit(aWCIS.getTempFahrenheit());
}
}
private void resetWeatherInfoViews()
{
((SingleWeatherInfoView)findViewById(R.id.weather_today)).reset();
((SingleWeatherInfoView)findViewById(R.id.weather_1)).reset();
((SingleWeatherInfoView)findViewById(R.id.weather_2)).reset();
((SingleWeatherInfoView)findViewById(R.id.weather_3)).reset();
((SingleWeatherInfoView)findViewById(R.id.weather_4)).reset();
}
}
Weather info view activity
package org.anddev.android.weatherforecast.views;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import org.anddev.android.weatherforecast.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* The View capable of showing a WeatehrIcon + a Temperature-TextView.
*/
public class SingleWeatherInfoView extends LinearLayout {
// ===========================================================
// Fields
// ===========================================================
private ImageView myWeatherImageView = null;
private TextView myTempTextView = null;
// ===========================================================
// Constructors
// ===========================================================
public SingleWeatherInfoView(Context context)
{
super(context);
}
public SingleWeatherInfoView(Context context, AttributeSet attrs) //,Map inflateParams
{
super(context,attrs);
/* Setup the ImageView that will show weather-icon. */
this.myWeatherImageView = new ImageView(context);
this.myWeatherImageView.setImageDrawable(getResources().getDrawable(R.drawable.dunno));
/* Setup the textView that will show the temperature. */
this.myTempTextView = new TextView(context);
this.myTempTextView.setText("? °C");
this.myTempTextView.setTextSize(16);
this.myTempTextView.setTypeface(Typeface.create("Tahoma", Typeface.BOLD));
/* Add child views to this object. */
this.addView(this.myWeatherImageView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
this.addView(this.myTempTextView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void reset()
{
this.myWeatherImageView.setImageDrawable(getResources().getDrawable(R.drawable.dunno));
this.myTempTextView.setText("? °C");
}
/** Sets the Child-ImageView of this to the URL passed. */
public void setRemoteImage(URL aURL)
{
try
{
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
this.myWeatherImageView.setImageBitmap(bm);
}
catch (IOException e)
{
/* Reset to 'Dunno' on any error. */
this.myWeatherImageView.setImageDrawable(getResources().getDrawable(R.drawable.dunno));
}
}
public void setTempCelcius(int aTemp)
{
this.myTempTextView.setText("" + aTemp + " °C");
}
public void setTempFahrenheit(int aTemp)
{
this.myTempTextView.setText("" + aTemp + " °F");
}
public void setTempFahrenheitMinMax(int aMinTemp, int aMaxTemp)
{
this.myTempTextView.setText("" + aMinTemp + "/" + aMaxTemp + " °F");
}
public void setTempCelciusMinMax(int aMinTemp, int aMaxTemp)
{
this.myTempTextView.setText("" + aMinTemp + "/" + aMaxTemp + " °C");
}
public void setTempString(String aTempString)
{
this.myTempTextView.setText(aTempString);
}
}

Android SAX Parser Error

I'm trying to make an SAX Parser for Android and started off by reading only one tag from the external XML file. I get an 'Unfortunately, -- has stopped' error. I looked at the Log file and it gives my a null reference error. My guess is the XMLAdapter class isn't working fine and I haven't been able to figure the problem out.
Here's my Main activity:
package com.vint.michiganbus;
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.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.view.Window;
import android.util.Log;
public class listView extends Activity {
XMLGettersSetters data;
private static final String TAG = "listView";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
View layout = findViewById(R.id.layout);
TextView title[];
Log.i(TAG, "data is hello");
try {
/**
* Create a new instance of the SAX parser
**/
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://mbus.pts.umich.edu/shared/public_feed.xml"); // URL of the XML
/**
* Create the Handler to handle each of the XML tags.
**/
XMLHandler myXMLHandler = new XMLHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
data = XMLHandler.data;
/**
* Makes the TextView length the size of the TextView arrays by getting the size of the
**/
title = new TextView[data.get().size()];
/**
* Run a for loop to set All the TextViews with text until
* the size of the array is reached.
*
**/
for (int i = 0; i < data.get().size(); i++) {
title[i] = new TextView(this);
title[i].setText("Title = "+data.get().get(i));
((ViewGroup) layout).addView(title[i]);
}
setContentView(layout);
//setContentView(R.layout.listview);
}
}
Here's my XML Handler:
package com.vint.michiganbus;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHandler extends DefaultHandler {
private static final String TAG = "In Handler";
String elementValue = null;
Boolean elementOn = false;
public static XMLGettersSetters data = null;
public static XMLGettersSetters getXMLData() {
return data;
}
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
/**
* This will be called when the tags of the XML starts.
**/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
Log.i(TAG, "starting Element "+localName);
if (localName.equals("livefeed"))
{
data = new XMLGettersSetters();
} else if (localName.equals("routecount")) {
/**
* We can get the values of attributes for eg. if the CD tag had an attribute( <CD attr= "band">Akon</CD> )
* we can get the value "band". Below is an example of how to achieve this.
*
* String attributeValue = attributes.getValue("attr");
* data.setAttribute(attributeValue);
*
* */
}
}
/**
* This will be called when the tags of the XML end.
**/
#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("routecount"))
data.set(elementValue);
/*else if (localName.equalsIgnoreCae("artist"))
data.setArtist(elementValue);
else if (localName.equalsIgnoreCase("country"))
data.setCountry(elementValue);
else if (localName.equalsIgnoreCase("company"))
data.setCompany(elementValue);
else if (localName.equalsIgnoreCase("price"))
data.setPrice(elementValue);
else if (localName.equalsIgnoreCase("year"))
data.setYear(elementValue);*/
}
/**
* This is called to get the tags value
**/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
And this is my GetterSetter class
package com.vint.michiganbus;
import java.util.ArrayList;
public class XMLGettersSetters {
private ArrayList<String> routecount = new ArrayList<String>();
public ArrayList<String> get() {
return routecount;
}
public void set(String company) {
this.routecount.add(company);
}
}
Any help will be greatly appreciated!
ps: If anyone has suggestions how to handle the XML in the URL efficiently I'd love that!
The error might be that you're trying to retrieve a web file from the activity thread. I would create an AsyncTask, put all my parser code in the doInBackground() method from AsyncTask.
Something that would look like this :
private class DownloadFilesTask extends AsyncTask<Document, Integer, Document>
{
Document doc;
String xml;
public DownloadFilesTask(){}
protected Document doInBackground(Document... params)
{
xml = xmlFunctions.getXML("Your URL");
doc = XmlFunctions.XMLfromString(xml);
return doc;
}
protected void onPostExecute(Document result)
{
//Some code changing UI from the nodes you've just parsed
}
}
then you can call this class in your onCreate using :
new DownloadTaskfiles().execute();
Hope this is of some help!

Categories

Resources