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.
Related
I am trying to make an app which uses last.fm's web API, sends a query for similar artists and returns all the names of the similar artists. It seems as though I manage to connect and get the xml response properly. However, I cannot extract the value of the name-attribute. I am using artistName = xmlData.getAttributeValue(null, "name"); but all it gives me is null.
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
#SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
private final String INPUTERROR = "Invalid/missing artist name.";
private NetworkCommunication nc;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nc = new NetworkCommunication();
nc.register(this);
list = new ArrayList<>();
ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void searchButton_Clicked(View v){
EditText inputField = (EditText)findViewById(R.id.editText_artistName);
String searchString = inputField.getText().toString();
searchString = cleanSearchString(searchString);
if(validateSearchString(searchString)){
nc.setSearchString(searchString);
nc.execute();
}
else{
Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
}
}
private String cleanSearchString(String oldSearchString){
String newString = oldSearchString.trim();
newString = newString.replace(" ", "");
return newString;
}
private boolean validateSearchString(String searchString){
boolean rValue = true;
if(TextUtils.isEmpty(searchString)){
rValue = false;
}
return rValue;
}
#Override
public void update(String artistName) {
list.add(artistName);
}
}
Here is my Network Communications class:
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
private final String MYAPIKEY = "--------------------------";
private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
private final String METHOD = "?method=artist.getsimilar";
private ArrayList<Observer> observers;
private int amountOfArtists = 0;
private String foundArtistName;
private String searchString;
NetworkCommunication(){
observers = new ArrayList<>();
}
void setSearchString(String newSearchString){
searchString = newSearchString;
}
private XmlPullParser sendRequest(){
try{
URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
receivedData.setInput(url.openStream(), null);
return receivedData;
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
return null;
}
private int tryProcessData(XmlPullParser xmlData){
int artistsFound = 0;
String artistName;
int eventType;
try{
while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if(xmlData.getName().equals("name")){
artistName = xmlData.getAttributeValue(null, "name");
publishProgress(artistName);
artistsFound++;
}
}
}
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
if (artistsFound == 0) {
publishProgress();
}
return artistsFound;
}
#Override
protected Integer doInBackground(Object... params) {
XmlPullParser data = sendRequest();
if(data != null){
return tryProcessData(data);
}
else{
return null;
}
}
#Override
protected void onProgressUpdate(String... values){
/*
if (values.length == 0) {
//No data found...
}
*/
if (values.length == 1) {
setFoundArtistName(values[0]);
notifyObserver();
}
super.onProgressUpdate(values);
}
private void setFoundArtistName(String newArtistName){
foundArtistName = newArtistName;
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
observers.remove(deleteObserver);
}
#Override
public void notifyObserver() {
for (Observer o : observers) {
Log.i("my tag.... ", "name = " + foundArtistName);
o.update(foundArtistName);
}
}
}
Here's a screenshot of the xml response in Google Chrome:
The only thing I am interested in extracting at this moment is the the value of the Name-Element.
I am logging the value of foundArtistName (in the method notifyObserver) it gives me A LOT of "my tag.... name = null my tag.... name = null my tag.... name = null etc.."
EDIT: I tried using getText() instead of getAttributeValue(), but it also gives me null.
I found the solution. I was using: artistName = xmlData.getAttributeValue(null, "name");, when I really should've used: artistName = xmlData.nextText();
I already made an Android RSS Feed App from Google Alerts Source. After I compiled and running only showing about half article or can't fetch all text from one source but not crash.
From RssAtomParseHandler.java
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.a.b.c.d.e.RssAtomItem;
public class RssAtomParseHandler extends DefaultHandler {
private List<RssAtomItem> rssItems;
// Used to reference item while parsing
private RssAtomItem currentItem;
// Parsing title indicator
private boolean parsingTitle;
// Parsing link indicator
private boolean parsingContents;
// A buffer for title contents
private StringBuffer currentTitleSb;
// A buffer for content tag contents
private StringBuffer currentContentSb;
public RssAtomParseHandler() {
rssItems = new ArrayList<RssAtomItem>();
}
public List<RssAtomItem> getItems() {
return rssItems;
}
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("entry".equals(qName)) {
currentItem = new RssAtomItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
currentTitleSb = new StringBuffer();
} else if ("content".equals(qName)) {
parsingContents = true;
currentContentSb = new StringBuffer();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("entry".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
if (currentItem != null) // There is a title tag for a whole channel present. It is being parsed before the entry tag is present, so we need to check if item is not null
currentItem.setTitle(currentTitleSb.toString());
} else if ("content".equals(qName)) {
parsingContents = false;
if (currentItem != null)
currentItem.setContent(currentContentSb.toString());
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (parsingTitle) {
if (currentItem != null)
currentTitleSb.append(new String(ch, start, length));
} else if (parsingContents) {
if (currentItem != null)
currentContentSb.append(new String(ch, start, length));
}
} }
From RssAtomReader.java
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.a.b.c.d.e.RssAtomItem;
public class RssAtomReader {
private String rssUrl;
/**
* Constructor
*
* #param rssUrl
*/
public RssAtomReader(String rssUrl) {
this.rssUrl = rssUrl;
}
/**
* Get RSS items.
*
* #return
*/
public List<RssAtomItem> getItems() throws Exception {
// SAX parse RSS data
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
RssAtomParseHandler handler = new RssAtomParseHandler();
saxParser.parse(rssUrl, handler);
return handler.getItems();
} }
From activity_details.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:id="#+id/detailsTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="[POST TITLE GOES HERE]"
android:textAppearance="?android:attr/textAppearanceMedium" />
<WebView
android:id="#+id/detailsWebView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
How I can fix it so it will show ?
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
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!
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!