我有一个Web服务,该服务具有向我返回xml字符串的方法,我想解析此xml,然后用list-view显示它.
主要活动
public class MainActivity extends ListActivity {
// All static variables
format=xml";
// XML node keys
static final String KEY_ITEM = "Roomtype"; // parent node
static final String KEY_ID = "IDRoom";
static final String KEY_NAME = "Code";
static final String KEY_COST = "normbed";
static final String KEY_DESC = "Maxbed";
static final String KEY_categroy = "Category";
static final String KEY_order = "Order";
ProgressBar pg;
String spin1;
String spin2;
String spin3;
String displayText;
TextView tv;
ListView lv;
int day, month, year;
ArrayList<HashMap<String, String>> menuItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
Spinner spinner3 = (Spinner) findViewById(R.id.spinner3);
pg = (ProgressBar) findViewById(R.id.progressBar1);
spin1 = spinner1.getSelectedItem().toString();
spin2 = spinner2.getSelectedItem().toString();
spin3 = spinner3.getSelectedItem().toString();
//Search
Button btn_search=(Button)findViewById(R.id.btn_search);
btn_search.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute
AsyncTask<String, Void, Void> xx=task.execute();
}
});
}
private void parsexml(String xmlresult){
ListView myList=(ListView)findViewById(android.R.id.list);
menuItems = new ArrayList<HashMap<String, String>>();
XmlParser parser = new XmlParser();
String xml = null; // getting XML
try {
xml = parser.getXmlFormUrl(xmlresult);
} catch (IOException e) {
e.printstacktrace();
}
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_DESC, parser.getValue(e, KEY_categroy));
map.put(KEY_DESC, parser.getValue(e, KEY_order));
// 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,KEY_categroy,KEY_order }, new int[] {
R.id.name, R.id.desciption, R.id.cost,R.id.categroy,R.id.order });
setlistadapter(adapter);
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
private Exception exception;
@Override
protected Void doInBackground(String... params) {
try {
//Invoke webservice
displayText = WebService.invokeHelloWorldWS(spin2, spin3, spin1, "search_availability");
parsexml(displayText);
}catch (Exception e) {
this.exception = e;
return null;
}
return null;
}
@Override
protected void onPostExecute(Void result) {
//Make ProgressBar invisible
pg.setVisibility(View.INVISIBLE);
}
@Override
protected void onPreExecute() {
//Make ProgressBar invisible
pg.setVisibility(View.VISIBLE);
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
XmlParser类
public class XmlParser {
String result;
public String getXmlFormUrl(String link) throws IOException {
URL url=new URL(link.toString());
HttpURLConnection UrlConnection= (HttpURLConnection) url.openConnection();
int status=UrlConnection.getResponseCode();
if(status==200){
InputStream inputStream=UrlConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"UTF8"));
StringBuilder stringBuilder= new StringBuilder();
String line;
while ((line=bufferedReader.readLine())!=null){
stringBuilder.append((line+"\n"));
}
result=stringBuilder.toString();
inputStream.close();
}
return result;
}
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 "";
}
}
这是xml文件的主要内容,当我点击搜索按钮时,结果将显示出来.
MainActivity.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tv_arrival"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Arrival Date"/>
<Button
android:id="@+id/btn_arrival"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Set"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_departure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Departure Date"/>
<Button
android:id="@+id/btn_departure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Set"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Persons"/>
<Spinner
android:id="@+id/spinner2"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown"
android:entries="@array/array_person"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="child"/>
<Spinner
android:id="@+id/spinner3"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown"
android:entries="@array/array_child"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:text="Rooms"/>
<Spinner
android:id="@+id/spinner1"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:background="@android:drawable/btn_dropdown"
android:spinnerMode="dropdown"
android:drawSelectorOnTop="true"
android:entries="@array/array_rooms"
/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Login"/>
<Button
android:id="@+id/btn_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Search"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@android:id/list"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="73dp" />
</RelativeLayout>
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="invisible"
/>
</LinearLayout>
List_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Name Label -->
<TextView
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#dc6800"
android:textSize="16sp"
android:textStyle="bold"
android:paddingTop="6dip"
android:paddingBottom="2dip" />
<!-- Description label -->
<TextView
android:id="@+id/desciption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:paddingBottom="2dip">
</TextView>
<!-- Linear layout for cost and price Cost: Rs.100 -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- Cost Label -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#5d5d5d"
android:gravity="left"
android:textStyle="bold"
android:text="Cost: " >
</TextView>
<!-- Price Label -->
<TextView
android:id="@+id/cost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:textStyle="bold"
android:gravity="left">
</TextView>
<TextView
android:id="@+id/categroy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:textStyle="bold"
android:gravity="left">
</TextView>
<TextView
android:id="@+id/order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#acacac"
android:textStyle="bold"
android:gravity="left">
</TextView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
解决方法:
您正在尝试使用WebService.invokeHelloWorldWS(spin2,spin3,spin1,“ search_availability”)的xml结果再次获得xml结果.更改代码以解析xml.
例:
private void parsexml(String xmlresult){
ListView myList=(ListView)findViewById(android.R.id.list);
menuItems = new ArrayList<HashMap<String, String>>();
XmlParser parser = new XmlParser();
Document doc = parser.getDomElement(xmlresult); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_DESC, parser.getValue(e, KEY_categroy));
map.put(KEY_DESC, parser.getValue(e, KEY_order));
// 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,KEY_categroy,KEY_order }, new int[] {
R.id.name, R.id.desciption, R.id.cost,R.id.categroy,R.id.order });
myList.setlistadapter(adapter);
((BaseAdapter)adapter).notifyDataSetChanged();
}
不要忘记在setlistadapter(adapter)之后在onPostExecute()中执行parsexml()和notifyDataSetChanged();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。