Android asynctask exception - android

i'm doing an app that have to get an XML file from an url and parse it. I always find this log cat (PS:i can't find the correct google prettify sintax code highlighting):
11-06 23:12:44.940: E/Trace(8751): error opening trace file: No such file or directory(2)
11-06 23:12:51.345: E/Error:(8751): expected: /hr read: body (position:END_TAG </body>#6:8 in java.io.StringReader#431887b8)
11-06 23:12:51.360: E/AndroidRuntime(8751): FATAL EXCEPTION: AsyncTask #1
11-06 23:12:51.360: E/AndroidRuntime(8751): java.lang.RuntimeException: An error occured while executing doInBackground()
11-06 23:12:51.360: E/AndroidRuntime(8751): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-06 23:12:51.360: E/AndroidRuntime(8751): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.lang.Thread.run(Thread.java:856)
11-06 23:12:51.360: E/AndroidRuntime(8751): Caused by: java.lang.NullPointerException
11-06 23:12:51.360: E/AndroidRuntime(8751): at com.ambro.app.Update$connection.doInBackground(Update.java:39)
11-06 23:12:51.360: E/AndroidRuntime(8751): at com.ambro.app.Update$connection.doInBackground(Update.java:1)
11-06 23:12:51.360: E/AndroidRuntime(8751): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-06 23:12:51.360: E/AndroidRuntime(8751): ... 5 more
the xml could be found at: http://www.lookedpath.tk/apps/firstapp/version.xml
the update.java code:
public class Update extends Activity {
private TextView testo2;
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.update);
super.onCreate(savedInstanceState);
testo2= (TextView) findViewById(R.id.textView2);
}
public void goToUpdate (View view) {
System.out.println("ciao");
new connection().execute();
}
public class connection extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
boolean updated=false;
String lastversion=null;
Element e=null;
final String URL = "http://www.lookedpath.tk/apps/firstapp/version.xml";
final String VERSION = "version";
final String APPLICATION = "application";
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(APPLICATION);
for (int i=0;i<nl.getLength();i++) {
e = (Element) nl.item(0);
lastversion = parser.getValue(e, VERSION); // name child value
}
String actver = getString(R.string.version);
if(actver==lastversion) updated=true;
return updated;
}
protected void onPostExecute(Boolean... result) {
if(result[0]==false){
testo2.setText(R.string.newversion);
} else {
testo2.setText(R.string.nonewversion);
}
}
};
}
so this is the xmlparser.java file:
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;
}
// 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 "";
}
}
the logcat say that the error is in the line 39 of the update class:
NodeList nl = doc.getElementsByTagName(APPLICATION);
but i can't manage to resolve the problem. can anyone help me?
UPDATE:
i have fixed the error 405 but i still have a null pointer exception. i found that the program run correctly but never enter in the post execute method because of this exception..

I have tried your code there is not any problem, it is fine. Problem is in the link.
In browser it looks like this
<?xml version="1.0" encoding="UTF-8"?>
<menu>
<application>
<version>1.5</version>
</application>
</menu>
But when i print xml variable it give me
<html>
<head><title>405 Not Allowed</title></head>
<body bgcolor="white">
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx</center>
</body>
</html>
and then in dom variable you got null and when you try to find element in nl variable which is null you got error..,.
I tried your code with some other xml feed it works great..,.

Hey have a look on my Library.
You can easily manipulate XML with it ;)

From the logs, I can see you have a NullPointer in Update.java, line 39. You can start from there. I believe it's not related to AsyncTask.

You can check this link for xml parsing from xml.
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
In your activity you are developing the AsyncTask but you forgot to override onPreExecute method. See this example for how to develop AsyncTask in your activity.
package com.androidhive.jsonparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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 AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetEventsTask().execute("");
}
protected class GetEventsTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
protected ArrayList<HashMap<String, String>> contactList;
private final ProgressDialog dialog = new ProgressDialog(
AndroidJSONParsingActivity.this);
//PreExecute Method
protected void onPreExecute() {
this.dialog.setMessage("Loading, Please Wait..");
this.dialog.setCancelable(false);
this.dialog.show();
}
//doInBackground Method
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
contactList = new ArrayList<HashMap<String, String>>();
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.i("json objects",""+json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
try {
// Getting Array of Contacts
contacts = jObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return contactList;
}
//onPostExecute Method
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
contactList, R.layout.list_item, new String[] { TAG_NAME,
TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
// selecting single ListView item
ListView lv = getListView();
lv.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
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.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
}

you get just null xml at that position so debuge your application first check any xml responce u get or not????
if u get null xml then use following code for parse xml
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHandler extends DefaultHandler {
String elementValue = null;
Boolean elementOn = false;
userdata d = userdata.getInstance();
public static XMLGettersSetters data = null;
public static XMLGettersSetters getXMLData() {
return data;
}
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
/**
* This will be called when the tags of the XML starts.
**/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
if (localName.equals("application"))
{
data = new XMLGettersSetters();
}
}
/**
* This will be called when the tags of the XML end.
**/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("version")){
System.out.println("ststus" + elementValue);
d.setIsregi(elementValue);
}
/**
* This is called to get the tags value
**/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}

You have to add the correct DTD to your xml (Document Type Definition) , try it and you will see that the parsing will run smooth .
Step 1 : Generate correcte DTD
Step 2 : Add it to your xml file and save it
Step 3 : upload your xml file , parse it and enjoy .

Related

JSON Parsed Data not showing in ListFragment

I have used a MYSQL Database and connected it to my Android App using PHP. I added a sample row in the table and the PHP Script is returning JSON. I have tried my best in parsing the JSON and displaying it in a list. But it does not seem to be working. Able to run the App - But does not display content - Only shows the Dialog. It seems to work in Case of an Activity - What changes should be made to make it work for a Fragment. Here is my LogCat when I open up the fragment - http://prntscr.com/3f6k0a .
package com.example.socbeta;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class events extends ListFragment {
private ProgressDialog pDialog;
private static final String READ_EVENTS_URL ="http://socapptest.comoj.com/socbeta/events.php";
//JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_EventName = "EventName";
private static final String TAG_POSTS = "posts";
private static final String TAG_ID = "ID";
private static final String TAG_DATE = "Date";
private static final String TAG_MESSAGE = "message";
private JSONArray mEvents = null;
private ArrayList<HashMap<String, String>> mEventList;
public events(){}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.events, container, false);
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadEvents().execute();
}
public void updateJSONdata() {
mEventList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_EVENTS_URL);
try {
mEvents = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mEvents.length(); i++) {
JSONObject c = mEvents.getJSONObject(i);
String EventName = c.getString(TAG_EventName);
String content = c.getString(TAG_MESSAGE);
String Date = c.getString(TAG_DATE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EventName, EventName);
map.put(TAG_MESSAGE, content);
map.put(TAG_DATE, Date);
mEventList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(getActivity(), mEventList,
R.layout.list_item,
new String[] { TAG_EventName, TAG_MESSAGE,TAG_DATE },
new int[] { R.id.eventname, R.id.message,R.id.date });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
});
}
public class LoadEvents extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Events...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
EDIT :
Got my code to work. The Problem was with the JSON Structure. I did not Navigate properly and this gave me a "No Value for message" Error. For others who might be having same issues - Remember that when you have { in your JSON , you use JSONArray and when you have [ you use JSONObject. You need to navigate module wise through your JSON.
try this code
pass json string to this method . it will work
public JSONObject getJSONfromURL(String url)
{
InputStream is = null;
JSONObject jObj = null;
String json = "";
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpget= new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpget);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}

Notify me if weather is gonna rain

Hi everyone i just want to ask, how will i be able to notify my phone
if its gonna rain like when you send a request for the current weather
the request should run on background and if its gonna rain then it will notify.
Can anyone give some hints or any tutorial for me
to able to send a request through a service and notify me
if its gonna rain please share some ideas
cause i really need it and thank you.
i have done a class for requesting the current location and i use openweathermap API for me to get the current weather.
package com.example.autoapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
public class WeatherJSONParser {
public WeatherJSONParser()
{
}
public JSONObject getWeatherFromUrl(String url)
{
String holder= null;
JSONObject jobj=null;
try
{
HttpClient client= new DefaultHttpClient();
HttpGet get= new HttpGet(url);
HttpResponse response= client.execute(get);
StatusLine sLine= response.getStatusLine();
int status= sLine.getStatusCode();
if(status==200)
{
HttpEntity content= response.getEntity();
InputStream iStream= content.getContent();
StringBuilder cBuilder= new StringBuilder();
BufferedReader bReader= new BufferedReader(new InputStreamReader(iStream));
String cLine=null;
while((cLine=bReader.readLine())!= null)
{
cBuilder.append(cLine);
}
iStream.close();
holder= cBuilder.toString();
jobj= new JSONObject(holder);
return jobj;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
private final String URL = "http://api.worldweatheronline.com/free/v1/weather.ashx?key=***your api key*****&q=00.00,00.00&cc=no&date=2010-04-23&format=xml";
private static final String KEY_SONG = "weather"; // parent node
// public variable
public static final String KEY_TEMPERATURE_MAXIMUM = "tempMaxC";
public static final String KEY_TEMPERATURE_MINIMUM = "tempMinC";
public static final String KEY_WEATHER_DESCRIPTION = "weatherDesc";
public static final String KEY_PRECIPITATION = "precipMM";
public static final String KEY_THUMB_URL = "weatherIconUrl";
private ArrayList<HashMap<String, String>> aList =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
aList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
try {
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TEMPERATURE_MAXIMUM, parser.getValue(e, KEY_TEMPERATURE_MAXIMUM));
map.put(KEY_TEMPERATURE_MINIMUM, parser.getValue(e, KEY_TEMPERATURE_MINIMUM));
map.put(KEY_WEATHER_DESCRIPTION, parser.getValue(e, KEY_WEATHER_DESCRIPTION).trim());
map.put(KEY_PRECIPITATION, parser.getValue(e, KEY_PRECIPITATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
aList.add(map);
}
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter = new LazyAdapterForWeather(WeatherReportActivity.this, aList, 0);
return "Executed";
}
#Override
protected void onPostExecute(String result) {
if(mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
list.setAdapter(adapter);
}
#Override
protected void onPreExecute() {
ShowLoading();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
See in this way you can get the weather report . For running the same thing in service at regular interval
you need to merge two code

How to parse same name tag in Android XML DOM Parsing?

I am not able to parse my XML here. It returns "Item" only.
My AndroidActivity cannot be shown as it is very big. That's why I have only shown the part which is responsible for parsing.
My XML Looks like this :
<MyResource>
<Item>First</Item>
<Item>Second</Item>
</MyResource>
My ActivityClass method:
public class ShowItems extends Activity{
ListView lv;
ListAdapter adapter;
static final String KEY_RESOURCE = "MyResource"; // parent node
static final String KEY_ITEM = "Item";
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String[] from={KEY_ITEM };
int[] to={R.id.mylist_item};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.showitems);
lv=(ListView) findViewById(R.id.lv_items);
parseXML();
adapter = new SimpleAdapter(this, mylist,R.layout.list_item,from , to);
lv.setAdapter(adapter);
}
private void parseXML() {
// TODO Auto-generated method stub
XMLParser parser = new XMLParser();
final String URL="http://10.0.2.2:8080/MySite/xml";
String xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_RESOURCE);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ITEM, parser.getValue(e, KEY_ITEM));
mylist.add(map); }
}
My XML Parser Class:
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.HttpClient;
import org.apache.http.client.methods.HttpGet;
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 {
public String getXmlFromUrl(String url) {
String xml = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
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 "";
}
}
I am not able to parse my XML here. What is the problem here?
It returns "Item" only.
What do I need to do in my ActivityClass especially in this part of the code?
String xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_RESOURCE);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ITEM, parser.getValue(e, KEY_ITEM));
mylist.add(map); }
Your getValue() method gets MyResource element, from there, you need to get all Items under MyResource and do getElementValue(). Example code is:
public Map getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
for (int i = 0; i < n.getLength(); i++) {
System.out.println(getElementValue(n.item(i)));
}
//Here store it in list/map and return list/map instead of String
return list/MapHere;
}

Parse Imagelink in Cdata description tag Dom parsing

I want to retrieve the image link inside the description tag, my tags are all working, here is the sample of description tag:
[http://news.instaforex.com/analytics/rss][1]
I want to retrieve the image link or to show the image. My question is how to that base on my code below?
mainactivity
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://news.instaforex.com/analytics/rss";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_PUBDATE = "pubDate";
static final String KEY_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayList<HashMap<String, Spanned>> menuItems = new ` ArrayList<HashMap<String, Spanned>>();
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, Spanned> map = new HashMap<String, Spanned>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
map.put(KEY_PUBDATE, Html.fromHtml(parser.getValue(e, KEY_PUBDATE)));
String description = parser.getValue(e, KEY_DESCRIPTION);;
int index = description.indexOf("The material has been provided by InstaForex Company", 0);
description = description.substring(0, index-1);
map.put(KEY_DESCRIPTION, Html.fromHtml(description));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_TITLE, KEY_PUBDATE }, new int[] {
R.id.name, R.id.cost });
setListAdapter(adapter);
((BaseAdapter) adapter).notifyDataSetChanged();
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String title = menuItems.get(position).get(KEY_TITLE).toString();
String pubDate = menuItems.get(position).get(KEY_PUBDATE).toString();
String description= menuItems.get(position).get(KEY_DESCRIPTION).toString();
System.out.println("PubDate==>"+pubDate+"\n Description===>"+description);
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_PUBDATE, pubDate);
in.putExtra(KEY_DESCRIPTION, description);
startActivity(in);
}
});
}
}
xmlparser
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.text.Html;
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();
dbf.setCoalescing(true);
dbf.setNamespaceAware(true);
if (dbf.isNamespaceAware()==Boolean.TRUE) {
dbf.setNamespaceAware(Boolean.FALSE);
}
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 || child.getNodeType() == Node.CDATA_SECTION_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 doing everything in background using doInBackground() where to use onPostExecute()

I am trying to show JSON data into Mapview, but always getting blank map.
I knew that to populate I need to use onPostExecute() in my activity but I am confuse where I need to put onPostExecute() method and what are the lines I need to place in that.
Please someone make these changes, below I have written my code, advance thanks to viewers and readers
JSON Data:-
{
"maps": [
{
"title": "Place One",
"latitude" : "46.483742",
"longitude" : "7.663157",
"country": "Switzerland"
},
{
"title" : "Place Two",
"latitude" : "59.25235",
"longitude" : "18.465536",
"country" : "Sweden"
},
{
"title" : "Place Three",
"latitude" : "56.404182",
"longitude" : "-3.818855",
"country" : "Scotland"
}
]
}
Activity Code:-
mapOverlays = mapView.getOverlays();
drawable = getResources().getDrawable(R.drawable.ic_launcher);
itemizedOverlay = new SimpleItemizedOverlay (drawable, mapView);
itemizedOverlay.setShowClose(false);
itemizedOverlay.setShowDisclosure(true);
itemizedOverlay.setSnapToCenter(false);
class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet("https://dl.***.com/maps.json");
// Get the response that sends back
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Convert this response into a readable string
String jsonString = null;
try {
jsonString = StreamUtils.convertToString(response.
getEntity().getContent());
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Create a JSON object that we can use from the String
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
JSONArray jsonArray = json.getJSONArray("maps");
Log.e("log_tag", "Opening JSON Array ");
for
(int i=0;i < jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String latitude = jsonObject.getString("latitude");
String longitude = jsonObject.getString("longitude");
String title = jsonObject.getString("title");
String country = jsonObject.getString("country");
double lat = Double.parseDouble(latitude);
double lng = Double.parseDouble(longitude);
Log.e("log_tag", "ADDING GEOPOINT"+title);
point = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
OverlayItem overlayItem = new OverlayItem(point, title,
country);
itemizedOverlay.addOverlay(overlayItem);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
itemizedOverlay.populateNow();
mapOverlays.add(itemizedOverlay);
if (savedInstanceState == null) {
MapController controller = mapView.getController();
controller.setCenter(point);
controller.setZoom(7);
} else {
// example restoring focused state of overlays
int focused;
focused = savedInstanceState.getInt("focused_1", -1);
if (focused >= 0) {
itemizedOverlay.setFocus
(itemizedOverlay.getItem(focused));
}
}
return jsonString; }
}
}
I understand your problem, the following code is how to get the json data and showing in a listview. It is helpful for you to show when you will write the PostExecute Method. you have to set the overlay items in PostExecute method.
package com.androidhive.jsonparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
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 AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetEventsTask().execute("");
}
protected class GetEventsTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
protected ArrayList<HashMap<String, String>> contactList;
private final ProgressDialog dialog = new ProgressDialog(
AndroidJSONParsingActivity.this);
//PreExecute Method
protected void onPreExecute() {
this.dialog.setMessage("Loading, Please Wait..");
this.dialog.setCancelable(false);
this.dialog.show();
}
//doInBackground Method
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
contactList = new ArrayList<HashMap<String, String>>();
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.i("json objects",""+json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
try {
// Getting Array of Contacts
contacts = jObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return contactList;
}
//onPostExecute Method
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// selecting single ListView item
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
contactList, R.layout.list_item, new String[] { TAG_NAME,
TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
lv.setListAdapter(adapter);
// Launching new screen on Selecting Single ListItem
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.email))
.getText().toString();
String description = ((TextView) view
.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
//Dismiss the dialog
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
}

Categories

Resources