I have an xml parser class which crashes if I'm not connected to the internet. Is there anyway that I can get the class to go to a layout that says, "no connection" or something similar when a connection is not present. thanks
Xml Parser
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
Activity that uses parser
public class CustomizedListView extends Fragment { // All static variables
static final String URL = "http://graffiti.hostoi.com/00Graffiti00/lists/00main00.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
static final String KEY_LINK = "key";
ListView list;
LazyAdapter adapter;
ArrayList<HashMap<String, String>> songsList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.news, container, false);
songsList = new ArrayList<HashMap<String, String>>();
list=(ListView) rootView.findViewById(R.id.list);
new RetrieveXML().execute(URL);
XMLParser parser = new XMLParser();
// Getting adapter by passing xml data ArrayList
// Click event for single list row
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), Article.class);
new Bundle();
intent.putExtra( "b", songsList.get(position).get(KEY_LINK));
startActivity(intent);
}
});
return rootView;
}
class RetrieveXML extends AsyncTask<String, Void, String> {
private Exception exception;
XMLParser parser = new XMLParser();
protected String doInBackground(String... urls) {
try {
return parser.getXmlFromUrl(urls[0]);
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(String xml) {
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_ID));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
adapter=new LazyAdapter(getActivity(), songsList);
list.setAdapter(adapter);
}
}
Try this..
Add the below class in your package
Utils.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
public class Utils {
public static boolean connectivity(Context c) {
if(c != null)
{
ConnectivityManager connec = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isConnected()||mobile.isConnected())
return true;
else if (wifi.isConnected() && mobile.isConnected())
return true;
else
return false;
} catch (NullPointerException e) {
Log.d("ConStatus", "No Active Connection");
return false;
}
}
else
{
Log.v("utils--", "null");
return false;
}
}
}
And before calling that RetrieveXML AsyncTask use like below code.
if(Utils.connectivity(getActivity()))
{
new RetrieveXML().execute(URL);
XMLParser parser = new XMLParser();
}
else
{
Toast.makeText(getActivity(), "Please connect to working internet connection.", Toast.LENGTH_SHORT).show();
}
Related
After much research, I can't manage to layout some XML data in my android app.
There is my MainActivity.java :
public class MainActivity extends Activity {
TextView textview1;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetXmlTask task = new GetXmlTask(textview1 , "http://www.3pi.tf/test.xml"); // get the XML
Log.i("TAG", "test1");
task.execute(); // execute the task
Log.i("TAG","test2");
textview1 = (TextView) findViewById(R.id.textview1);
Log.i("TAG", "test4");
}
}
And there is my GetXmlTask.java :
public class GetXmlTask extends AsyncTask<Void, Void, String>{
public WeakReference<TextView> textViewReference;
public String url;
public GetXmlTask(TextView textview, String url) {
this.textViewReference = new WeakReference<TextView>(textview);
this.url = url;
}
public String THEXML = null;
public String doInBackground(Void... sUrl) {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://3pi.tf/test.xml");
Log.i("TAG2",""+request);
HttpResponse response = httpclient.execute(request);
Log.i("TAG2",""+response);
HttpEntity resEntity = response.getEntity();
Log.i("TAG2",""+resEntity);
THEXML = EntityUtils.toString(resEntity);
Log.i("DONNEES XML",""+THEXML);
}
catch(Exception e){ e.printStackTrace(); }
return THEXML;
}
public Document getDomElement(String task) {
Log.i("TAG2","test01");
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(task));
doc = db.parse(is);
}
catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
}
catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
}
catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
//Retrieve each element child element value by using node name of element.
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
As you can see, I put some logcat in to see how it passes through.
I can see all my XML in the logcat with the variable "THEXML" but I can't layout to my mobile app... I did all the method in an AsyncTask because that was highly recommended..
Please help me
Thank you
Use a interface as a callback to the activity
GetXmlTask task = new GetXmlTask(ActivityName.this, "http://www.3pi.tf/test.xml");
Then in GetXmlTask
ReturnData mCallback;
public GetXmlTask(Context context, String url) { // Constructor in asynctask
this.url = url;
mCallback = (ReturnData)context;
}
Then
public interface ReturnData
{
public void Returnxml(String xml);
}
In doInbackground you return THEXML
return THEXML;
In onPostExecute
#Override
public void onPostExecute(String result)
{
super.onPostExecute(result);
if(mCallback!=null)
{
mCallback.Returnxml(result);
}
}
In MainActivity implement the interface
public class MainActivity extends Activity implements ReturnData {
Then
public void Retunxml(String data)
{
textView1.setText(data);
}
You should overwrite the onPostExecute method of AsynckTask and handle there the operation over your downloaded file if it is different from null. In you case something like this:
protected void onPostExecute(Void result) {
if(THEXML !=null)
{
//do something
}
}
I want to read XML data from URL and have tried in different ways. But unable to find the answer. Iam developing a agumented reality application, where iam reading location information from XML ( which is in URL )
Iam new bee to android as well
I have the following XML data.
<specialoffers>
<categories>
<category>
<![CDATA[ 0% Installment Payment Plan Offers ]]>
</category>
<merchants>
<merchantname>
<![CDATA[ EmaxIPP ]]>
</merchantname>
<merchantbigimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20190x73-1_tcm20-48180.jpg
]]>
</merchantbigimage>
<merchantsmallimage>
<![CDATA[
http://www.XXX.com/Images/Emax%20New%20-%20104x75-1_tcm20-48179.jpg
]]>
</merchantsmallimage>
<merchantmobileimage>
<![CDATA[ http://www.XXX.com ]]>
</merchantmobileimage>
<mobilehighlight>
<![CDATA[
Enjoy 0% Installment Payment Plan for 3 months on
all purchases made </b>
]]>
</mobilehighlight>
<highlight>
<![CDATA[
Enjoy 0% Installment Payment Plan for 3 months on all purchases
made with your </b>
]]>
</highlight>
<locations>
<location>
<emirate>
<![CDATA[ XXX]]>
</emirate>
<address>
<![CDATA[ Center 1 ]]>
</address>
<latitude>
<![CDATA[ 51.169601 ]]>
</latitude>
<longitude>
<![CDATA[ 61.240395 ]]>
</longitude>
</location>
</merchants>
</categories>
</specialoffers>
Here is the code....
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.adcb.com/specialoffers-test.xml";
// XML node keys
static final String KEY_ITEM = "categories"; // parent node
static final String KEY_ID = "category";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems =
new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_ID, "KEY_DESC", "100" }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView)
view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView)
view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView)
view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(KEY_ID, name);
in.putExtra("100", cost);
in.putExtra("KEY_DESC", description);
startActivity(in);
}
});
}
}
XMLParser.java
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child =
child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
SingleMenuItemActivity.java
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_ID = "category";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_ID);
String cost = in.getStringExtra(KEY_COST);
String description = in.getStringExtra(KEY_DESC);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.cost_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
You can use xmlpullparser like this :
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
I found a link demonstrating the same example as per your need.Please go through this link
Or just go the android way . A developer guide link
Hope it helps you.
Use SimpleXml xml parsing API for android it'll make your coding easy.
I'm trying to get XML datas from web and to show these datas into ListView. But something's going wrong when i run the project. Can you help me for this problem,please? Thank you.
XMLParser.java
public class XMLParser extends Activity {
public String getXmlFromUrl(String url) {
String xml = null;
try {
new Thread(new Runnable() {
public void run() {
try {
URL uri=new URL("http://api.androidhive.info/pizza/?format=xml");
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
System.out.println("done");
}
catch(Exception e) {
e.printStackTrace();
}
}
}).start();
//readfilethread.start();
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
System.out.println("here");
// HttpResponse httpResponse = httpClient.execute(httpPost);
//HttpEntity httpEntity = httpResponse.getEntity();
//xml = EntityUtils.toString(httpEntity);
} catch (Exception e) {
e.printStackTrace();
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables..
static final String URL = "http://api.androidhive.info/pizza/?format=xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// -> menuItems
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// 2. Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.description, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
android.widget.ListView lv = getListView();
// listening to single list item click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.description)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleListItem.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
'
LOGCAT PART
08-25 08:34:10.211: E/AndroidRuntime(1700): FATAL EXCEPTION: main
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uygulama/com.example.uygulama.AndroidXMLParsingActivity}: java.lang.NullPointerException
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Handler.dispatchMessage(Handler.java:99)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.os.Looper.loop(Looper.java:137)
08-25 08:34:10.211: E/AndroidRuntime(1700): at android.app.ActivityThread.main(ActivityThread.java:5039)
....
08-25 08:34:10.341: I/System.out(1700): done
Try this codes ...
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class NetActivity extends Activity {
String url = "http://api.androidhive.info/pizza/?format=xml";
// Progress dialog
ProgressDialog pDialog;
ArrayList<String> title;
ArrayList<String> description;
ArrayList<String> id;
ArrayList<String> cost;
ItemAdapter adapter1;
ListView list;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_net);
list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
id = new ArrayList<String>();
cost = new ArrayList<String>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(url).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new XmlParsing(url).execute(new String[]{null});
}
#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;
}
public class XmlParsing extends AsyncTask<String, Void, String> {
// variables passed in:
String urls;
// constructor
public XmlParsing(String urls) {
this.urls = urls;
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(NetActivity.this, "Fetching Details..", "Please wait...", true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
URL url;
try {
url = new URL(urls);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(""+ ((Node) nameList.item(0)).getNodeValue());
System.out.println("name : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("id");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
description.add(""+ ((Node) nameList1.item(0)).getNodeValue());
System.out.println("id : "+ ((Node) nameList1.item(0)).getNodeValue());
Element fstElmnt2 = (Element) node;
NodeList nameList2 = fstElmnt2.getElementsByTagName("cost");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
id.add(""+ ((Node) nameList2.item(0)).getNodeValue());
System.out.println("cost : "+ ((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) node;
NodeList nameList3 = fstElmnt3.getElementsByTagName("description");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
cost.add(""+ ((Node) nameList3.item(0)).getNodeValue());
System.out.println("description : "+ ((Node) nameList3.item(0)).getNodeValue());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// Now we have your JSONObject, play around with it.
if (pDialog.isShowing())
pDialog.dismiss();
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
public TextView id_text;
public TextView cost_text;
}
public ItemAdapter(XmlParsing xmlParsing) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//#Override
public int getCount() {
return title.size();
}
//#Override
public Object getItem(int position) {
return position;
}
//#Override
public long getItemId(int position) {
return position;
}
//#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
holder.id_text = (TextView) view.findViewById(R.id.id_text);
holder.cost_text = (TextView) view.findViewById(R.id.cost_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+description.get(position));
holder.id_text.setText(""+id.get(position));
holder.cost_text.setText(""+cost.get(position));
return view;
}
}
}
I'm trying to parse xml data from this URL:http://cloud.tfl.gov.uk/TrackerNet/LineStatus but am getting a NullPointerException on the line that read:
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
Before I show the code, I'd just like to say whats going on. First I download the XML file to the SDCard in
saveToSdCard();
Then I retrieve it with
getDataFromSDcard();
Here is my code:
Main Activity:
public class DashboardFragment extends SherlockFragment {
private CardUI mCardView;
String TUBE_STATUS_URL;
String KEY_ITEM = "LineStatus";
String KEY_LINE = "Line";
String KEY_NAME = "name";
String KEY_STATUS_DETAILS = "StatusDetails";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.activity_dashboard,
container, false);
// Get the URL's
TUBE_STATUS_URL = "http://cloud.tfl.gov.uk/TrackerNet/LineStatus";
// Find the cards in inflated layout
CardUI cardGroup = (CardUI) rootView.findViewById(R.id.cardsview);
fillCards(cardGroup);
DownloadFeedsTask task = new DownloadFeedsTask();
task.execute(new String[] { "" });
return rootView;
}
private void fillCards(CardUI cardGroup) {
// Fill cards with data
// init CardView
mCardView = cardGroup;
mCardView.setSwipeable(true);
// create a stack
CardStack delayStack = new CardStack();
delayStack.setTitle("Tube Lines with delays");
// add cards to stack
delayStack.add(new MyCard("Jubilee Line", MyCard.LINE_UNAVAILABLE));
delayStack.add(new MyCard("Victoria Line", MyCard.LINE_AVAILABLE));
delayStack
.add(new MyCard("Piccadilly Line", MyCard.LINE_IN_MAINTENANCE));
delayStack.add(new MyCard("Northern", MyCard.LINE_AVAILABLE));
// create a stack
CardStack activeStack = new CardStack();
activeStack.setTitle("Active Tube Lines");
// add cards to stack
activeStack.add(new MyCard("Jubilee Line", MyCard.LINE_HIDE_STATUS));
activeStack.add(new MyCard("Victoria Line", MyCard.LINE_HIDE_STATUS));
// add stack to cardView
mCardView.addStack(delayStack);
mCardView.addStack(activeStack);
// draw cards
mCardView.refresh();
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
return super.onOptionsItemSelected(item);
}
private class DownloadFeedsTask extends AsyncTask<String, Void, String> {
ArrayList<HashMap<String, String>> menuItems;
#Override
protected String doInBackground(String... urls) {
try {
saveToSdCard();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String response = "";
XMLParser parser = new XMLParser();
String xml = getDataFromSDcard(); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, e.getAttribute(KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
// adapter = new SimpleAdapter(
// mCtx,
// menuItems,
// R.layout.list_item,
// new String[] { KEY_ADVERT, KEY_CONTACT, KEY_DATE },
// new int[] { R.id.textView1, R.id.textView2, R.id.textView3 });
return response;
}
private String getDataFromSDcard() {
// Get data from SDCard
// Find the directory for the SD Card using the API
// *Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
// Get the text file
File file = new File(sdcard, "Folder/test.xml");
// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
// You'll need to add proper error handling here
}
return text.toString();
}
private void saveToSdCard() throws IOException {
try {
URL url = new URL(TUBE_STATUS_URL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(
Environment.getExternalStorageDirectory() + "/Folder");
if (!testDirectory.exists()) {
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory
+ "/test.xml");
byte data[] = new byte[1024];
int count = 0;
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1) {
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp;
}
fos.write(data, 0, count);
}
is.close();
fos.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
// Toast.makeText(getActivity(), String.valueOf(menuItems.size()),
// Toast.LENGTH_LONG).show();
// Log.d("Commuter+", String.valueOf(menuItems.size()));
}
}
}
And my XMLParser class:
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
Log.d("Commuter+", String.valueOf(doc.toString().length()));
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
}
I tried fixing this by testing my code with other URLs that had XML data and it worked, but there seems to be a problem when I use this URL.
public class XMLParser {
// constructor
public XMLParser() {
}
public String getXmlFromUrl(String url) {
String responseBody = null;
getset d1 = new getset();
String d = d1.getData(); // text
String y = d1.getYear(); // year
String c = d1.getCircular();
String p = d1.getPage();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("YearID", y));
nameValuePairs.add(new BasicNameValuePair("CircularNo", c));
nameValuePairs.add(new BasicNameValuePair("SearchText", d));
nameValuePairs.add(new BasicNameValuePair("pagenumber", p));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
responseBody = EntityUtils.toString(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return responseBody;
}
public Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
// i m getting Exception here
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/**
* Getting node value
*
* #param elem
* element
*/
public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
*
* #param Element
* node
* #param key
* string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
I am getting Exception in this class for parsing data. I want print this message in another class which extends from Activity. Can you please tell me how? I tried much but not able to do..
public class AndroidXMLParsingActivity extends Activity {
public int currentPage = 1;
public ListView lisView1;
static final String KEY_ITEM = "docdetails";
static final String KEY_NAME = "heading";
public Button btnNext;
public Button btnPre;
public static String url = "http://dev.taxmann.com/TaxmannService/TaxmannService.asmx/GetNotificationList";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// listView1
lisView1 = (ListView) findViewById(R.id.listView1);
// Next
btnNext = (Button) findViewById(R.id.btnNext);
// Perform action on click
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage + 1;
ShowData();
}
});
// Previous
btnPre = (Button) findViewById(R.id.btnPre);
// Perform action on click
btnPre.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
currentPage = currentPage - 1;
ShowData();
}
});
ShowData();
}
public void ShowData() {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
int displayPerPage = 5; // Per Page
int TotalRows = nl.getLength();
int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);
int TotalPage = 0;
if (TotalRows <= displayPerPage) {
TotalPage = 1;
} else if ((TotalRows % displayPerPage) == 0) {
TotalPage = (TotalRows / displayPerPage);
} else {
TotalPage = (TotalRows / displayPerPage) + 1; // 7
TotalPage = (int) TotalPage; // 7
}
int indexRowEnd = displayPerPage * currentPage; // 5
if (indexRowEnd > TotalRows) {
indexRowEnd = TotalRows;
}
// Disabled Button Next
if (currentPage >= TotalPage) {
btnNext.setEnabled(false);
} else {
btnNext.setEnabled(true);
}
// Disabled Button Previos
if (currentPage <= 1) {
btnPre.setEnabled(false);
} else {
btnPre.setEnabled(true);
}
// Load Data from Index
int RowID = 1;
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
// RowID
if (currentPage > 1) {
RowID = (displayPerPage * (currentPage - 1)) + 1;
}
for (int i = indexRowStart; i < indexRowEnd; i++) {
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map = new HashMap<String, String>();
map.put("RowID", String.valueOf(RowID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
RowID = RowID + 1;
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(AndroidXMLParsingActivity.this, menuItems,
R.layout.list_item, new String[] { "RowID", KEY_NAME },
new int[] { R.id.ColRowID, R.id.ColName });
lisView1.setAdapter(sAdap);
}
}
This my class where I want to Print that message
You can simply surround your code with a Try/Catch block like this:
String xml;
Document doc;
NodeList nl;
try {
xml = parser.getXmlFromUrl(url); // getting XML
doc = parser.getDomElement(xml); // getting DOM element
nl = doc.getElementsByTagName(KEY_ITEM);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
This way you don't have to make any changes in your XMLParser class and you can easily handle any exceptions occurring while parsing your code in the main class itself. Also, for displaying error messages, Toast is the best thing according to me.
Hope this helps.. Thanks.
I would say, add throws SAXException in XMLParser.getDomElement() method and don't catch SAXException in this method as:
public Document getDomElement(String xml) throws SAXException {
Catch the SAXException in AndroidXMLParsingActivity.ShowData() where you are calling getDomElement() method and print the message in the desired way e.g.
public void ShowData() {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = null;
try{
doc = parser.getDomElement(xml); // getting DOM element
}catch(SAXException sae){
//print the desired message here
}
.......
.......
}
For showing Message from Non Activity Class you will need to pass Current Activity Context as:
public class XMLParser {
Context context
// constructor
public XMLParser(Context conts) {
context =conts;
}
///YOUR CODE
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(context, e.toString(), Toast.Long).show();
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(context, e.toString(), Toast.Long).show();
// i m getting Exception here
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(context, e.toString(), Toast.Long).show();
return null;
}
Simply pass the constructor to your XMLParser class and used that there as your constructor. Or, you can try with use of getApplicationContext() You can simply show the Toast when you getting an exception like below -
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception
// i m getting Exception here
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
Toast.makeToast(con, e.toString(), Toast.Long).show(); // Will show the message of exception
return null;
}
Update
Okay, just pass the constructor as per below - Where you are calling that XMLparser class just call like below -
....
XMLParser xml = new XMLParser(AndroidXMLParsingActivity.this);
....
And, in XMLParser class there mention your constructor like below -
public class XMLParser {
Context con;
public XMLParser(Context context) {
con = context;
}
......
}
And, use this con as your constructor in your XMLParser class.