java.lang.NullPointerException xml解析

标签 java android xml parsing nullpointerexception

这段代码应该解析 xml 并显示它!但它有异常(exception):

02-02 12:36:49.508: I/Choreographer(1184): Skipped 32 frames! The application may be doing too much work on its main thread. 02-02 12:36:50.926: W/System.err(1184): java.lang.NullPointerException 02-02 12:36:50.926: W/System.err(1184): at com.example.sample.itcuties.android.reader.ITCutiesReaderAppActivity.onCreate(ITCutiesReaderAppActivity.java:52) 02-02 12:36:50.946: W/System.err(1184): at android.app.Activity.performCreate(Activity.java:5008) 02-02 12:36:50.946: W/System.err(1184): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 02-02 12:36:50.946: W/System.err(1184): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 02-02 12:36:50.966: W/System.err(1184): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 02-02 12:36:50.966: W/System.err(1184): at android.app.ActivityThread.access$600(ActivityThread.java:130) 02-02 12:36:50.986: W/System.err(1184): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 02-02 12:36:50.986: W/System.err(1184): at android.os.Handler.dispatchMessage(Handler.java:99) 02-02 12:36:50.998: W/System.err(1184): at android.os.Looper.loop(Looper.java:137) 02-02 12:36:51.006: W/System.err(1184): at android.app.ActivityThread.main(ActivityThread.java:4745) 02-02 12:36:51.018: W/System.err(1184): at java.lang.reflect.Method.invokeNative(Native Method) 02-02 12:36:51.026: W/System.err(1184): at java.lang.reflect.Method.invoke(Method.java:511) 02-02 12:36:51.026: W/System.err(1184): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 02-02 12:36:51.036: W/System.err(1184): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 02-02 12:36:51.036: W/System.err(1184): at dalvik.system.NativeStart.main(Native Method) 02-02 12:36:51.046: I/System.out(1184): xml activity Excpetion = java.lang.NullPointerException 02-02 12:36:51.736: I/Choreographer(1184): Skipped 39 frames! The application may be doing too much work on its main thread. 02-02 12:36:53.596: D/dalvikvm(1184): GC_CONCURRENT freed 180K, 4% free 8234K/8519K, paused 96ms+114ms, total 356ms

找不到原因!!!

package com.example.sample.itcuties.android.reader;


import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;


/**
 * Main application activity.
 * 
 * @author ITCuties
 *
 */
public class ITCutiesReaderAppActivity extends Activity {
    NodeList nodeList;
    /** 
     * This method creates main application view
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set view

        try{


        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.HORIZONTAL);
         /** Create a new textview array to display the results */
        TextView name[];
        TextView website[];
        TextView category[];

        LongOperation lOp = new LongOperation(this);
        lOp.execute("");

         if(nodeList.getLength() > 0)
         {
             name = new TextView[nodeList.getLength()];
            website = new TextView[nodeList.getLength()];
            category = new TextView[nodeList.getLength()];

            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);

                name[i] = new TextView(this);
                website[i] = new TextView(this);
                category[i] = new TextView(this);

                Element fstElmnt = (Element) node;
                NodeList nameList = fstElmnt.getElementsByTagName("name");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();
                name[i].setText("Name = " + ((Node) nameList.item(0)).getNodeValue());

                NodeList websiteList = fstElmnt.getElementsByTagName("website");
                Element websiteElement = (Element) websiteList.item(0);
                websiteList = websiteElement.getChildNodes();
                website[i].setText("Website = " + ((Node) websiteList.item(0)).getNodeValue());

                category[i].setText("Website Category = " + websiteElement.getAttribute("category"));

                layout.addView(name[i]);
                layout.addView(website[i]);
                layout.addView(category[i]);
            }


         }

    /** Set the layout view to display */
            setContentView(layout);

         } catch (Exception e) {
             System.out.println("xml activity Excpetion = " + e);
         }
    }
     private class LongOperation extends AsyncTask<String, Void, String> {

         Context LongOperation;

            public LongOperation(Context context){
                   this.LongOperation = context;
                 }
            @Override
            protected String doInBackground(String... params) {


                try {

                    URL url = new URL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    Document doc = db.parse(new InputSource(url.openStream()));
                    doc.getDocumentElement().normalize();

                    nodeList = doc.getElementsByTagName("item");

                } catch (Exception e) {
                    System.out.println("XML Pasing Excpetion = " + e);
                }


                return null;
            }        

            @Override
            protected void onPostExecute(String result) {             
            }

            @Override
            protected void onPreExecute() {
            }

            @Override
            protected void onProgressUpdate(Void... values) {
            }
        }

}

最佳答案

LongOperation lOp = new LongOperation(this); lOp.execute(""); 

从这一行来看,您似乎正在将 nodeList 填充到 AsyncTask 中,但您不是等待它被填充,而是立即开始解析它。确保从 LongOperation 中的 onPostExecuted 开始解析。

顺便说一句,在后台进行解析也不是一个坏主意。

关于java.lang.NullPointerException xml解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21508739/

相关文章:

java - Spring/JTA/JPA 单元测试 : Rollback not working

java - Quarkus 中的 JAX-RS 子资源问题

java - 使用 Dagger 2 的自定义注解拦截器

android - 调试 Java InterruptedException 即找到原因

sql - SQL中查询XML有LIKE子句吗

c# - 不需要的命名空间属性添加到根子元素

java - 元素 "xsd"的前缀 "xsd:element"未绑定(bind)。 [11]

android - 以编程方式将借记卡或信用卡添加到 Google 电子钱包

php - 无法在 PHP 中将数据库获取到对象内的数组

Java/Android - https 在 apache http 中不工作