Android,解析 xml 文件的问题

发布于 2024-12-16 14:45:28 字数 7971 浏览 0 评论 0原文

我正在尝试解析此内容: xml 的 url
通过遵循本教程 Android XML 解析教程 - 使用 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。原始图特现在的三个修改后的源代码类是: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 问题?提前谢谢..

I'm trying to parse this: xml's url
By following this tutorial Android XML Parsing Tutorial - Using SAXParser, I tried to modify the source code but I get the next error:

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

Thats my LogCat when the emulator runs. The three modified source code classes from the original tut now are: LectorXML2Activity.java, Lista.java, LecturaXML.java, here's the code:

//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>

So, what am I missing to make it work properly?, how do I solve that NullPointerException issue? thnx in advance..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一梦等七年七年为一梦 2024-12-23 14:45:28

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

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

它们保持为空并导致空指针异常。在使用它们之前您需要对其进行初始化。例如,以下内容可能有效:

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

You don't initialize either of these:

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

They stay null and are causing you a null pointer exception. You need to initialize them before using them. The following could would work for example:

public static Lista lista = new Lista();
private String valorActual = "";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文