Android,解析xml文件的问题

时间:2011-11-17 20:31:21

标签: android xml-parsing nullpointerexception saxparser

我正在尝试解析这个:xml's url
按照本教程Android XML Parsing Tutorial - Using SAXParser,我尝试修改源代码,但是我收到了下一个错误:

11-17 20:04:38.072: I/System.out(13247): Error: null
11-17 20:04:38.072: D/AndroidRuntime(13247): Shutting down VM
11-17 20:04:38.082: W/dalvikvm(13247): threadid=1: thread exiting with uncaught exception (group=0x409951f8)
11-17 20:04:38.122: E/AndroidRuntime(13247): FATAL EXCEPTION: main
11-17 20:04:38.122: E/AndroidRuntime(13247): java.lang.RuntimeException: Unable to start activity ComponentInfo{net.net46.sourcecode.android.lectorxml2/net.net46.sourcecode.android.lectorxml2.LectorXML2Activity}: java.lang.NullPointerException
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.app.ActivityThread.access$600(ActivityThread.java:122)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.os.Looper.loop(Looper.java:137)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.app.ActivityThread.main(ActivityThread.java:4340)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at java.lang.reflect.Method.invokeNative(Native Method)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at java.lang.reflect.Method.invoke(Method.java:511)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at dalvik.system.NativeStart.main(Native Method)
11-17 20:04:38.122: E/AndroidRuntime(13247): Caused by: java.lang.NullPointerException
11-17 20:04:38.122: E/AndroidRuntime(13247):    at net.net46.sourcecode.android.lectorxml2.LectorXML2Activity.onCreate(LectorXML2Activity.java:36)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.app.Activity.performCreate(Activity.java:4465)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-17 20:04:38.122: E/AndroidRuntime(13247):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
11-17 20:04:38.122: E/AndroidRuntime(13247):    ... 11 more

模拟器运行时,我的LogCat。原始tut中的三个修改后的源代码类现在是:LectorXML2Activity.java,Lista.java,LecturaXML.java,这里是代码:

//Lista.java
package net.net46.sourcecode.android.lectorxml2;
import java.util.ArrayList;
public class Lista {
private ArrayList<String> nombre = new ArrayList<String>();
private ArrayList<String> pagina = new ArrayList<String>();
private ArrayList<String> categoria = new ArrayList<String>();
public void setNombre(String nombre){
    this.nombre.add(nombre);
}
public ArrayList<String> getNombre(){
    return this.nombre;
}

public void setPagina(String pagina){
    this.pagina.add(pagina);
}   
public ArrayList<String> getPagina(){
    return this.pagina;
}

public void setCategoria(String categoria){
    this.categoria.add(categoria);
}
public ArrayList<String> getCategoria(){
    return this.categoria;
}
}


//LecturaXML.java
package net.net46.sourcecode.android.lectorxml2;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
public class LecturaXML extends DefaultHandler{
public static Lista lista = null;
private Boolean elementoActual;
private String valorActual = null;
@Override
public void startElement(String uri, String nombreLocal,
                         String qNombre, Attributes atributos)
throws SAXException{
    elementoActual = true;
    if(nombreLocal.equals("tecnologias")){
        lista = new Lista();
    }else if(nombreLocal.equals("pagina")){
        String attr = atributos.getValue("categoria");
        lista.setCategoria(attr);
    }
}   
@Override
public void endElement(String uri, String nombreLocal, String qNombre)
throws SAXException{
    elementoActual = false;
    if(nombreLocal.equalsIgnoreCase("nombre")){
        lista.setNombre(valorActual);
    }else if(nombreLocal.equalsIgnoreCase("pagina")){
        lista.setPagina(valorActual);
    }
}
@Override
public void characters(char[]ch, int inicio, int longitud)
throws SAXException{
    if(elementoActual){
        valorActual = new String(ch,inicio,longitud);
        elementoActual = false;
    }
}

public static Lista getLista(){
    return lista;
}
public static void setLista(Lista lista){
    LecturaXML.lista = lista;
}
}



//LectorXML2Activity.java
package net.net46.sourcecode.android.lectorxml2;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import net.net46.sourcecode.android.lectorxml2.R;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import java.net.URL;
public class LectorXML2Activity extends Activity{
Lista lista = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LinearLayout vista = new LinearLayout(this);
    vista.setOrientation(1);
    TextView[] nombre;
    TextView[] pagina;
    TextView[] categoria;
    try{
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        URL url = new URL("http://sourcecode.net46.net/android/xml/tecnologies.xml");
        LecturaXML lectura = new LecturaXML();
        xr.setContentHandler(lectura);
        xr.parse(new InputSource(url.openStream()));
    }catch(Exception e){
        System.out.println("Error: " + e.getMessage());
    }
    lista = LecturaXML.lista;
    nombre = new TextView[lista.getNombre().size()];
    pagina = new TextView[lista.getNombre().size()];
    categoria = new TextView[lista.getNombre().size()];
    for(int i=0;i<lista.getNombre().size();i++){
        nombre[i] = new TextView(this);
        nombre[i].setText("Nombre: "+lista.getNombre().get(i));
        pagina[i] = new TextView(this);
        pagina[i].setText("Pagina: "+lista.getPagina().get(i));
        categoria[i] = new TextView(this);
        categoria[i].setText("Categoría: "+lista.getCategoria().get(i));
        vista.addView(nombre[i]);
        vista.addView(pagina[i]);
        vista.addView(categoria[i]);
    }
    setContentView(vista);
}
}

//AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.net46.sourcecode.android.lectorxml2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="14" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:label="@string/app_name"
        android:name=".LectorXML2Activity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

那么,为了让它正常工作,我错过了什么?,如何解决NullPointerException问题? thnx提前..

1 个答案:

答案 0 :(得分:0)

您不会初始化其中任何一个:

public static Lista lista = null;
private String valorActual = null;

它们保持为null并导致空指针异常。您需要在使用它们之前初始化它们。以下可能会起作用:

public static Lista lista = new Lista();
private String valorActual = "";