简体   繁体   English

Android中解析XML,放入ListView

[英]Parsing XML in Android, and put into ListView

I am creating an app that makes an HTTP request to a web service and receives information in XML format.我正在创建一个应用程序,它向 Web 服务发出 HTTP 请求并接收 XML 格式的信息。

I have a EditExt where I insert the name and using a submit button the request..我有一个 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());
}

in "OnPostExecute" method of asyncktask I want to do the xml parsing the result and add it to a list view...在 asyncktask 的“OnPostExecute”方法中,我想对结果进行 xml 解析并将其添加到列表视图中...

the xml result is formatted like this: 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>

Anyone know how to parse a file / xml result and put it in a listview?任何人都知道如何解析文件/ xml 结果并将其放入列表视图中?

Sorry for my english =)对不起我的英语=)

Create a class XMLParser.java in your project.在您的项目中创建一个XMLParser.java类。

This class calls a url to get the xml data.The class will have below three methods.该类调用一个 url 来获取 xml 数据。该类将具有以下三个方法。

Method1方法一

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;
    }

Now you would need to parse that returned xml to get elements现在您需要解析返回的 xml 以获取元素

Method2方法二

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;
    }

Once you have done that you need to get each child element value passing node name:完成后,您需要获取每个传递节点名称的子元素值:

Method3方法三

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 "";
  }

Now having created all these you need to use these functions to parse the xml and set list adapter.现在已经创建了所有这些,您需要使用这些函数来解析 xml 并设置列表适配器。

the xml structure looks like this: 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>

Finally you need to create a listview and feed the xml data最后,您需要创建一个列表视图并提供 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();


        }
    });
}
}

Hope it helps you.希望对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM