i have an xml file located at
http://androtrends.hostingsiteforfree.com/direct.xml
i am trying to parse this xml file to use it in my program but every time the program force closes although it has no errors.i am new to java, please help!
Following is the code which i have used in XMLParser.java
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;
}
//Parsing XML content and getting DOM element
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;
}
//Getting each xml child element value by passing element node name
public String getValue(Element item, String str) {
NodeList n = ((Document) 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 "";
}
}
The code for Channel.java is
public class Channel extends ListActivity{
String selectedmode, channelName, channelLink;
Intent urlIntent;
// All static variables
static final String DirectURL = "http://androtrends.hostingsiteforfree.com/direct.xml";
static final String FlashURL="http://androtrends.hostingsiteforfree.com/direct.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_Channel = "channel";
static final String KEY_Link = "link";
String xml;
Toast toast;
ArrayList<HashMap<String, String>> menuItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.channels);
selectedmode=getIntent().getExtras().getString("key");
urlIntent=new Intent(Intent.ACTION_VIEW);
Toast.makeText(this, "Wait 60 secs to load the stream...", Toast.LENGTH_LONG).show();
updatechannels();
ListView lv=getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
channelName= ((TextView) view.findViewById(R.id.channelName)).getText().toString();
channelLink= ((TextView) view.findViewById(R.id.channelLink)).getText().toString();
urlIntent.setData(Uri.parse(channelLink));
toast.show();
startActivity(urlIntent);
}
});
}
private void updatechannels() {
// TODO Auto-generated method stub
menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
if (selectedmode.equalsIgnoreCase("direct"))
{
xml = parser.getXmlFromUrl(DirectURL); // getting XML
}else
{
xml = parser.getXmlFromUrl(FlashURL);
}
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_Channel, parser.getValue(e, KEY_Channel));
map.put(KEY_Link, parser.getValue(e, KEY_Link));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_Channel, KEY_Link }, new int[] {
R.id.channelName, R.id.channelLink });
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Try this..
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://androtrends.hostingsiteforfree.com/direct.xml";
// Progress dialog
ProgressDialog pDialog;
ArrayList<String> title;
ArrayList<String> description;
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>();
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("channel");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(""+ ((Node) nameList.item(0)).getNodeValue());
System.out.println("channel : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("link");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
description.add(""+ ((Node) nameList1.item(0)).getNodeValue());
System.out.println("link : "+ ((Node) nameList1.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();
String value = result;
// Log.v("URL Res- - - -", ""+value);
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 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);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+description.get(position));
return view;
}
}
}
Related
I'm following this tutorial at Techiedreams.com. I want to change the URL of the RSS to my own at http://feeds.feedburner.com/TwitterRssFeedXML. Here are my codes:
SplashActivity.Java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SplashActivty extends Activity {
String RSSFEEDURL = "http://feeds.feedburner.com/androidcentral?format=xml";
//wanted http://feeds.feedburner.com/TwitterRssFeedXML instead
RSSFeed feed;
String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
fileName = "TDRSSFeed.td";
File feedFile = getBaseContext().getFileStreamPath(fileName);
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
// No connectivity. Check if feed File exists
if (!feedFile.exists()) {
// No connectivity & Feed file doesn't exist: Show alert to exit
// & check for connectivity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// No connectivty and file exists: Read feed from the File
Toast toast = Toast.makeText(this,
"No connectivity! Reading last update...",
Toast.LENGTH_LONG);
toast.show();
feed = ReadFeed(fileName);
startLisActivity(feed);
}
} else {
// Connected - Start parsing
new AsyncLoadXMLFeed().execute();
}
}
private void startLisActivity(RSSFeed feed) {
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivty.this, List_Activity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
feed = myParser.parseXml(RSSFEEDURL);
if (feed != null && feed.getItemCount() > 0)
WriteFeed(feed);
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
startLisActivity(feed);
}
}
// Method to write the feed to the File
private void WriteFeed(RSSFeed data) {
FileOutputStream fOut = null;
ObjectOutputStream osw = null;
try {
fOut = openFileOutput(fileName, MODE_PRIVATE);
osw = new ObjectOutputStream(fOut);
osw.writeObject(data);
osw.flush();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method to read the feed from the File
private RSSFeed ReadFeed(String fName) {
FileInputStream fIn = null;
ObjectInputStream isr = null;
RSSFeed _feed = null;
File feedFile = getBaseContext().getFileStreamPath(fileName);
if (!feedFile.exists())
return null;
try {
fIn = openFileInput(fName);
isr = new ObjectInputStream(fIn);
_feed = (RSSFeed) isr.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return _feed;
}
}
RSSItem.Java:
package com.example.samsung.feedrss;
import java.io.Serializable;
public class RSSItem implements Serializable {
private static final long serialVersionUID = 1L;
private String _title = null;
private String _description = null;
private String _date = null;
private String _image = null;
void setTitle(String title) {
_title = title;
}
void setDescription(String description) {
_description = description;
}
void setDate(String pubdate) {
_date = pubdate;
}
void setImage(String image) {
_image = image;
}
public String getTitle() {
return _title;
}
public String getDescription() {
return _description;
}
public String getDate() {
return _date;
}
public String getImage() {
return _image;
}
}
DOMparser:
public class DOMParser {
private RSSFeed _feed = new RSSFeed();
public RSSFeed parseXml(String xml) {
// _feed.clearList();
URL url = null;
try {
url = new URL(xml);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
// Create required instances
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
String nodeName = thisNode.getNodeName();
theString = nchild.item(j).getFirstChild().getNodeValue();
if (theString != null) {
if ("title".equals(nodeName)) {
// Node name is equals to 'title' so set the Node
// value to the Title in the RSSItem.
_item.setTitle(theString);
}
else if ("description".equals(nodeName)) {
_item.setDescription(theString);
// Parse the html description to get the image url
String html = theString;
org.jsoup.nodes.Document docHtml = Jsoup
.parse(html);
Elements imgEle = docHtml.select("img");
_item.setImage(imgEle.attr("src"));
}
else if ("pubDate".equals(nodeName)) {
// We replace the plus and zero's in the date with
// empty string
String formatedDate = theString.replace(" +0000",
"");
_item.setDate(formatedDate);
}
}
}
// add item to the list
_feed.addItem(_item);
}
} catch (Exception e) {
e.printStackTrace();
}
// Return the final feed once all the Items are added to the RSSFeed
// Object(_feed).
return _feed;
}
}
The problem is that my personal URL doesn't work but the original does. Could anyone please solve this issue?
Okay, after some time of work, I've found a solution to this. Just tweak some settings in feedburner.com, make sure to activate SmartFeed under Optimize and you're good to go. Make sure to check any other settings too if SmartFeed alone doesn't work.
I try to get currency from this url http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml. But my parsing doesn't work. This is my code.
http://www.ecb.europa.eu/stats/exchange/eurofxref/html/index.en.html
AndroidXMLParsingActivit.java
package com.androidhive.xmlparsing;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://api.androidhive.info/pizza/?format=xml";
static final String URL = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
// XML node keys
//static final String KEY_ITEM = "item"; // parent node
static final String KEY_ITEM = "Cube"; // parent node
static final String KEY_ID = "currency";
static final String KEY_NAME = "rate";
/*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);
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));
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);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
//new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
new String[] { KEY_NAME, KEY_ID, KEY_ID }, 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, cost);
in.putExtra(KEY_NAME, name);
//in.putExtra(KEY_COST, cost);
//in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
SingleMenuItemActivity.java
package com.androidhive.xmlparsing;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_ID = "currency";
static final String KEY_NAME = "rate";
/*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);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_NAME);
String cost = 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(cost);
Log.i("name", name+"");
Log.i("cost", cost+"");
}
}
XMLParser.java
package com.androidhive.xmlparsing;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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.util.Log;
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));
}
}
Original post from here.
File fXmlFile = new File("your XML file");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Cube");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String currency = eElement.getAttribute("currency");
String rate = eElement.getAttribute("rate");
if(currency.isEmpty()){
continue;
}
System.out.println("Ccurrency :" + currency);
System.out.println("Rate : " + rate);
}
}
It's printing the currency and the Rate.
Just replace
File fXmlFile = new File("your XML file");
on
URL url = null;
try {
url = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
URLConnection conn = null;
try {
conn = url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
And code must run in AsyncTask. I will send full source code through few days.
My last question was badly phrased - I am attempting to parse the following xml:
I am having issues parsing the elements inside congestion location:
<tns:camera>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Eastbound</tns:direction>
<tns:order>6</tns:order>
</tns:congestionLocations>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Westbound</tns:direction>
<tns:order>2</tns:order>
</tns:congestionLocations>
<tns:id>130</tns:id>
<tns:offline>false</tns:offline>
<tns:underMaintenance>false</tns:underMaintenance>
</tns:camera>
Using XMLPullParser, I can read the id, offline, etc elements. This works fine. I've written my code to parse the XML below:
// Get our factory and PullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
// Open up InputStream and Reader of our file.
FileInputStream fis = ctx.openFileInput("CameraSites.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
// point the parser to our file.
xpp.setInput(reader);
// get initial eventType
int eventType = xpp.getEventType();
// Loop through pull events until we reach END_DOCUMENT
while (eventType != XmlPullParser.END_DOCUMENT) {
// Get the current tag
String tagname = xpp.getName();
// React to different event types appropriately
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// If we are starting a new <site> block we need
//a new CameraClass object to represent it
curCameraClass = new CameraClass();
}
break;
case XmlPullParser.TEXT:
//grab the current text so we can use it in END_TAG event
curText = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// if </site> then we are done with current Site
// add it to the list.
CameraSites.add(curCameraClass);
} else if (tagname.equalsIgnoreCase(KEY_ID)) {
curCameraClass.setID(curText);
} else if (tagname.equalsIgnoreCase(KEY_MAIN)) {
curCameraClass.setMAIN(curText);
}
break;
default:
break;
}
//move on to next iteration
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
// return the populated list.
return CameraSites;
}
My question is, how would I parse the congestion and direction elements found in the congestion locations? I am parsing these into a get/set method with a class (CameraClass).
Thanks in advance!
Here is the code with your xml..
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
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.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.util.Log;
import android.view.Menu;
public class FileActivity extends Activity {
// Progress dialog
ProgressDialog pDialog;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
String data = "<tns:camera>"
+" <tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Eastbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Westbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:description>Bond St looking east</tns:description>"
+"<tns:direction>Eastbound</tns:direction>"
+"<tns:group>SH16-North-Western</tns:group>"
+"<tns:lat>-36.869</tns:lat>"
+"<tns:lon>174.746</tns:lon>"
+"<tns:name>SH16 1 Bond St</tns:name>"
+"<tns:viewUrl>http://www.trafficnz.info/camera/view/130</tns:viewUrl>"
+" </tns:camera>";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(data).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new XmlParsing(data).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 data;
// constructor
public XmlParsing(String data) {
this.data = data;
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(FileActivity.this, "Fetching Details..", "Please wait...", true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dbFactory.newDocumentBuilder();
FileOutputStream out = openFileOutput("hello.txt",Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
BufferedReader input = new BufferedReader(new InputStreamReader(openFileInput("hello.txt")));
StringBuffer inLine = new StringBuffer();
String text;
while ((text = input.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
input.close();
String finalData =inLine.toString();
InputStream is = new ByteArrayInputStream(finalData.getBytes("UTF-8"));
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("tns:camera");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tns:group");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Log.v("tns:group : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("tns:viewUrl");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
Log.v("tns:viewUrl : "+ ((Node) nameList1.item(0)).getNodeValue());
if(node.getNodeType() == Node.ELEMENT_NODE)
{
Element e = (Element) node;
NodeList resultNodeList = e.getElementsByTagName("tns:congestionLocations");
int resultNodeListSize = resultNodeList.getLength();
for(int j = 0 ; j < resultNodeListSize ; j++ )
{
Node resultNode = resultNodeList.item(j);
if(resultNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt2 = (Element) resultNode;
NodeList nameList2 = fstElmnt2.getElementsByTagName("tns:congestion");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
Log.v("tns:congestion", ""+((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) resultNode;
NodeList nameList3 = fstElmnt3.getElementsByTagName("tns:direction");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
Log.v("tns:direction--", ""+((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();
}
}
}
From log you can see the result...
I'm getting a NullPointerException at the line :
handler.getQueryResponse(stream);
I've looked over the source code quite a few times and I'm not sure exactly why this is occurring.
Any suggestions are greatly appreciated.
LOGCAT:
08-16 16:26:24.401: E/AndroidRuntime(9542): FATAL EXCEPTION: main
08-16 16:26:24.401: E/AndroidRuntime(9542): java.lang.NullPointerException
08-16 16:26:24.401: E/AndroidRuntime(9542): at com.project.new.datasettings.UpdateActivity.success(UpdateActivity.java:426)
08-16 16:26:24.401: E/AndroidRuntime(9542): at com.project.new.datasettings.UpdateActivity$NetworkTask.onPostExecute(UpdateActivity.java:389)
08-16 16:26:24.401: E/AndroidRuntime(9542): at com.project.new.datasettings.UpdateActivity$NetworkTask.onPostExecute(UpdateActivity.java:1)
SOURCE:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import javax.xml.parsers.ParserConfigurationException;
import com.project.new.datasettings.XmlParserHandlerFinal;
import org.xml.sax.SAXException;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ClipDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import com.project.new.datasettings.R;
public class UpdateActivity extends Activity implements OnClickListener {
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
public static int count;
AlertDialog mErrorAlert = null;
int version;
public static int TotalSteps = 8;
private TelephonyManager tm;
private static final String LOG_TAG = "STDataSettings";
private Button mUpdateButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
private int mInstructionNumber = 0;
AlertDialog mConfirmAlert = null;
public static InputStream stream = null;
public static XmlParserHandlerFinal handler;
private NetworkTask task;
private AnimationDrawable loadingAnimation;
private static final String TAG = "UpdateActivity";
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
int version = android.os.Build.VERSION.SDK_INT;
if (phoneType == TelephonyManager.PHONE_TYPE_CDMA
|| (phoneType != TelephonyManager.PHONE_TYPE_GSM
&& networkType != TelephonyManager.NETWORK_TYPE_GPRS
&& networkType != TelephonyManager.NETWORK_TYPE_EDGE
&& networkType != TelephonyManager.NETWORK_TYPE_HSDPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPAP
&& networkType != TelephonyManager.NETWORK_TYPE_HSUPA
&& networkType != TelephonyManager.NETWORK_TYPE_UMTS && networkType != TelephonyManager.NETWORK_TYPE_LTE)) {
// If the phone type is CDMA or
// the phone phone type is not GSM and the network type is none of
// the network types indicated in the statement
// Display incompatibility message
showAlert(getString(R.string.incomp_sm_dialog));
// Network type is looked because some tablets have no phone type.
// We rely on network type in such cases
} else if (!(tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo)) || (tm
.getSimOperator()).equals(getString(R.string.numeric_att)))) {
// if SIM is present and is NOT a T-Mo network SIM,
// display Error message alert indicating to use SM SIM
showAlert(getString(R.string.insert_sm_dialog));
}// No SIM or SIM with T-Mo MNC MCC present
else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Initial UI setup for versions lower than ICS
setContentView(R.layout.update);
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(this);
} else {// ICS and up
// task.execute();
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
task = new NetworkTask();
task.execute("");
// Device has T-Mo network SIM card MCC and MNC correctly
// populated
// Reduce number of steps to 6
TotalSteps = 6;
}
}
}
public void onClick(View v) {
if (v == mUpdateButton) {
// Update button for versions lower than ICS is selected
// setContentView(R.layout.updating);
onClickMethod(v);
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
} else if (v == mAssistUpdateButton) {
// Update button for ICS and up is selected
// Get the TextView in the Assist Update UI
TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
String text = "";
CharSequence styledText = text;
switch (mInstructionNumber) {
case 0:
// Retrieve the instruction string resource corresponding the
// 2nd set of instructions
text = String.format(getString(R.string.apn_app_text_instr),
TotalSteps);
styledText = Html.fromHtml(text);
// Update the TextView with the correct set of instructions
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 1:
text = getString(R.string.apn_app_text_instr2);
styledText = Html.fromHtml(text);
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 2:
// Final set of instructions-Change to the corresponding layout
setContentView(R.layout.assist_instructions);
String assistUpdateInstr = String.format(
getString(R.string.apn_app_text_instr3), TotalSteps);
styledText = Html.fromHtml(assistUpdateInstr);
TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
assistInstrText.setText(styledText);
mAssistInstrButton = (Button) findViewById(R.id.assist_instr_btn);
mReadAgainButton = (TextView) findViewById(R.id.read_again_btn);
mAssistInstrButton.setOnClickListener(this);
mReadAgainButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
// Create ConfigActivity Intent
Intent i = new Intent(this, ConfigFinalActivity.class);
// Invoke ConfigActivity Intent to start the assisted update
startActivity(i);
finish();
} else if (v == mReadAgainButton) {
// go back to 1st set of instructions if read again is selected
mInstructionNumber = 0;
setContentView(R.layout.assist_update);
String assistUpdate = getString(R.string.apn_app_text_cta2);
CharSequence styledText = Html.fromHtml(assistUpdate);
TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
assistText.setText(styledText);
mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
mAssistUpdateButton.setOnClickListener(this);
}
}
public void onClickMethod(View v) {
mUpdateButton = (Button) findViewById(R.drawable.btn_update_active_hdpi);
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UpdateActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
// AsyncTask to call web service
class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected InputStream doInBackground(String... params) {
try {
// saving the response in InputStream
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
// stream = new BufferedInputStream(https.getInputStream());
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) { // Print the content on the console
System.out.println (strLine);
System.out.println (strLine);
in.close();
}
} catch (IOException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SAXException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
}
// The code below plays a Simple Promo animation
for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show 1 dot
// And Increasing the level to reduce the amount of clipping and
// slowly reveals the hand image
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {
// HttpsURLConnection https = null;
HttpsURLConnection https = null;
String uri = urlQueryString;
URL urlo = new URL(uri);
try {
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(20000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();
} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} finally {
// https.disconnect();
}
return stream;
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2], progress[3], progress[4]);
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the ArrayLists
success();
}
}
private void setProgressImgView(Integer imageViewId1, Integer imageViewId2, Integer imageViewId3, Integer imageViewId4, Integer imageViewId5) {
// update image view with the updating dots
// Reset view layout in case orientation while updating
setContentView(R.layout.updating);
mProgressImageview1 = (ImageView) findViewById(R.id.loading_empty1);
mProgressImageview1.setBackgroundResource(imageViewId1);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview1.setBackgroundResource(imageViewId2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview1.setBackgroundResource(imageViewId3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview1.setBackgroundResource(imageViewId4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview1.setBackgroundResource(imageViewId5);
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(stream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// to set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
// method to save the ArrayLists from parser
public static void setArrayList() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getMmscProxyArr();
portArr = handler.getMmsPortArr();
count = handler.getCount();
//System.out.println("testing123");
for(int i = 0; i < nameArr.size()-1; i++){
System.out.println(nameArr.get(i));
}
for(int i = 0; i < ApnArr.size()-1; i++){
System.out.println(ApnArr.get(i));
}
}
}
XMLPARSERHANDLERFINAL:
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
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.ContentValues;
import android.content.Context;
import android.os.StrictMode;
import android.util.Log;
public class XmlParserHandlerFinal extends DefaultHandler {
public String queryResult;
private String name, Value;
public ArrayList<String> NameArr = new ArrayList<String>();
public ArrayList<String> ValueArr = new ArrayList<String>();
public ArrayList<String> nameArr = new ArrayList<String>();
public ArrayList<String> ApnArr = new ArrayList<String>();
public ArrayList<String> mmscArr = new ArrayList<String>();
public ArrayList<String> mmsportArr = new ArrayList<String>();
public ArrayList<String> mmsproxyArr = new ArrayList<String>();
public ArrayList<String> portArr = new ArrayList<String>();
public ArrayList<String> proxyArr = new ArrayList<String>();
public ArrayList<ContentValues> ArrValues = new ArrayList<ContentValues>();
public ContentValues values = new ContentValues();
public int count = 0;
Context c;
private boolean isPhoneSettings = false, isName = false, isValue = false;;
public XmlParserHandlerFinal() {
}
public void setContext(Context c) {
this.c = c;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes atts) {
if (qName.equalsIgnoreCase("Phonesettings")) {
isPhoneSettings = true;
}
if (qName.equals("name")) {
isName = true;
}
if (qName.equals("value")) {
isValue = true;
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (isPhoneSettings) {
isPhoneSettings = false;
}
if (isName) {
isName = false;
}
if (isValue) {
isValue = false;
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (isName) {
name = new String(ch, start, length);
NameArr.add(name);
}
if (isValue) {
Value = new String(ch, start, length);
ValueArr.add(Value);
values.put(name, Value);
if (name.equals("name")) {
nameArr.add(Value);
} else if (name.equals("apn")) {
ApnArr.add(Value);
} else if (name.equals("mmsc")) {
count++;
mmscArr.add(Value);
} else if (name.equals("mmsproxy")) {
mmsproxyArr.add(Value);
} else if (name.equals("mmsport")) {
mmsportArr.add(Value);
} else if (name.equals("port")) {
portArr.add(Value);
} else if (name.equals("proxy")) {
proxyArr.add(Value);
} else
if (name.equals("type")) {
// System.out.println("values in parser" + values);
ArrValues.add(values);
Log.v("value", Value);
System.out.println("size " + ArrValues.size());
// ((ConfigActivityForMultiProf) context)
// .InsertAPN();
// try {
// ((ConfigActivityForMultiProf) context)
// .showNotification(values);
// } catch (ParserConfigurationException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
/*
* for(int i =0;i<=NameArr.size()-1;i++){ NameArr.remove(i); }
* for(int i =0;i<=ValueArr.size()-1;i++){ ValueArr.remove(i); }
*/
}
}
}
public String getQueryResponse(InputStream in) throws SAXException,
IOException {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
SAXParserFactory spf = SAXParserFactory.newInstance();
Log.v("In the parser", "now");
SAXParser sp;
sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(this);
xr.parse(new InputSource(in));
} catch (ParserConfigurationException e) {
Log.e("", "XML Handler Exception: " + e.toString());
}
return queryResult;
}
public int getCount() {
return count;
}
public ArrayList<String> getNameArr() {
for (int i = 0; i <= NameArr.size() - 1; i++) {
System.out.println(NameArr.get(i));
}
return NameArr;
}
public ArrayList<String> getValueArr() {
for (int i = 0; i <= ValueArr.size() - 1; i++) {
System.out.println(ValueArr.get(i));
}
return ValueArr;
}
public ArrayList<String> getnameArr() {
for (int i = 0; i <= nameArr.size() - 1; i++) {
System.out.println(nameArr.get(i));
}
return nameArr;
}
public ArrayList<String> getApnArr() {
for (int i = 0; i <= ApnArr.size() - 1; i++) {
System.out.println(ApnArr.get(i));
}
return ApnArr;
}
public ArrayList<String> getMMSCArr() {
return mmscArr;
}
public ArrayList<String> getMmscProxyArr() {
return mmsproxyArr;
}
public ArrayList<String> getMmsPortArr() {
return mmsportArr;
}
public ArrayList<String> getProxyArr() {
return proxyArr;
}
public ArrayList<String> getPortArr() {
return portArr;
}
public ArrayList<ContentValues> getArrValuesArr() {
return ArrValues;
}
}
Your declaration of handler still needs to assign it a value before reference. Just because the declaration is static, does not mean that the variable is referencing anything.
Here is a simpler example of what you are trying to do:
public class MyClass {
public static Object o;
public static void main(String[] args) {
String s;
s = o.toString(); // this will throw an exception
}
}
You still need to initialize the data member. You can use a static initialization block as one method. Example:
public class MyClass {
public static Object o;
static {
o = new Object(); // initialize the data member here
}
public static void main(String[] args) {
String s;
s = o.toString(); // now pointing to a valid object
}
}
public class MainActivity extends Activity {
GridView gridView;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.grid_view);
adapter=new LazyAdapter(this, mStrings);
gridView.setAdapter(adapter);
Button b=(Button)findViewById(R.id.button2);
b.setOnClickListener(listener);
}
#Override
public void onDestroy()
{
adapter.imageLoader.stopThread();
gridView.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
private String[] mStrings={
"http://www.globaltvbc.com/uploadedImages/Global_News/Content/Wallpaper.jpeg",
"http://cdn.windows7themes.net/themes/halo-3-hd-wallpaper.jpg",
};
}
The question is i want to display the item on the gridview and display the item in full screen.I want to include any code to display the gridview item in full screen to be in the same class as MainActivity.I dont want my code to be in a new class.
if you want to load the full screen on the same activity then you should use popup window for displaying the image.
or the best solution is implement onItemClickListener on your main activity and on click get the item by position and pass the image url to next activityfor loading it there.
I am giving you my code edit this according to your need
|main Activity
package com.mypack;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.RelativeLayout;
public class GridViewActivity extends Activity implements OnItemClickListener {
List<RowItem4> rowItems;
private GridView gridView;
private Button galleryButton;
private Button shareButton;
private String[] mStringArray;
public static final Integer[] partyid = { 1, 2, 3, 4, 18, 19, 20 };
int i = 1;
private String xml;
String output = "";
/*private static final String NAMESPACE = "";
private static final String URL = "";
private static final String SOAP_ACTION = "";
private static final String METHOD_NAME = "";*/
private int pos;
private ProgressDialog progressDialog;
private int galleryId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_view);
Intent i = getIntent();
pos = i.getIntExtra("position", 0);
galleryId = i.getIntExtra("galleryId", 0);
progressDialog = ProgressDialog.show(GridViewActivity.this, "",
"Loading...");
Thread myThread = new Thread() {
private GridViewAdapter adapter;
public void run() {
getImages();
rowItems = new ArrayList<RowItem4>();
for (int i = 0; i < mStringArray.length; i++) {
RowItem4 item = new RowItem4(mStringArray[i]);
rowItems.add(item);
}
// LoadImageFromURL(""
// + output);
adapter = new GridViewAdapter(GridViewActivity.this, rowItems);
runOnUiThread(new Runnable() {
public void run() {
try {
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(GridViewActivity.this);
progressDialog.dismiss();
} catch (final Exception ex) {
Log.i("---", "Exception in thread");
}
}
});
}
};
myThread.start();
setUpView();
}
private void getImages() {
final String envelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+ "<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" "
+ "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
+ " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" "
+ "xmlns:tns=\"urn:registerwsdl\">" + "<SOAP-ENV:Body>"
+ "<tns:register " + "xmlns:tns=\"urn:registerwsdl\">"
+ "<galleryid xsi:type=\"xsd:integer\">" + galleryId
+ "</galleryid>" + "<partyid xsi:type=\"xsd:integer\">"
+ partyid[pos] + "</partyid>" + "</tns:register>" +
// "</SOAP-ENV:Body></SOAP-ENV:Envelope>",Name,Email,Password,Status,Type,Date];
"</SOAP-ENV:Body></SOAP-ENV:Envelope>";
System.out.println("------------" + envelope);
CallWebService(URL, SOAP_ACTION, envelope);
org.w3c.dom.Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
ArrayList<String> myList = new ArrayList<String>();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
NodeList nl1 = doc.getElementsByTagName("response");
for (int j = 0; j < nl1.getLength(); j++) {
NodeList nl = doc.getElementsByTagName("url");
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
myList.add(node.getFirstChild().getNodeValue());
}
}
mStringArray = new String[myList.size()];
mStringArray = myList.toArray(mStringArray);
for (int i = 0; i < mStringArray.length; i++) {
Log.d("string is", (mStringArray[i]));
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
String CallWebService(String url, String soapAction, String envelope) {
final DefaultHttpClient httpClient = new DefaultHttpClient();
// request parameters
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 20000);
HttpConnectionParams.setSoTimeout(params, 25000);
// set parameter
HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);
// POST the envelope
HttpPost httppost = new HttpPost(url);
// add headers
httppost.setHeader("soapaction", soapAction);
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
String responseString = "";
try {
// the entity holds the request
HttpEntity entity = new StringEntity(envelope);
httppost.setEntity(entity);
// Response handler
ResponseHandler<String> rh = new ResponseHandler<String>() {
// invoked when client receives response
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
// get response entity
HttpEntity entity = response.getEntity();
// read the response as byte array
StringBuffer out = new StringBuffer();
byte[] b = EntityUtils.toByteArray(entity);
// write the response byte array to a string buffer
out.append(new String(b, 0, b.length));
return out.toString();
}
};
responseString = httpClient.execute(httppost, rh);
} catch (Exception e) {
Log.v("exception", e.toString());
}
xml = responseString.toString();
// close the connection
System.out.println("xml file ------" + xml);
httpClient.getConnectionManager().shutdown();
return responseString;
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (i == 2) {
if (galleryButton.getVisibility() == View.VISIBLE) {
galleryButton.setVisibility(View.INVISIBLE);
shareButton.setVisibility(View.INVISIBLE);
} else {
galleryButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.VISIBLE);
}
i = 0;
}
i++;
super.dispatchTouchEvent(ev);
return false;
}
/*
* public OnTouchListener touch = new View.OnTouchListener() {
*
* public boolean onTouch(View v, MotionEvent event) {
* //System.out.println("onTouch =============-----------"); if
* (galleryButton.getVisibility() == v.VISIBLE) {
* galleryButton.setVisibility(v.INVISIBLE);
*
* shareButton.setVisibility(v.INVISIBLE);
*
* } else { galleryButton.setVisibility(v.VISIBLE);
*
* shareButton.setVisibility(v.VISIBLE);
*
* } return false; } };
*/
private void setUpView() {
gridView = (GridView) findViewById(R.id.gridView1);
galleryButton = (Button) findViewById(R.id.gallery_button);
shareButton = (Button) findViewById(R.id.share_button);
// relativeLayout1.setOnTouchListener(touch);
}
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
Intent i = new Intent(getApplicationContext(), ShowImageActivity.class);
i.putExtra("image", mStringArray[position]);
i.putExtra("galleryId", galleryId);
startActivity(i);
}
}
RowItem4 Object Class
package com.mypack;
public class RowItem4 {
private String imageId;
public String getImageId() {
return imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public RowItem4(String mStringArray) {
this.imageId = mStringArray;
}
}
GridViewAdapter extending BaseAdapter
package com.mypack;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class GridViewAdapter extends BaseAdapter {
Context context;
List<RowItem4> rowItems;
private ViewHolder holder;
private Drawable d;
public GridViewAdapter(Context context, List<RowItem4> rowItems) {
super();
this.context = context;
this.rowItems = rowItems;
}
private class ViewHolder {
ImageView imageView;
public int position;
}
public int getCount() {
// TODO Auto-generated method stub
return rowItems.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return rowItems.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return rowItems.indexOf(getItem(position));
}
public View getView(int position, View convertView, ViewGroup parent) {
holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_image_view, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem4 rowItem = (RowItem4) getItem(position);
holder.position = position;
GetXMLTask task = new GetXMLTask(position,holder);
task.execute(new String[] { ""+rowItem.getImageId() });
//holder.imageView.setImageDrawable(d);
return convertView;
}
/*private Drawable LoadImageFromURL(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
d = Drawable.createFromStream(is, "src");
return d;
}catch (Exception e) {
System.out.println(e);
return null;
}
}*/
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
private int mPosition;
private ViewHolder mHolder;
public GetXMLTask(int position, ViewHolder holder) {
mPosition = position;
mHolder = holder;
}
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
protected void onPostExecute(Bitmap result) {
if (mHolder.position == mPosition)
{
mHolder.imageView.setImageBitmap(result);
}
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
This code is if you want to load the image on second activity,and if you want to load image on the same activity just add the code for adding popup window in the main activity. I think now it is clear