<NewDataSet>
<Table>
<Cust_Name>Dev</Cust_Name>
<Order_No>OR00000009</Order_No>
<Freight_Rate>68000</Freight_Rate>
<Station_Name>Chennai</Station_Name>
<Station_Name1>Kolkatta</Station_Name1>
</Table>
<Table>
<Cust_Name>FSL</Cust_Name>
<Order_No>OR00000010</Order_No>
<Freight_Rate>6000</Freight_Rate>
<Station_Name>Mumbai</Station_Name>
<Station_Name1>Pune</Station_Name1>
</Table>
<Table>
<Cust_Name>FSL</Cust_Name>
<Order_No>OR00000011</Order_No>
<Freight_Rate>7000</Freight_Rate>
<Station_Name>Mumbai</Station_Name>
<Station_Name1>Pune</Station_Name1>
</Table>
<Table>
<Cust_Name>FSL</Cust_Name>
<Order_No>OR00000012</Order_No>
<Freight_Rate>7000</Freight_Rate>
<Station_Name>Chennai</Station_Name>
<Station_Name1>Bangalore</Station_Name1>
</Table>
</NewDataSet>
How to arrange Cust_Name,Order_No,Freight_Rate etc,.. in a row of a gridview in android?
This is the exact link for the above XML file
"http://54.251.60.177/StudentWebService/StudentDetail.asmx/GetTMSOrders"
Sources for reference
public class GridSample extends Activity
{
// All static variables
static final String URL = "http://54.251.60.177/StudentWebService/StudentDetail.asmx/GetTMSOrders";
// XML node keys
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_CUST = "Cust_Name";
static final String KEY_ORDER = "Order_No";
static final String KEY_FREIGHT = "Freight_Rate";
#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_TABLE);
// 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_CUST, parser.getValue(e, KEY_CUST));
map.put(KEY_ORDER, parser.getValue(e, KEY_ORDER));
map.put(KEY_FREIGHT,parser.getValue(e, KEY_FREIGHT));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.grid_item,new String[] { KEY_CUST, KEY_ORDER, KEY_FREIGHT },
new int[] { R.id.name, R.id.desciption, R.id.cost });
GridView gv = (GridView)findViewById(R.id.gridVi);
gv.setAdapter(adapter);
gv.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_CUST, name);
in.putExtra(KEY_ORDER, cost);
in.putExtra(KEY_FREIGHT, description);
startActivity(in);
}
});
}}
SingleMenuItemActivity.java
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_CUST = "Cust_Name";
static final String KEY_ORDER = "Order_No";
static final String KEY_FREIGHT = "Freight_Rate";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_grid_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String cust = in.getStringExtra(KEY_CUST);
String order = in.getStringExtra(KEY_ORDER);
String freight = in.getStringExtra(KEY_FREIGHT);
// Displaying all values on the screen
TextView lblcust = (TextView) findViewById(R.id.cust_label);
TextView lblorder = (TextView) findViewById(R.id.Order_label);
TextView lblfreight = (TextView) findViewById(R.id.freight_label);
lblcust.setText(cust);
lblorder.setText(order);
lblfreight.setText(freight);
}}
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));
}}
Thanks a lot!..
you can set your xml file layout in horizontal way and try parsing xml in that gridview
Related
"http://54.251.60.177/StudentWebService/StudentDetail.asmx"
The above link is the web service, which contains two methods namely
GetStudentDetails
GetStudentsDetailsXML
The input values for this method is "carrier" for both methods
I am trying to consume this web service from android by the method SOAP.Actually the second method service is returning the values in the form of XML,here i am trying to consume this method and trying to show that returned values into List-view.But after getting run of my emulator,its simply just showing a black screen.
How to achieve my requirements? Can any one make me clear.
Please find my sources for reference
web method.java
package org.test.web.services;
public class GetStudentsDetailsXML
{
public String GetStudentsDetailsXML(String fieldName)
{
return fieldName;
}
}
AndroidXMLParsingActivity.java
public class AndroidXMLParsingActivity extends ListActivity
{
private String METHOD_NAME = "GetStudentsDetailsXML";
private String NAMESPACE = "http://tempuri.org/";
private String SOAP_ACTION ="http://tempuri.org/GetStudentsDetailsXML";
private static final String URL = "http://54.251.60.177/StudentWebService/StudentDetail.asmx?WSDL";
EditText edt1,edt2;
Button btn;
TextView tv;
static final String URL_XML = "http://54.251.60.177/StudentWebService/StudentDetail.asmx/GetStudentsDetailsXML";
//XML node keys
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_FIELDTYPE = "FieldType";
static final String KEY_FIELDFORMAT = "FieldFormat";
static final String KEY_SAMPLE = "Sample";
static final String KEY_SEARCH = "SearchTags";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.button_get_result);
edt1 = (EditText)findViewById(R.id.editText1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//Use this to add parameters
request.addProperty("fieldName",edt1.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try
{
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
System.out.println("Result : "+ result.toString());
}
catch (Exception E)
{
E.printStackTrace();
}
}
});
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL_XML); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TABLE);
// 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_FIELDTYPE, parser.getValue(e, KEY_FIELDTYPE));
map.put(KEY_FIELDFORMAT, parser.getValue(e, KEY_FIELDFORMAT));
map.put(KEY_SAMPLE, parser.getValue(e, KEY_SAMPLE));
map.put(KEY_SEARCH, parser.getValue(e, KEY_SEARCH));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.list_item,new String[] { KEY_FIELDFORMAT, KEY_SEARCH, KEY_SAMPLE }, new int[]
{R.id.FieldFORMAT_textView, R.id.Search_TEXTVIEW, R.id.Sample_TEXTVIEW });
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 FieldFormat = ((TextView) view.findViewById(R.id.FieldFORMAT_textView)).getText().toString();
String Sample = ((TextView) view.findViewById(R.id.Sample_TEXTVIEW)).getText().toString();
String Search = ((TextView) view.findViewById(R.id.Search_TEXTVIEW)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_FIELDFORMAT, FieldFormat);
in.putExtra(KEY_SAMPLE, Sample);
in.putExtra(KEY_SEARCH, Search);
startActivity(in);
}
}); } }
SingleMenuItemActivity.java
public class SingleMenuItemActivity extends Activity
{
// XML node keys
static final String KEY_FIELDFORMAT = "FieldFormat";
static final String KEY_SAMPLE = "Sample";
static final String KEY_SEARCH = "SearchTags";
#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 Fieldformat = in.getStringExtra(KEY_FIELDFORMAT);
String Sample = in.getStringExtra(KEY_SAMPLE);
String Search = in.getStringExtra(KEY_SEARCH);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.fieldformat_label);
TextView lblCost = (TextView) findViewById(R.id.Sample_label);
TextView lblDesc = (TextView) findViewById(R.id.Search_label);
lblName.setText(Fieldformat);
lblCost.setText(Sample);
lblDesc.setText(Search);
}}
XMLParser.java
public class XMLParser
{
// constructor
public XMLParser()
{
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String urlxml) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlxml);
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));
}
}
Thanks in advance!..
After the line:
// selecting single ListView item
ListView lv = getListView();
if the adapter related to lv is adapter (a few lines above), I would put this way,though it works with ArrayAdapter and not ListAdapter:
lv.setAdapter(adapter);
then, you have to add elements to the adapter with adapter.add(what you add, which is a string if I'm not wrong according to the documentation),and when all is added add:
adapter.notifyDataSetChanged();
The last one is to make the elements to be shown on the screen
Right now i am displaying the data from XML file in to grid view in android.This is the exact xml's file link
"http://54.251.60.177/StudentWebService/StudentDetail.asmx/GetTMSOrders" which
i am trying to show.I have done that concept successfully, but here the problem is,i am not getting the answer like the below image
i need to show like the below image, in android
but i am getting only like the below image.....
How to overcome this concept?can any one please make me clear?
thanks for your precious time!..
Here my sources for reference,please find
GridviewSample.java
public class GridviewSample extends Activity
{
// All static variables
static final String URL = "http://54.251.60.177/StudentWebService/StudentDetail.asmx/GetTMSOrders";
// XML node keys
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_CUST = "Cust_Name";
static final String KEY_ORDER = "Order_No";
static final String KEY_FREIGHT = "Freight_Rate";
static final String KEY_STATION1 = "Station_Name";
static final String KEY_STATION2 = "Station_Name1";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv = (GridView)findViewById(R.id.gridView1);
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_TABLE);
// 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_CUST, parser.getValue(e, KEY_CUST));
map.put(KEY_ORDER, parser.getValue(e, KEY_ORDER));
map.put(KEY_FREIGHT, parser.getValue(e, KEY_FREIGHT));
map.put(KEY_STATION1, parser.getValue(e, KEY_STATION1));
map.put(KEY_STATION2, parser.getValue(e, KEY_STATION2));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
SimpleAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.grid_item,
new String[] { KEY_CUST, KEY_ORDER, KEY_FREIGHT,KEY_STATION1,KEY_STATION2 }, new int[]
{
R.id.cust, R.id.order, R.id.freight,R.id.statio1,R.id.station2 });
gv.setAdapter(adapter);
gv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> Table, View v,int position, long id)
{
String cust = ((TextView) v.findViewById(R.id.cust)).getText().toString();
String order = ((TextView) v.findViewById(R.id.order)).getText().toString();
String freight = ((TextView) v.findViewById(R.id.freight)).getText().toString();
String station1 = ((TextView) v.findViewById(R.id.statio1)).getText().toString();
String station2 = ((TextView) v.findViewById(R.id.station2)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), Single_gridview_item.class);
in.putExtra(KEY_CUST, cust);
in.putExtra(KEY_ORDER, order);
in.putExtra(KEY_FREIGHT, freight);
in.putExtra(KEY_STATION1, station1);
in.putExtra(KEY_STATION2, station2);
startActivity(in);
}
});
} }
Single_gridview_item
public class Single_gridview_item extends Activity
{
// XML node keys
static final String KEY_TABLE = "Table"; // parent node
static final String KEY_CUST_NAME = "Cust_Name";
static final String KEY_ORDER = "Order_No";
static final String KEY_FREIGHT = "Freight_Rate";
static final String KEY_STATION1 = "Station_Name";
static final String KEY_STATION2="Station_Name1";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.single_grid_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String cust = in.getStringExtra(KEY_CUST_NAME);
String order = in.getStringExtra(KEY_ORDER);
String freight = in.getStringExtra(KEY_FREIGHT);
String station1 = in.getStringExtra(KEY_STATION1);
String station2 = in.getStringExtra(KEY_STATION2);
// Displaying all values on the screen
TextView lblcust = (TextView) findViewById(R.id.cust_label);
TextView lblorder = (TextView) findViewById(R.id.order_label);
TextView lblfreight = (TextView) findViewById(R.id.freight_label);
TextView lblstation1 = (TextView) findViewById(R.id.station1_label);
TextView lblstation2 = (TextView) findViewById(R.id.station2_label);
lblcust.setText(cust);
lblorder.setText(order);
lblfreight.setText(freight);
lblstation1.setText(station1);
lblstation2.setText(station2);
}}
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));
}}
Don't use a grid view, it won't help you. It is designed to display a list of items as a grid. You may specify the number of columns, but displaying a table is more of a job for a TableLayout.
I've seen quite a few posts about this, but actually I did not get any to work. I am building a simple TV guide android application. I simply Use RSS from a tvprofil.net to show whats on TV today. The problem is, I do not know how to Parse CDATA in XML. I am using some standard parser with DOM... at least I think so..
This is a bit of XML:
.
.
.
<item>
<title>RTS1 14.08.2012</title>
<pubDate>Tue, 14 Aug 2012 06:00:00</pubDate>
<content:encoded><![CDATA[06:00 Vesti<br>06:05 Jutarnji program<br>08:00 Dnevnik
<br>8:15 Jutarnji Program<br>09:00 Vesti ... ]]></content:encoded>
</item>
.
.
.
now, this is my main app:
public class Main extends ListActivity {
// All static variables
static final String URL = "http://tvprofil.net/rss/feed/channel-group-2.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_NAME = "title";
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "content:encoded";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String,String>> menuItems = new ArrayList<HashMap<String,String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); //get XML
Document doc = parser.getDomElement(xml); // get DOM elem.
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//loop
for (int i=0; i< nl.getLength(); i++){
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
//add to map
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// hash => list
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item,
new String[]{KEY_NAME, KEY_DESC, KEY_DATE}, new int[]{
R.id.name, R.id.description, R.id.date
});
setListAdapter(adapter);
//singleView
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String name = ((TextView)view.findViewById(R.id.name)).getText().toString();
String date = ((TextView)view.findViewById(R.id.date)).getText().toString();
String description = ((TextView)view.findViewById(R.id.description)).getText().toString();
//intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_DATE, date);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
and the parser class:
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));
}
}
there is one more class for Single menu item.. but I think it's irrelevant in this case.
Now, I'd just like to see no HTML tags after parsing it and dealing with CDATA...
Anyone got idea about this one?
Add this
dbf.setCoalescing(true);
where dbf is
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
First add this method
public String getCharacterDataFromElement(Element e, String str) {
NodeList n = e.getElementsByTagName(str);
Element e1=(Element) n.item(0);
Node child = e1.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
Call the above method as so-
map.put(KEY_DESC, parser.getCharacterDataFromElement(e, KEY_DESC));
This should get you the CDATA in String format. HOpe this helps
getTextContent.
This attribute returns the text content of this node and its
descendants
getNodeValue()
The value of this node, depending on its type;
usually you shouled use getTextContent.
zg_spring's answer worked perfectly for me when I needed to extract image URLs from CDATA in a set of "description" xml elements:
//Get the content of all "item" elements
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xml)));
NodeList nlDetails = doc.getElementsByTagName("item");
//Loop through elements and extract content of "description" elements
for(int k = 0; k < numDetails; k++) {
Element nDetails = (Element)nlDetails.item(k);
NodeList nlCoverURL = nDetails.getElementsByTagName("description");
Node nCoverURL = nlCoverURL.item(0);
String sCoverURL = nCoverURL.getTextContent();
//Isolate the relevant part of the String and load it into an ArrayList
String[] descriptionContent = sCoverURL.split("\"");
String s = descriptionContent[11]
alImages.add(s);
}
Ok, about this specific situation, I have large XML file that should be parsed and shown in Android, and the part of it is here:
.
.
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/:
.
.
<item>
<title>RTS1</title>
<pubDate>Tue, 14, Aug 2012</pubDate>
<content:encoded><![CDATA[6:00 Vesti<br>06:05 Jutarnji program<br>08:15 Jutarnji dnevnik
<br>09:00 Kamiondzije .................. 23:15 Film<br>]]>
</content:encoded>
<item>
In my main, app I have done this:
public class Main extends ListActivity {
// All static variables
static final String URL = "http://tvprofil.net/rss/feed/channel-group-2.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_NAME = "title";
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "content:encoded";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String,String>> menuItems = new ArrayList<HashMap<String,String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); //get XML
Document doc = parser.getDomElement(xml); // get DOM elem.
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//loop
for (int i=0; i< nl.getLength(); i++){
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
//add to map
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// hash => list
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item,
new String[]{KEY_NAME, KEY_DESC, KEY_DATE}, new int[]{
R.id.name, R.id.description, R.id.date
});
setListAdapter(adapter);
//singleView
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String name = ((TextView)view.findViewById(R.id.name)).getText().toString();
String date = ((TextView)view.findViewById(R.id.date)).getText().toString();
String description = ((TextView)view.findViewById(R.id.description)).getText().toString();
//intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_DATE, date);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
please, look closely at:
static final String KEY_DESC = "content:encoded";
I've tried with:
static final String KEY_DESC = "encoded";
and even with:
static final String KEY_DESC = "http://purl.org/rss/1.0/modules/content/encoded";
but nothing works.. doesn't show anything nor in Log.w when I set it nor on phone...
I'll even post parser class, I don't want any confusion:
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);
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));
}
}
I have written this code to parse this xml:
http://hiscentral.cuahsi.org/webservices/hiscentral.asmx/GetSeriesCatalogForBox2
But when I run it... it say "APP Stopped Working" and I can't figure out the reason... Please help!
The code is:
xmlActivity.java
package com.example.xml;
public class XmlActivity extends ListActivity {
static final String URL = "http://hiscentral.cuahsi.org/webservices/hiscentral.asmx/GetSeriesCatalogForBox2";
// XML node keys
static final String KEY_SeriesRecord = "SeriesRecord"; // parent node
static final String KEY_latitude = "latitude";
static final String KEY_longitude = "longitude";
static final String KEY_location = "location";
/** Called when the activity is first created. */
#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_SeriesRecord);
// 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_SeriesRecord, parser.getValue(e, KEY_SeriesRecord));
map.put(KEY_latitude, parser.getValue(e, KEY_latitude));
map.put(KEY_longitude, parser.getValue(e, KEY_longitude));
map.put(KEY_location, parser.getValue(e, KEY_location));
// adding HashList to ArrayList
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item, new String[] { KEY_latitude, KEY_longitude,
KEY_location }, new int[] { R.id.name, R.id.desciption,
R.id.cost });
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_latitude, name);
in.putExtra(KEY_longitude, cost);
in.putExtra(KEY_location, description);
startActivity(in);
}
});
}
}
SingleMenuItemActivity.java
package com.example.xml;
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_latitude = "latitude";
static final String KEY_longitude = "longitude";
static final String KEY_location = "location ";
#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 latitude = in.getStringExtra(KEY_latitude);
String longitude = in.getStringExtra(KEY_longitude);
String location = in.getStringExtra(KEY_location);
// 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(latitude);
lblCost.setText(longitude);
lblDesc.setText(location);
}
}
xmlParser.java
package com.example.xml;
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));
}
}
You cannot do slow operation like HttpRequest in the Activity Thread. You must put them in a separate thread (AsyncTask). This is mentionned by Google but i lost source i'm sorry.
You should try creating an AsyncTask here is how you should try :
public class GetSoigneurInfoTask extends AsyncTask<Document, Integer, Document> //Le même code s'applique pour presque tout sauf onPostExecute()
{
Document doc;
String xml;
String url;
public GetSoigneurInfoTask(String URL)
{
url = URL;
}
protected Document doInBackground(Document...params)
{
xml = XmlFunctions.getXML(url);
doc = XmlFunctions.XMLfromString(xml);
return doc;
}
protected void onPostExecute(Document result)
{
if(result != null)
{
NodeList nodeList = doc.getElementsByTagName("RootTag"); //Crée une liste avec les elements sous soigneur
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
NodeList nodelist = element.getElementsByTagName("childTag");
Element element1 = (Element) nodelist.item(0);
NodeList fstNm = element1.getChildNodes();
soignTemp = fstNm.item(0).getNodeValue();
}
}
}
}
So you call your methods in doInBackground() and you do everything you have to do with UI in onPostExecute()!
Hope this helps!