cannot in parsing nested xml structure - android

this is my xml structure :
<menu>
<item_category>
<category_name>ICECREAM</category_name>
<item>
<item_name>SOFTY</item_name>
<item_price>7.00</item_price>
</item>
<item>
<item_name>STICK</item_name>
<item_price>15.00</item_price>
</item>
<item>
<item_name>CONE</item_name>
<item_price>25.00</item_price>
</item>
</item_category>
<item_category>
<category_name>PIZZA</category_name>
<item>
<item_name>PIZZA-HOT</item_name>
<item_price>35.00</item_price>
</item>
<item>
<item_name>PIZZA-CRISPY</item_name>
<item_price>29.00</item_price>
</item>
</item_category>
</menu>
this is my code where i am parsing into list view
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://api.androidhive.info/pizza/?format=xml";
static final String URL = "http://192.168.1.112/dine/index.php/dineout/mob_view";
//static final String URL = "http://192.168.1.112/dineout/index.php/dineout/view";
// XML node keys
static final String KEY_MENU= "menu"; // parent node
//static final String KEY_ID = "foodjoint_id";
static final String KEY_CATEGORY= "category_name";
static final String KEY_ITEM= "item";
static final String KEY_ITEM_NAME= "item_name";
static final String KEY_PRICE= "item_price";
#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++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_CATEGORY, parser.getValue(e,KEY_CATEGORY));
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] {KEY_CATEGORY,KEY_ITEM_NAME,KEY_PRICE}, new int[] {R.id.category,R.id.name,R.id.costlab });
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 category = ((TextView) view.findViewById(R.id.category)).getText().toString();
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
//in.putExtra(KEY_ITEM, name);
in.putExtra(KEY_CATEGORY, category);
in.putExtra(KEY_ITEM_NAME,name);
in.putExtra(KEY_PRICE, cost);
//in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
My problem is i am not getting the value of category_name. I tried with nested loop but its all the same. please help me . what should i change in the code.
This is my xmlParser
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));
}

try this way
NodeList n,ncategories;
Element e;
static final String KEY_ITEMCATEGORY= "item_category";
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
ncategories = doc.getElementsByTagName(KEY_MENU);
for(int i=0;i<ncategories.getLength();i++){
e=(Element)ncategories.item(i);
n=e.getElementsByTagName(KEY_ITEMCATEGORY);
for(int c=0;c<n.getLength();c++){
HashMap<String, String> map = new HashMap<String, String>();
e=(Element)n.item(c);
String category= parser.getValue(e, KEY_CATEGORY).toString();
Log.e("catname", parser.getValue(e, KEY_CATEGORY).toString());
map.put(KEY_CATEGORY, category);
NodeList ns=e.getElementsByTagName(KEY_ITEM);
for(int j=0;j<ns.getLength();j++){
e=(Element)ns.item(j);
Log.e("itemname", parser.getValue(e,KEY_ITEM_NAME).toString());
Log.e("itemprice", parser.getValue(e, KEY_PRICE).toString()+"\n");
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
}
menuItems.add(map);
}

Try something like this:
NodeList nl_Cat = doc.getElementsByTagName(KEY_ITEM_CATEGORY);
for (int i = 0; i < nl_Cat.getLength(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element cat = (Element) nl_Cat(i);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int j = 0; j < nl.getLength(); j++)
{
Element e = (Element) nl.item(j);
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
}
menuItems.add(map);
}
Hope this works!

You are retrieving list of item elements and trying to find category_name in item element. However, looking at your xml, category_name is sibling of item element, not child. So you will not get category name in that way.
You might want to retrieve list of item_category and then populate items from it.
NodeList nl_categories = doc.getElementsByTagName(KEY_ITEM_CATEGORY);
for(int i = 0; i < nl_categories; i++)
{
Element e = (Element) nl.item(i);
String category = parser.getValue(e,KEY_CATEGORY);
NodeList nl = e.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int j = 0; j < nl.getLength(); j++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(j);
map.put(KEY_CATEGORY, category);
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
menuItems.add(map);
}
}

Related

removing selected item in listview in android

Can somebody please give me an example code of removing a selected item in a listview ?.
i am using simple adapter to store the data.
My code is..
static final String KEY_ITEM = "finance"; // parent node
static final String KEY_ID = "finance";
static final String KEY_NAME = "company";
static final String KEY_COST = "high";
static final String KEY_DESC = "volume";
static final String KEY_SYMBOL="symbol";
static final String KEY = "low";
private String selectedItem;
private ListAdapter adapter;
Context context;
ListView lv;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView titleBar = (TextView)getWindow().findViewById(android.R.id.title);
titleBar.setTextColor(Color.GREEN);
final 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);
for (int i = 0; i < nl.getLength(); i++) {
// HashMap<String, String> map = new HashMap<String, String>();
Node theAttribute;
Element e = (Element) nl.item(i);
NodeList nl1=e.getElementsByTagName(KEY_ID);
System.out.println("keyId"+nl1.getLength());
for(int j=0;j<nl1.getLength();j++)
{
Element e1 = (Element) nl1.item(j);
HashMap<String, String> map = new HashMap<String, String>();
NodeList n = e1.getElementsByTagName(KEY_NAME);
for (int k = 0; k < n.getLength(); k++) {
Element e2 = (Element) n.item(k);
// System.out.println("node Title value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
theAttribute = attributes2.item(a);
String s=theAttribute.getNodeValue();
// lblName.setTypeface(hindiFont);
//s = s.replaceAll("[-;#39&amp:,]","");
map.put(KEY_NAME,s);
}
}
NodeList n4 = e1.getElementsByTagName(KEY_SYMBOL);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n4.getLength(); k++) {
Element e2 = (Element) n4.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
for (int a = 0; a < attributes2.getLength(); a++)
{
// HashMap<String, String> map = new HashMap<String, String>();
theAttribute = attributes2.item(a);
String s=theAttribute.getNodeValue();
map.put(KEY_SYMBOL,s);
// menuItems.add(map);
}
}
NodeList n1 = e1.getElementsByTagName(KEY_COST);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n1.getLength(); k++) {
Element e2 = (Element) n1.item(k);
// System.out.println("node Url value");
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
//HashMap<String, String> map = new HashMap<String, String>();
theAttribute = attributes2.item(a);
map.put(KEY_COST,theAttribute.getNodeValue());
}}
NodeList n2 = e1.getElementsByTagName(KEY_DESC);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n2.getLength(); k++) {
Element e2 = (Element) n2.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
for (int a = 0; a < attributes2.getLength(); a++)
{
// HashMap<String, String> map = new HashMap<String, String>();
theAttribute = attributes2.item(a);
String s=theAttribute.getNodeValue();
map.put(KEY_DESC,s);
// menuItems.add(map);
}
} NodeList n3 = e1.getElementsByTagName(KEY);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n3.getLength(); k++) {
Element e2 = (Element) n3.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
for (int a = 0; a < attributes2.getLength(); a++)
{
// HashMap<String, String> map = new HashMap<String, String>();
theAttribute = attributes2.item(a);
String s=theAttribute.getNodeValue();
map.put(KEY,s);
// menuItems.add(map);
}
}
menuItems.add(map);
}
}
// Adding menuItems to ListView
adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST,KEY,KEY_SYMBOL }, new int[] {
R.id.name, R.id.desciption, R.id.cost,R.id.low,R.id.symbol }){
};
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
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_NAME, name);
in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);*/
Toast.makeText(getApplicationContext(), "on clicked",Toast.LENGTH_LONG).show();
}
});
// Create the listener for long item clicks
OnItemLongClickListener itemLongListener = new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, final int position, long rowid) {
final View view=v;
// Store selected item in global variable
selectedItem = parent.getItemAtPosition(position).toString();
// Toast.makeText(getApplicationContext(), "select item"+selectedItem,Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidXMLParsingActivity.this);
builder.setMessage("Do you want to remove " + "?");
final int positionToRemove = position;
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
adapter.remove(selectedItem);
adapter.notifyDataSetChanged();
Toast.makeText(
getApplicationContext(),
selectedItem + " has been removed.",
Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Create and show the dialog
builder.show();
// Signal OK to avoid further processing of the long click
return true;
}
};
getListView().setOnItemLongClickListener(itemLongListener);
}
}
it show the error in these line
adapter.remove(selectedItem);
adapter.notifyDataSetChanged();
it show
The method remove(String) is undefined for the type ListAdapter
add to cast adapter
please help me with example code!!!!
thanks in advance!!!!!!!!
Change from ListAdapter SimpleAdapter.
private SimpleAdapter adapter;
Make menuItems global.
And then you can do
menuItems.remove(selectedItem);
adapter.notifyDataSetChanged();

Android DOM Parser - retrieving image link from description tag

I'm using DOM Parser to parse this XML feed: http://loc.grupolusofona.pt/index.php/?format=feed
I got the Parser working fine for all tags, i'm just missing ideas to be able to retrieve the image from within the description tag.
The description tag on the feed looks like this:
<description><![CDATA[<div class="K2FeedIntroText"><p><img style="margin: 10px;"
alt="joana soares rostos" src="http://loc.grupolusofona.pt/images/stories/varios/joana%20soares%20rostos.jpg"
height="110" width="120" />Quis ser veterinária mas deixou-se seduzir pela magia
de retratar o real. Joana Soares frequenta o primeiro ano do curso de Fotografia
da Lusófona e descreve a sua paixão pelas fotos como «inexplicável».</p>
</div>]]></description>
And i wanted to retrieve the image link:
http://loc.grupolusofona.pt/images/stories/varios/joana%20soares%20rostos.jpg
My Parser :
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
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 ) {
if( elem != null){
return elem.getTextContent();
}
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));
}
}
And my Main Activity:
public class Noticias extends ListActivity {
// All static variables
static final String URL = "http://loc.grupolusofona.pt/index.php/?format=feed";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DESC = "description";
static final String KEY_LINK = "link";
static final String KEY_PUBDATE = "pubDate";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_noticias);
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_ID, Html.fromHtml(parser.getValue(e, KEY_ID)));
map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
map.put(KEY_DESC, Html.fromHtml(parser.getValue(e, KEY_DESC)));
map.put(KEY_PUBDATE, Html.fromHtml(parser.getValue(e, KEY_PUBDATE)));
map.put(KEY_LINK, Html.fromHtml(parser.getValue(e, KEY_LINK)));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.linha_feed,
new String[] { KEY_TITLE, KEY_DESC, KEY_PUBDATE, KEY_LINK }, new int[] {
R.id.title, R.id.desc, R.id.pub, R.id.link});
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 title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desc)).getText().toString();
String pub = ((TextView) view.findViewById(R.id.pub)).getText().toString();
String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
// Starting new intent
System.out.println("Title: " + title);
System.out.println("Link: " + link);
System.out.println("Description:" + description);
System.out.println("Pubdate: " + pub);
Intent in = new Intent(Intent.ACTION_VIEW);
in.setData(Uri.parse(link));
startActivity(in);
}
});
}
}
Any ideas ?
Thanks for your time.
Use RegEx with a simple pattern like this:
<\s*img\s*[^>]+src\s*=\s*(['"]?)(.*?)\1
Here use these functions:
public static String getMatch(String patternString, String text, int groupIndex){
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE | Pattern.DOTALL );
return RegEx.getMatch(pattern, text, groupIndex);
}
public static String getMatch(Pattern pattern, String text, int groupIndex){
if(text!=null){
Matcher matcher = pattern.matcher(text);
String match = null;
while(matcher.find()){
match = matcher.group(groupIndex);
break;
}
return match;
}else{
return null;
}
}
Then you can plug in that pattern like this:
String imageSource = getMatch("<\\s*img\\s*[^>]+src\\s*=\\s*(['\"]?)(.*?)\\1", description, 2);

xml parsing using DOM parser

I need to parse document using DOM parser in android. I was unable to print all the node values
My Sample XML is:`
<xml_api_reply version="1">
<news module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
<title data="Top Stories"/>
<section_type data="0"/>
<news_entry>
<title data="BSE Sensex breaches 19000, Nifty above 5800"/>
<url data="http://in.reuters.com/article/2012/10/04/sensex-above-19000-on-reform-hopes- idINDEE89301O20121004"/>
<snippet data="| MUMBAI (Reuters) - The Nifty rose above 5800 points on Thursday, joining the Sensex in breaching key psychological levels, after continued government reform measures sparked hopes for continued action. Banks led gainers, with ICICI Bank (ICBK."/>
<source data="Reuters India"/>
<date data="3 hours ago"/>
<num_related data="145"/>
<cluster_url data="http://google.co.in/news/story?ncl=da6VmeBXmuquikM&hl=en"/>
</news_entry>
<news_entry>
<title data="Uncertainty over Kingfisher resuming operations tomorrow"/>
<url data="http://www.hindustantimes.com/India-news/NewDelhi/Uncertainty-over- Kingfisher-resuming-operations-tomorrow/Article1-939628.aspx"/>
<snippet data="Hopes of ailing Kingfisher Airlines resuming operations on Friday has faded with last ditch efforts by the management to persuade striking engineers and pilots to return to work failing to end the deadlock over the issue of non-payment of salaries for ..."/>
<source data="Hindustan Times"/>
<date data="1 hour ago"/>
<num_related data="993"/>
<cluster_url data="http://google.co.in/news/story?ncl=dzf460GzYKTOyxM&hl=en"/>
</news_entry>
</news>
</xml_api_reply>`
and I am using following code to parse the xml
xmlactivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.google.co.in/ig/api?news&hl=en";
// XML node keys
static final String KEY_ITEM = "news"; // parent node
//static final String KEY_ID = "news_entry";
static final String KEY_NAME = "title ";
static final String KEY_COST = "url ";
static final String KEY_DESC = "snippet";
#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, 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[] {
R.id.name, R.id.desciption, R.id.cost });*/
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME }, new int[] {
R.id.name});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
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_NAME, name);
//in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
and xmlParser.java
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
please help me . what is the problem and suggestion
thanks in advance!!!!!!!!!
//Try this code..
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
URLConnection conn = null;
InputStream inputStream = null;
URL urls = new URL(url);
conn = urls.openConnection();
conn.setConnectTimeout(10000);
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.setConnectTimeout(10000);
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
StringWriter writer=new StringWriter();
String line="";
while ( null!=(line=in.readLine())){
writer.write(line);
}
xml =writer.toString();
} 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();
doc = db.parse(new InputSource(new StringReader(xml)));
doc.normalize();
//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;
}
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.getTextContent();
}
}
}
}
return "";
}
// All static variables
static final String URL = "http://www.google.co.in/ig/api?news&hl=en";
// XML node keys
static final String KEY_ITEM = "news"; // parent node
static final String KEY_ID = "news_entry";
static final String KEY_NAME = "title";
static final String KEY_COST = "url";
static final String KEY_DESC = "snippet";
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);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
NamedNodeMap attributes = e.getAttributes();
System.out.println("attrlength"+attributes.getLength());
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
NodeList nl1=e.getElementsByTagName(KEY_ID);
System.out.println("keyId"+nl1.getLength());
for(int j=0;j<nl1.getLength();j++)
{
Element e1 = (Element) nl1.item(j);
NodeList n = e1.getElementsByTagName(KEY_NAME);
for (int k = 0; k < n.getLength(); k++) {
Element e2 = (Element) n.item(k);
// System.out.println("node Title value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
NodeList n1 = e1.getElementsByTagName(KEY_COST);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n1.getLength(); k++) {
Element e2 = (Element) n1.item(k);
// System.out.println("node Url value");
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}}
NodeList n2 = e1.getElementsByTagName(KEY_DESC);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n2.getLength(); k++) {
Element e2 = (Element) n2.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
}
menuItems.add(map);
}
}

android get nodelist attribute from xml file

I make listview from xml file http://view-source:http://www.macetlagi.com/maps/st/canvaser/3/tb/tb123.I will get element from "segment" tag.When i run and debug my code,i get this error java.lang.NullPointerException.Please correct my code if i do my stupid coding.This is my java code in android :
public class ListSegment extends ListActivity {
String URL_XML = "http://www.macetlagi.com/maps/st/canvaser/3/tb/tb123";
static final String KEY_SEGMENT = "segment";
static final String KEY_SEGMENT_ID = "segment_id";
static final String KEY_MAIN_SEGMENT = "main_segment_name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listsegment_main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL_XML);
Document doc = parser.getDomElement(xml);
NodeList nL = doc.getElementsByTagName(KEY_SEGMENT);
for (int i = 0; i < nL.getLength(); i++) {
Node node = nL.item(i);
if(node.hasAttributes()) {
NamedNodeMap attr_id = node.getAttributes();
attr_id.getNamedItem(KEY_SEGMENT);
}
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nL.item(i);
map.put(KEY_SEGMENT_ID, parser.getValue(e, KEY_SEGMENT_ID));
map.put(KEY_MAIN_SEGMENT, parser.getValue(e, KEY_MAIN_SEGMENT));
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item,
new String[] {KEY_SEGMENT_ID, KEY_MAIN_SEGMENT}, new int[] {
R.id.segmentid, R.id.segmentname
});
setListAdapter(adapter);
}
}

XML Parsing Error

I am consuming a web service as its output is an XML string. I am parsing it into a document and getting each child node value one by one and inserting into my SQLlite table as shown below:
public void DownloadAndInsertProblemAndReasonCode(String serverIPAddress,
String deviceId) {
String SOAP_ACTION = "http://VisionEPODWebService/GetProblemAndReasonCodesNew";
String OPERATION_NAME = "GetProblemAndReasonCodesNew";
String WSDL_TARGET_NAMESPACE = "http://VisionEPODWebService/";
String SOAP_ADDRESS = "";
SOAP_ADDRESS = "http://" + serverIPAddress
+ "/VisionEPODWebService/SystemData.asmx";
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER10);
request.addProperty("deviceID", deviceId);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
DocumentBuilderFactory docBuilberFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilberFactory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource
.setCharacterStream(new StringReader(response.toString()));
Document doc = docBuilder.parse(inputSource);
NodeList nodesProblemCode = doc
.getElementsByTagName("tblProblemCode");
ContentValues initialProblemCodeValues = new ContentValues();
dbAdapter = new DatabaseAdapter(this.context);
dbAdapter.open();
dbAdapter.BeginTransaction();
dbAdapter.DeleteRecord("tblProblemCode", "", "");
for (int i = 0; i < nodesProblemCode.getLength(); i++) {
Element element = (Element) nodesProblemCode.item(i);
NodeList PKProblemCode = element
.getElementsByTagName("PKProblemCode");
Element line = (Element) PKProblemCode.item(0);
initialProblemCodeValues.put("PKProblemCode",
getCharacterDataFromElement(line).toString());
NodeList ProblemCode = element
.getElementsByTagName("ProblemCode");
line = (Element) ProblemCode.item(0);
initialProblemCodeValues.put("ProblemCode",
getCharacterDataFromElement(line));
NodeList ProblemCodeDescription = element
.getElementsByTagName("ProblemCodeDescription");
line = (Element) ProblemCodeDescription.item(0);
initialProblemCodeValues.put("ProblemCodeDescription",
getCharacterDataFromElement(line).toString());
NodeList VWReturn = element.getElementsByTagName("VWReturn");
line = (Element) VWReturn.item(0);
initialProblemCodeValues.put("VWReturn",
getCharacterDataFromElement(line).toString());
dbAdapter.InsertRecord("tblProblemCode", "",
initialProblemCodeValues);
}
NodeList nodesReasonCode = doc
.getElementsByTagName("tblReasonCode");
ContentValues initialReasonCodeValues = new ContentValues();
dbAdapter.DeleteRecord("tblReasonCode", "", "");
for (int i = 0; i < nodesReasonCode.getLength(); i++) {
Element element = (Element) nodesReasonCode.item(i);
NodeList PKReasonCode = element
.getElementsByTagName("PKReasonCode");
Element line = (Element) PKReasonCode.item(0);
initialReasonCodeValues.put("PKReasonCode",
getCharacterDataFromElement(line).toString());
NodeList ReasonDescription = element
.getElementsByTagName("ReasonDescription");
line = (Element) ReasonDescription.item(0);
initialReasonCodeValues.put("ReasonDescription",
getCharacterDataFromElement(line));
dbAdapter.InsertRecord("tblReasonCode", "",
initialReasonCodeValues);
}
dbAdapter.SetSucessfulTransaction();
dbAdapter.EndTransaction();
dbAdapter.close();
}
catch (Exception exception) {
exception.toString();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
The problem is that after some time the XML string will not have some of child node. For example
"ProblemCode" child node.....at that time the code shows error.
How can I check whether there exists an element in the document, or whether values exist or not for the element?
I think you need to check if the child node exists: specifically for your problem node:
NodeList NL = element.getElementsByTagName("PKProblemCode");
if ((NL==null)||(NL.getLength()==0)) {
//No such node so use a default instead
} else
Element line = (Element) PKProblemCode.item(0);

Categories

Resources