[英]Parsing XML in Android, and put into ListView
我正在創建一個應用程序,它向 Web 服務發出 HTTP 請求並接收 XML 格式的信息。
我有一個 EditExt 在其中插入名稱並使用提交按鈕請求..
public class MainActivity extends AppCompatActivity {
//Variabili layout
TextView result_text;
EditText person_name;
Button conf;
//url site
String url="";
ProgressDialog progress=null;
ConnectivityManager connMgr;
NetworkInfo networkInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
conf=(Button)findViewById(R.id.button_conf);
person_name=(EditText)findViewById(R.id.editText);
result=(TextView)findViewById(R.id.textView_risultato);
connMgr=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
networkInfo= connMgr.getActiveNetworkInfo();
//Al click del bottne controllo che la editext non sia vuota e che ci sia connessione...
conf.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
url="";
url="http://remote.tesisrl.net/AlboUnicoServices/OttieniSoggetti?v=";
if (person_name.getText().toString().equals("")){
person_name.setError("Insert name");
//Se cè connessione lancio l'asyncktask
} else if (isNetworkAvailable()){
url=url+person_name.getText().toString();
new DownloadUrlTask().execute(url); // mando la richiesta al sito
}
else if (!isNetworkAvailable()){
//Mostro errore tramite toast
Toast.makeText(MainActivity.this,"Connessione Internet Assente",Toast.LENGTH_LONG).show();
}
}
});
}
private boolean isNetworkAvailable() {
//CONTROLLO CONNESSIONE INTERNET
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
//AsyncTask
private class DownloadUrlTask extends AsyncTask<String, Void,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
// aggiornamento UI
progress = ProgressDialog.show(MainActivity.this, "Richiesta",
"Attendere...", true);
}
@Override
protected String doInBackground(String... urls) {
//Il parametro proviene dalla chiamata execute(); params [0] e la url.
try{
return downloadPage(urls[0]); //lancio il metodo per la connessione
}catch (IOException e){
return "URL non valida";
}
}
// onPostExecute mostra il sirultato dell'AsyncTask
@Override
protected void onPostExecute(String result) {
// aggiornamento UI
progress.dismiss();
Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show();
restul_text.setText(result);
// Here i wont to parsing xml and insert the result in a listview
}
}
// metodo per la richiesta al webservice
private String downloadPage(String url1) throws IOException {
InputStream is=null;
String DEBUG_TAG="Debug_prova";
try {
URL url= new URL(url1);
HttpURLConnection conn =(HttpURLConnection)url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
//Instaurare connessione
conn.connect();
int response= conn.getResponseCode();
Log.d(DEBUG_TAG,"statuscode"+response);
String content= null;
is = conn.getInputStream();
if (response==200){
//Convertire l'InputStream in stringa
content= convertInputStreamToString(is);
}
return content;
// Assicurarsi che l'InputStream sia chiuso
}finally {
if (is!=null){
is.close();
}
}
}
//Convertire la richiesta in una stringa
private String convertInputStreamToString(InputStream is){
ByteArrayOutputStream baos= new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read;
try {
while ((read = is.read(buffer)) != -1){
baos.write(buffer, 0 , read);
}
}catch (IOException e){
e.printStackTrace();
}
return new String(baos.toByteArray());
}
在 asyncktask 的“OnPostExecute”方法中,我想對結果進行 xml 解析並將其添加到列表視圖中...
xml 結果的格式如下:
<ArrayOfSoggetto xmlns="http://schemas.datacontract.org/2004/07/AlboUnicoWcf" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Soggetto> <CodiceFiscale>PRTBLD48D25B007W</CodiceFiscale> <Cognome>PIEROTTI</Cognome> <Eliminato>false</Eliminato> <Esterno>true</Esterno> <IDSoggetto>6563</IDSoggetto> <Nome>UBALDO</Nome> <NomeCompleto>PIEROTTI UBALDO</NomeCompleto> <TipoSoggetto>108</TipoSoggetto> <TipoSoggettoEtichetta>Professionista</TipoSoggettoEtichetta> </Soggetto> </ArrayOfSoggetto>
任何人都知道如何解析文件/ xml 結果並將其放入列表視圖中?
對不起我的英語=)
在您的項目中創建一個XMLParser.java
類。
該類調用一個 url 來獲取 xml 數據。該類將具有以下三個方法。
方法一
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;
}
現在您需要解析返回的 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 "";
}
現在已經創建了所有這些,您需要使用這些函數來解析 xml 並設置列表適配器。
xml 結構如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<menu>
<item>
<id>1</id>
<name>Margherita</name>
<cost>155</cost>
<description>Single cheese topping</description>
</item>
<item>
<id>2</id>
<name>Double Cheese Margherita</name>
<cost>225</cost>
<description>Loaded with Extra Cheese</description>
</item>
</menu>
最后,您需要創建一個列表視圖並提供 xml 數據
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "someurl.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
}
});
}
}
希望對你有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.