0

I am trying to parse an xml file. I searched a lot and finally found some tutorials abut this. I write my own code but I have a problem now. When I start function (by change radiobutton: I get error. Can you help me to fix my mistakes?

Here is my code:

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

and here is my XMLParser class:

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

}

finally error that I resive:

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)

Here Is my permissions:

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

I tried to use a String as xml that contains one of those xml files (to find that is there problem with connecting to internet or with parsing xml?) but get error too,Here Is my logcat while using an pre defined string 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)

Edit:Thanks to all friend that helped me..No I think I fixed one of my problems I added a AsyncTask to downloadxml function and I didnot get network error anymore..Here Is my new download xml function

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

    }

But now I have a NullPointerException But cant find why it is happening..How I must find its reason?

Edit:I tried a lot to fix nullexeption error but cant find Its reason. Here is my code:

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

I got this error

    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)

as you see I logged menuItems and It seams reading from xml has not any problem..I think problem Is in my list adapter :( The line which I get error Is 258 that contains list.setAdapter(adapter); I checked my custom list layout but cant find anything so I posted my customlayout here

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

An Intresting thing is when I added this lines to my function

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

I got this new error

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)

line 263 contains :

Log.i("NullPointerException", ex.getMessage());
Majid
  • 230
  • 1
  • 5
  • 20
  • This has been asked several times. Take a look at this [duplicate thread](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception). – Deepak Bala Apr 12 '13 at 17:42
  • Actually, the problem isn't choice of XML parser... yet. It is still an `AsyncTask` issue at this point. – David Manpearl Apr 12 '13 at 17:51
  • P.S. @Majid I think you made the right choice using a DOM parser instead of SAX. I usually think it is better to start with DOM (which is easier to implement and uses less code) and only switch to SAX if you have to because of extremely large or complicated XML data, speed requirements, memory consumption for lots of data, or the need to process results on-the-fly as they are being parsed from an `InputStream`. – David Manpearl Apr 12 '13 at 17:54

2 Answers2

1

You cannot call xmlp(URL); in onCheckedChanged() within your main UI thread. You must run this internet call in a different Thread. There are many ways to do this. The most common and best practice is to use an AsyncTask.

David Manpearl
  • 12,362
  • 8
  • 55
  • 72
  • @DavidManpeal Thanks a lot for your help..So If I use AsyncTask my problem will fixes?what If I add those 3 xml files in assest folder and use them?Can I do this? – Majid Apr 12 '13 at 18:19
  • If you use AsyncTask, then the first problem in your `LogCat` (`NetworkOnMainThreadException`) will be fixed. The second problem (`NullPointerException`) occurring on line 190 is unrelated. Your test with an XML `String` is a good idea. So, you also must fix this `NullPointerException` on line 190. The answer to your second question is: Yes - you can read XML files from your "assets" folder, but you also _should_ use `AsyncTask` to read from there. Get the `String` parsing working first and then look for examples of how to read files from the "assets" folder. – David Manpearl Apr 12 '13 at 18:29
  • Thanks dear David,I fixed my first prolem but now I still have NullPointerException ..Do I must run getDomElement(String xml) function in AsyncTask again? – Majid Apr 12 '13 at 19:10
  • Yes. You are on the right track. Now you must solve the `NullPointerException`. Your `LogCat` tells you where the problem is `Download_database.java:190`, but the line number will now be different. You can test `getDomElement()` with hardcoded `String` or value from Internet. You *SERIOUSLY* need some `Exception` handling in the method `xmlp()`. – David Manpearl Apr 12 '13 at 19:22
  • Thanks My friend for your great answers and time which you spend ..I will work on It and report the result..Thanks again – Majid Apr 12 '13 at 20:00
  • Hello,Finally I found my problem is with list adapter..But dont know where am I wrong..I updated my question ..Can you take a look at it?Thanks – Majid Apr 13 '13 at 09:40
  • Thanks my friend I find a solution.. and now I can parse xml file :) – Majid Apr 13 '13 at 13:11
1

To handle the error from getXmlFromUrl(String url) making a network request you can extend the AsyncTask class to start a separate Thread. You would simple transfer your logic to the doInBackground(...) method of the AsyncTask class and return the data using the onPostExecute(...) method. Example can be found on Google.

drunkenRabbit
  • 394
  • 5
  • 15
  • Thanks again..I added an AsyncTask and my network error fixed but now I got NullPointerException error:( – Majid Apr 12 '13 at 19:09
  • Still progress! If you post the code where you are seeing the NPE and specify line numbers for the exception, maybe myself or someone here can assist you. – drunkenRabbit Apr 12 '13 at 20:22
  • Thanks my friend I updated my question with new information about that error. – Majid Apr 13 '13 at 08:20
  • Finally I find that problem is because of listview id I deleted it and creat a new one and It works..Thanks a lot – Majid Apr 13 '13 at 13:10
  • I think encountered that problem before. It's because when using a ListFragment the listView needs id list eg. `android:id="@id/android:list` – drunkenRabbit Apr 13 '13 at 21:49
  • I don't know but When I replaced listview with a new one it fixed..Anyway thanks a lot for your helps – Majid Apr 14 '13 at 05:40