【问题标题】:Parsing XML in Android, and put into ListView在Android中解析XML,并放入ListView
【发布时间】:2016-08-13 08:30:30
【问题描述】:

我正在创建一个应用程序,该应用程序向 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结果并将其放入列表视图中吗?

对不起我的英语 =)

【问题讨论】:

标签: java android listview android-studio xml-parsing


【解决方案1】:

在您的项目中创建一个类XMLParser.java

这个类调用一个url来获取xml数据。这个类将有以下三个方法。

方法1

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 以获取元素

方法2

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

完成后,您需要获取传递节点名称的每个子元素值:

方法3

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();


        }
    });
}
}

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    相关资源
    最近更新 更多