【问题标题】:Android:Xml Parsing安卓:XML解析
【发布时间】:2013-04-12 17:29:48
【问题描述】:

我正在尝试解析一个 xml 文件。我搜索了很多,最后找到了一些与此相关的教程。我编写了自己的代码,但我现在遇到了问题。当我启动功能时(通过更改单选按钮:我得到错误。你能帮我解决我的错误吗?

这是我的代码:

public class Download_database extends Activity {
    static String URL = "http://ganjoor.sourceforge.net/newgdbs.xml";
    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
      XMLParser parser = new XMLParser();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_download_database);
        RadioGroup download_section_group=(RadioGroup)findViewById(R.id.download_section_grop);
        RadioButton newgdb=(RadioButton)findViewById(R.id.radio_newgdb);
        RadioButton sitegdb=(RadioButton)findViewById(R.id.radio_sitegdb);
        RadioButton programgdb=(RadioButton)findViewById(R.id.radio_programgdb);
        download_section_group.check(R.id.radio_newgdb);
        final TextView hint=(TextView)findViewById(R.id.txt_download_db_hint);
        TabHost tabs=(TabHost)findViewById(R.id.download_cat_tabhost);
        tabs.setup();
        TabHost.TabSpec spec=tabs.newTabSpec("down_tag1");
        spec.setContent(R.id.download_cat_01);
        spec.setIndicator(getString(R.string.txt_download_tab_download_sections));
        tabs.addTab(spec);
        spec=tabs.newTabSpec("down_tag2");
        spec.setContent(R.id.download_cat_02);
        spec.setIndicator(getString(R.string.txt_download_tab_download_list));
        tabs.addTab(spec);



        download_section_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {

                if(R.id.radio_newgdb== arg1){
                    hint.setText(getString(R.string.txt_download_hint_newgdb));
                    URL = "http://ganjoor.sourceforge.net/newgdbs.xml";
                    xmlp(URL);
                }

                if(R.id.radio_sitegdb== arg1){
                    hint.setText(getString(R.string.txt_download_hint_sitedb));
                    URL = "http://ganjoor.sourceforge.net/sitegdbs.xml";
                    xmlp(URL);

                }

                if(R.id.radio_programgdb== arg1){
                    hint.setText(getString(R.string.txt_download_hint_programgdb));
                    URL = "http://ganjoor.sourceforge.net/programgdbs.xml";
                    xmlp(URL);
                }

            }
        });





        if(isOnline()){


        }
        else{
            Toast.makeText(this, "you are not connected to internet..Please check your connections", 1).show();
        }
    }


    private void xmlp(String url){
        Log.i(URL, "call xmlp");
        String xml = parser.getXmlFromUrl(url); // getting XML

        Log.i("getting DOM element", "getting DOM element");
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(parser.KEY_gdb);
        // 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(parser.KEY_CatName, parser.getValue(e, parser.KEY_CatName));
            map.put(parser.KEY_PoetID, parser.getValue(e, parser.KEY_PoetID));
            map.put(parser.KEY_DownloadUrl, parser.getValue(e, parser.KEY_DownloadUrl));
            map.put(parser.KEY_PubDate, parser.getValue(e, parser.KEY_PubDate));
            map.put(parser.KEY_FileSizeInByte,"Size:"+ parser.getValue(e,parser.KEY_FileSizeInByte));
            // adding HashList to ArrayList
            menuItems.add(map);
            ListView list=(ListView)findViewById(R.id.database_list);
            ListAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.list_item,new String[] {parser.KEY_CatName,parser.KEY_PoetID, parser.KEY_DownloadUrl ,parser.KEY_PubDate,parser.KEY_FileSizeInByte}, new int[] {
                            R.id.chk_database_list_item, R.id.txt_database_poet_id, R.id.txt_database_download_link,R.id.txt_database_pub_date,R.id.txt_database_size });
            list.setAdapter(adapter);
        }
    }

这是我的XMLParser 课程:

package co.tosca.persianpoem;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
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 org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {
    // XML node keys
    public static final String KEY_gdb = "gdb"; // parent node
    public static final String KEY_CatName = "CatName";
    public static final String KEY_PoetID = "PoetID";
    public static final String KEY_DownloadUrl = "DownloadUrl";
    public static final String KEY_FileSizeInByte = "FileSizeInByte";
    public static final String KEY_PubDate = "PubDate";
    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;
    }

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

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

}

终于报错了:

04-12 21:35:08.822: I/http://ganjoor.sourceforge.net/sitegdbs.xml(2460): call xmlp
04-12 21:35:08.872: D/AndroidRuntime(2460): Shutting down VM
04-12 21:35:08.872: W/dalvikvm(2460): threadid=1: thread exiting with uncaught exception (group=0x2b542210)
04-12 21:35:08.902: E/AndroidRuntime(2460): FATAL EXCEPTION: main
04-12 21:35:08.902: E/AndroidRuntime(2460): android.os.NetworkOnMainThreadException
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1108)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:580)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:512)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:490)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at co.tosca.persianpoem.XMLParser.getXmlFromUrl(XMLParser.java:42)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at co.tosca.persianpoem.Download_database.xmlp(Download_database.java:123)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at co.tosca.persianpoem.Download_database.access$0(Download_database.java:121)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at co.tosca.persianpoem.Download_database$1.onCheckedChanged(Download_database.java:94)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.widget.RadioGroup.setCheckedId(RadioGroup.java:172)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.widget.RadioGroup.access$600(RadioGroup.java:52)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.widget.RadioGroup$CheckedStateTracker.onCheckedChanged(RadioGroup.java:342)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.widget.CompoundButton.setChecked(CompoundButton.java:132)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.widget.CompoundButton.toggle(CompoundButton.java:91)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.widget.RadioButton.toggle(RadioButton.java:81)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.widget.CompoundButton.performClick(CompoundButton.java:103)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.view.View$PerformClick.run(View.java:14263)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.os.Handler.handleCallback(Handler.java:605)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.os.Looper.loop(Looper.java:137)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at android.app.ActivityThread.main(ActivityThread.java:4441)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at java.lang.reflect.Method.invokeNative(Native Method)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at java.lang.reflect.Method.invoke(Method.java:511)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-12 21:35:08.902: E/AndroidRuntime(2460):     at dalvik.system.NativeStart.main(Native Method)

这是我的权限:

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET" /> 

我尝试使用包含这些 xml 文件之一的字符串作为 xml(发现连接到 Internet 或解析 xml 有问题吗?)但也出现错误,这是我在使用预定义字符串时的 logcat xml

    04-12 21:33:24.032: I/http://ganjoor.sourceforge.net/sitegdbs.xml(1972): call xmlp
    04-12 21:33:24.032: I/getting DOM element(1972): getting DOM element
    04-12 21:33:24.072: D/AndroidRuntime(1972): Shutting down VM
    04-12 21:33:24.072: W/dalvikvm(1972): threadid=1: thread exiting with uncaught exception (group=0x2b542210)
    04-12 21:33:24.082: E/AndroidRuntime(1972): FATAL EXCEPTION: main
    04-12 21:33:24.082: E/AndroidRuntime(1972): java.lang.NullPointerException
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at co.tosca.persianpoem.Download_database.xmlp(Download_database.java:190)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at co.tosca.persianpoem.Download_database.access$0(Download_database.java:121)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at co.tosca.persianpoem.Download_database$1.onCheckedChanged(Download_database.java:94)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.widget.RadioGroup.setCheckedId(RadioGroup.java:172)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.widget.RadioGroup.access$600(RadioGroup.java:52)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.widget.RadioGroup$CheckedStateTracker.onCheckedChanged(RadioGroup.java:342)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.widget.CompoundButton.setChecked(CompoundButton.java:132)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.widget.CompoundButton.toggle(CompoundButton.java:91)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.widget.RadioButton.toggle(RadioButton.java:81)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.widget.CompoundButton.performClick(CompoundButton.java:103)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.view.View$PerformClick.run(View.java:14263)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.os.Handler.handleCallback(Handler.java:605)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.os.Handler.dispatchMessage(Handler.java:92)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.os.Looper.loop(Looper.java:137)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at android.app.ActivityThread.main
(ActivityThread.java:4441)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at java.lang.reflect.Method.invokeNative(Native Method)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at java.lang.reflect.Method.invoke(Method.java:511)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    04-12 21:33:24.082: E/AndroidRuntime(1972):     at dalvik.system.NativeStart.main(Native Method)

编辑:感谢所有帮助我的朋友..不,我认为我解决了我的一个问题 我在 downloadxml 函数中添加了一个AsyncTask,但我没有再遇到网络错误。这是我的新下载 xml 函数

   public class getxml extends AsyncTask<String, Void,String>{

        @Override
        protected String doInBackground(String... url) {

            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url[0]);

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

            Log.i("getxml", xml);
            return xml;
        }

    }

但现在我有一个NullPointerException 但找不到它发生的原因..我必须如何找到它的原因?

编辑:我尝试了很多来修复 nullexeption 错误,但找不到它的原因。 这是我的代码:

  private void xmlp(String url){
        Log.i(URL, "call xmlp");
        //String xml = parser.getXmlFromUrl(url); // getting XML old way


        new getxml().execute(url);// getting XML new way
        Log.i("xml Content", xml);
        try{
        Document doc = parser.getDomElement(xml); // getting DOM element
        NodeList nl = doc.getElementsByTagName(parser.KEY_gdb);
        // 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(parser.KEY_CatName, parser.getValue(e, parser.KEY_CatName));
            map.put(parser.KEY_PoetID, parser.getValue(e, parser.KEY_PoetID));
            map.put(parser.KEY_DownloadUrl, parser.getValue(e, parser.KEY_DownloadUrl));
            map.put(parser.KEY_PubDate, parser.getValue(e, parser.KEY_PubDate));
            map.put(parser.KEY_FileSizeInByte,"Size:"+ parser.getValue(e,parser.KEY_FileSizeInByte));
            // adding HashList to ArrayList
            menuItems.add(map);

        }
        Log.i("menuItems", menuItems.toString());
        ListView list=(ListView)findViewById(R.id.database_list);
        ListAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.database_list_item,new String[] {parser.KEY_CatName}, new int[] {
                R.id.chk_database_list_item });

      list.setAdapter(adapter);

}
catch (NullPointerException ex){
    Log.i("NullPointerException", ex.getMessage());
  }
    }

我收到了这个错误

    04-13 12:21:50.372: I/menuItems(3295): [{DownloadUrl=http://sourceforge.net/projects/ganjoor/files/gdb/abvsEid-abvalkhir.zip, PubDate=2011-09-24, FileSizeInByte=Size:123331, CatName=ابوسعيد ابوالخير, PoetID=26}, {DownloadUrl=http://sourceforge.net/projects/ganjoor/files/gdb/asdi-tvsi.zip, PubDate=2012-05-05, FileSizeInByte=Size:559711, CatName=اسدي توسي, PoetID=52}, {DownloadUrl=http://sourceforge.net/projects/ganjoor/files/gdb/aghbal-lahvri.zip, PubDate=2011-09-24, FileSizeInByte=Size:551922, CatName=اقبال لاهوري, PoetID=42}, {DownloadUrl=http://sourceforge.net/projects/ganjoor/files/gdb/amirkhsrv-dhlvi.zip, PubDate=2011-09-24, FileSizeInByte=Size:505209, CatName=اميرخسرو دهلوي, PoetID=34}, {DownloadUrl=http://sourceforge.net/projects/ganjoor/files/gdb/anvri.zip, PubDate=2011-09-24, FileSizeInByte=Size:902760, CatName=انوري, PoetID=18}, {DownloadUrl=http://sourceforge.net/projects/ganjoor/files/gdb/avhdi.zip, PubDate=2011-09-24, FileSizeInByte=Size:991556, CatName=اوحدي, PoetID=19}, {DownloadUrl=http://sourceforge.net/projects/ganjoor/files/gdb/babatahr.zip, PubDate=2011-09-24, FileSizeInByte=Size:60641, CatName=باباطاهر, PoetID=28}, {DownloadUrl=http://sourceforge.net/projects/ganjoor/files/gdb/bidl-dhlvi.zip, PubDate=2011-09-24, FileSizeInByte=Size:2406463, CatName=بيدل دهلوي, PoetID=43}]
04-13 12:13:06.912: D/AndroidRuntime(3149): Shutting down VM
04-13 12:13:06.912: W/dalvikvm(3149): threadid=1: thread exiting with uncaught exception (group=0x2b542210)
04-13 12:13:06.912: E/AndroidRuntime(3149): FATAL EXCEPTION: main
04-13 12:13:06.912: E/AndroidRuntime(3149): java.lang.NullPointerException
04-13 12:13:06.912: E/AndroidRuntime(3149):     at co.tosca.persianpoem.Download_database.xmlp(Download_database.java:258)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at co.tosca.persianpoem.Download_database.access$0(Download_database.java:132)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at co.tosca.persianpoem.Download_database$1.onCheckedChanged(Download_database.java:104)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.widget.RadioGroup.setCheckedId(RadioGroup.java:172)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.widget.RadioGroup.access$600(RadioGroup.java:52)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.widget.RadioGroup$CheckedStateTracker.onCheckedChanged(RadioGroup.java:342)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.widget.CompoundButton.setChecked(CompoundButton.java:132)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.widget.CompoundButton.toggle(CompoundButton.java:91)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.widget.RadioButton.toggle(RadioButton.java:81)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.widget.CompoundButton.performClick(CompoundButton.java:103)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.view.View$PerformClick.run(View.java:14263)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.os.Handler.handleCallback(Handler.java:605)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.os.Looper.loop(Looper.java:137)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at android.app.ActivityThread.main(ActivityThread.java:4441)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at java.lang.reflect.Method.invokeNative(Native Method)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at java.lang.reflect.Method.invoke(Method.java:511)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-13 12:13:06.912: E/AndroidRuntime(3149):     at dalvik.system.NativeStart.main(Native Method)

如您所见,我记录了 menuItems 并且从 xml 读取的接缝没有任何问题..我认为问题出在我的列表适配器中 :( 我收到错误的行是 258,其中包含 list.setAdapter(adapter); 我检查了我的自定义列表布局但找不到任何东西,所以我在这里发布了我的自定义布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <CheckBox
            android:id="@+id/chk_database_list_item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="start"
            android:text="CheckBox" />

        <TextView
            android:id="@+id/txt_database_size"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center_vertical|end"
            android:text="TextView" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/txt_database_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <TextView
            android:id="@+id/txt_database_pub_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:text="TextView" />

        <TextView
            android:id="@+id/txt_database_download_link"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <TextView
            android:id="@+id/txt_database_poet_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />

    </LinearLayout>

</LinearLayout>

有趣的是,当我将这些行添加到我的函数中时

catch (NullPointerException ex){
    Log.i("NullPointerException", ex.getMessage());
  }

我收到了这个新错误

04-13 12:21:50.372: W/dalvikvm(3295): threadid=1: thread exiting with uncaught exception (group=0x2b542210)
04-13 12:21:50.382: E/AndroidRuntime(3295): FATAL EXCEPTION: main
04-13 12:21:50.382: E/AndroidRuntime(3295): java.lang.NullPointerException: println needs a message
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.util.Log.println_native(Native Method)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.util.Log.i(Log.java:159)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at co.tosca.persianpoem.Download_database.xmlp(Download_database.java:263)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at co.tosca.persianpoem.Download_database.access$0(Download_database.java:132)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at co.tosca.persianpoem.Download_database$1.onCheckedChanged(Download_database.java:112)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.widget.RadioGroup.setCheckedId(RadioGroup.java:172)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.widget.RadioGroup.access$600(RadioGroup.java:52)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.widget.RadioGroup$CheckedStateTracker.onCheckedChanged(RadioGroup.java:342)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.widget.CompoundButton.setChecked(CompoundButton.java:132)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.widget.CompoundButton.toggle(CompoundButton.java:91)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.widget.RadioButton.toggle(RadioButton.java:81)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.widget.CompoundButton.performClick(CompoundButton.java:103)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.view.View$PerformClick.run(View.java:14263)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.os.Handler.handleCallback(Handler.java:605)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.os.Looper.loop(Looper.java:137)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at android.app.ActivityThread.main(ActivityThread.java:4441)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at java.lang.reflect.Method.invokeNative(Native Method)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at java.lang.reflect.Method.invoke(Method.java:511)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-13 12:21:50.382: E/AndroidRuntime(3295):     at dalvik.system.NativeStart.main(Native Method)

第 263 行包含:

Log.i("NullPointerException", ex.getMessage());

【问题讨论】:

  • 这个问题已经被问过好几次了。看看这个duplicate thread
  • 实际上,问题不在于 XML 解析器的选择……但是。目前仍是AsyncTask 问题。
  • P.S. @Majid 我认为您使用 DOM 解析器而不是 SAX 做出了正确的选择。我通常认为最好从 DOM 开始(它更容易实现并且使用更少的代码),并且只在必须切换到 SAX 时才切换到 SAX,因为 XML 数据非常大或非常复杂、速度要求、大量数据的内存消耗,或者需要在从InputStream 解析结果时即时处理结果。

标签: android xml-parsing


【解决方案1】:

您不能在主 UI 线程中调用 onCheckedChanged() 中的 xmlp(URL);。您必须在不同的线程中运行此互联网呼叫。有很多方法可以做到这一点。最常见和最佳的做法是使用AsyncTask

【讨论】:

  • @DavidManpeal 非常感谢您的帮助。所以如果我使用 AsyncTask 我的问题会解决吗?如果我将这 3 个 xml 文件添加到 assest 文件夹中并使用它们会怎样?我可以这样做吗?跨度>
  • 如果您使用 AsyncTask,那么您的LogCat (NetworkOnMainThreadException) 中的第一个问题将得到修复。第 190 行发生的第二个问题 (NullPointerException) 与此无关。使用 XML String 进行测试是个好主意。因此,您还必须在第 190 行修复此 NullPointerException。第二个问题的答案是:是的 - 您可以从“资产”文件夹中读取 XML 文件,但您也应该使用 @987654329 @从那里阅读。先让String 解析工作,然后查找如何从“assets”文件夹中读取文件的示例。
  • 谢谢亲爱的大卫,我解决了我的第一个问题,但现在我仍然有 NullPointerException ..我必须再次在 AsyncTask 中运行 getDomElement(String xml) 函数吗?
  • 是的。你在正确的轨道上。现在你必须解决NullPointerException。您的LogCat 告诉您问题出在哪里Download_database.java:190,但现在行号将有所不同。您可以使用硬编码的 String 或来自 Internet 的值来测试 getDomElement()。您严重需要在方法xmlp() 中处理一些Exception
  • 感谢我的朋友您的精彩回答和您花费的时间..我会处理它并报告结果..再次感谢
【解决方案2】:

要处理来自getXmlFromUrl(String url) 发出网络请求的错误,您可以扩展AsyncTask 类以启动单独的线程。您只需将逻辑转移到 AsyncTask 类的 doInBackground(...) 方法,并使用 onPostExecute(...) 方法返回数据。可以在 Google 上找到示例。

【讨论】:

  • 再次感谢..我添加了一个 AsyncTask 并修复了我的网络错误,但现在我收到 NullPointerException 错误:(
  • 还在进步!如果您在看到 NPE 的地方发布代码并为异常指定行号,也许我自己或这里的某个人可以帮助您。
  • 感谢我的朋友,我用有关该错误的新信息更新了我的问题。
  • 最后我发现问题是因为 listview id 我删除了它并创建了一个新的并且它可以工作..非常感谢
  • 我认为之前遇到过这个问题。这是因为当使用 ListFragment 时,listView 需要 id 列表,例如。 android:id="@id/android:list
猜你喜欢
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多