簡體   English   中英

檢索XML文件時Android應用程序崩潰

[英]Android App Crashing While Retrieving XML File

我正在開發一個簡單的android應用程序,它將在textview中獲取並顯示xml數據。 以下是代碼。

try {
            t1 = (TextView)findViewById(R.id.textView2);
            URL url = new URL("http://www.sevenzaseo.com/androidapi.php");
            URLConnection conn = url.openConnection();

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(conn.getInputStream());

            NodeList nodes = doc.getElementsByTagName("socialinfo");
            for (int i = 0; i < nodes.getLength(); i++) {
                Element element = (Element) nodes.item(i);
                NodeList title = element.getElementsByTagName("facebooklikes");
                Element line = (Element) title.item(0);
                t1.setText(line.getTextContent());
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }

和XML文件:

<?xml version="1.0" encoding="utf-8"?><xml>
<socialinfo>
    <facebooklikes>420</facebooklikes>
    <twitterfollowers>12</twitterfollowers>
    <googleplusfollowers>121</googleplusfollowers>
    <linkedinfollowers>24</linkedinfollowers>
    <websiteviews>500</websiteviews>
</socialinfo>
</xml>

但是這些應用無法正常運行,並且無法獲取URL數據。 我將其定位在具有3G連接功能的三星Galaxy S3上,有人可以幫忙嗎?

您正在UI線程上使用網絡,將其刪除並使用異步任務

無法在主線程中進行網絡處理 因此,您需要使用AsyncTask 檢索doInBackground的數據(),最后在postExecute TextView的或其他顯示它() 嘗試使用的AsyncTask如下:

public class MyAsync extends AsyncTask<String, Void, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... args) {


        try {


            }
        } catch () {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(JSONObject url) {

        // updating UI from Background Thread for some case. you may remove this as well
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                //do something at last, may be display result to textview or use adapter
            }
        });
    }
}

您可能想看看這個這個

您無法在主線程(UI線程)中進行網絡處理Android絕對不允許您這樣做,因此您應該通過創建新線程來使用異步任務來執行此操作。

讀這個:

http://developer.android.com/reference/android/os/AsyncTask.html

使用此代碼代替您的代碼,它將解決您的問題

static final String URL = "http://www.sevenzaseo.com/androidapi.php";
    // XML node keys
    static final String KEY_TASK = "socialinfo"; // parent node
    static final String KEY_FACEBOOKLIKE = "facebooklikes";
    static final String KEY_TWITTERFOLL = "twitterfollowers";
    static final String KEY_GOODLEPLUS = "googleplusfollowers";
    static final String KEY_LINKEDIN = "linkedinfollowers";
    static final String KEY_WESITEVIEW = "websiteviews";


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_TASK);
            // looping through all task nodes <task>
            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_FACEBOOKLIKE, parser.getValue(e, KEY_FACEBOOKLIKE));
                map.put(KEY_TWITTERFOLL, parser.getValue(e, KEY_TWITTERFOLL));
                map.put(KEY_GOODLEPLUS,parser.getValue(e, KEY_GOODLEPLUS));
                map.put(KEY_LINKEDIN,"Linkined: " + parser.getValue(e, KEY_LINKEDIN));
                map.put(KEY_WESITEVIEW,"WebsiteCount: " + parser.getValue(e, KEY_WESITEVIEW));

                // adding HashList to ArrayList
                menuItems.add(map);
            }

在您的包文件夾中創建此類

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM