2

I am making an android app and in that firstly I saved the XML on sdcard from web and its getting successfully saved then after trying to parse that XML but getting Run time Error. I have added my LogCat below.

This is my code,

protected String doInBackground(String... params) 
    {
        // TODO Auto-generated method stub

        try {               

            URL url = new URL(data);

            stringList=new ArrayList<String>();
            stringList1=new ArrayList<String>();

            //create the new connection

            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            //set up some things on the connection

            urlConnection.setRequestMethod("GET");

            urlConnection.setDoOutput(true);

            //and connect!

            urlConnection.connect();

            //set the path where we want to save the file

            //in this case, going to save it on the root directory of the

            //sd card.

            File SDCardRoot = new File("/sdcard/");

            //create a new file, specifying the path, and the filename

            //which we want to save the file as.

            File file = new File(SDCardRoot,"hello.xml");

            //this will be used to write the downloaded data into the file we created

            FileOutputStream fileOutput = new FileOutputStream(file);

            //this will be used in reading the data from the internet

            InputStream inputStream = urlConnection.getInputStream();

            //this is the total size of the file

            int totalSize = urlConnection.getContentLength();

            //variable to store total downloaded bytes

            int downloadedSize = 0;

            //create a buffer...

            byte[] buffer = new byte[1024];

            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file

            while ( (bufferLength = inputStream.read(buffer)) > 0 ) 

            {

            //add the data in the buffer to the file in the file output stream (the file on the sd card

            fileOutput.write(buffer, 0, bufferLength);

            //add up the size so we know how much is downloaded

            downloadedSize += bufferLength;

            int progress=(int)(downloadedSize*100/totalSize);

            //this is where you would do something to report the prgress, like this maybe

            //updateProgress(downloadedSize, totalSize);

            }

            //close the output stream when done

            fileOutput.close();

            InputStream is = new FileInputStream(file.getPath());
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(is));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("Table");

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

                Element fstElmnt = (Element) node;
                NodeList nameList = fstElmnt.getElementsByTagName("State");
                Element nameElement = (Element) nameList.item(0);
                nameList = nameElement.getChildNodes();
                state=((Node) nameList.item(0)).getNodeValue();

                Element fstElmnt1 = (Element) node;
                NodeList nameList1 = fstElmnt1.getElementsByTagName("District");
                Element nameElement1 = (Element) nameList1.item(0);
                nameList1 = nameElement1.getChildNodes();
                district=((Node) nameList1.item(0)).getNodeValue();

                if(!stringList.contains(state) && !stringList1.contains(district))
                {
                    stringList.add(state);
                    stringList1.add(district);
                    DatabaseHandler mydb = new DatabaseHandler(getApplicationContext());
                    // inserting new label into database
                    mydb.insertData(state,district);
                    //mydb.close();
                }
                //System.out.println("State : "+((Node) nameList.item(0)).getNodeValue());
           }

            loadStateSpinnerData();
            loadDistrictSpinnerData();

        } 
        catch (MalformedURLException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getBaseContext(), "No Internet Connection!", Toast.LENGTH_LONG).show();
        } 
        catch (ParserConfigurationException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (SAXException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }

And my LogCat,

10-23 13:02:49.059: E/AndroidRuntime(8678): FATAL EXCEPTION: AsyncTask #1
10-23 13:02:49.059: E/AndroidRuntime(8678): java.lang.RuntimeException: An error occured while executing doInBackground()
10-23 13:02:49.059: E/AndroidRuntime(8678):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at java.lang.Thread.run(Thread.java:1019)
10-23 13:02:49.059: E/AndroidRuntime(8678): Caused by: java.lang.ClassCastException: org.apache.harmony.xml.dom.TextImpl
10-23 13:02:49.059: E/AndroidRuntime(8678):     at com.example.androidspinnerfromsqlite.AndroidSpinnerFromSQLiteActivity$XmlParsing.doInBackground(AndroidSpinnerFromSQLiteActivity.java:190)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at com.example.androidspinnerfromsqlite.AndroidSpinnerFromSQLiteActivity$XmlParsing.doInBackground(AndroidSpinnerFromSQLiteActivity.java:1)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-23 13:02:49.059: E/AndroidRuntime(8678):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
10-23 13:02:49.059: E/AndroidRuntime(8678):     ... 4 more
10-23 13:02:56.189: E/WindowManager(8678): Activity com.example.androidspinnerfromsqlite.AndroidSpinnerFromSQLiteActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405233a8 that was originally added here
10-23 13:02:56.189: E/WindowManager(8678): android.view.WindowLeaked: Activity com.example.androidspinnerfromsqlite.AndroidSpinnerFromSQLiteActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405233a8 that was originally added here
10-23 13:02:56.189: E/WindowManager(8678):  at android.view.ViewRoot.<init>(ViewRoot.java:263)
10-23 13:02:56.189: E/WindowManager(8678):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
10-23 13:02:56.189: E/WindowManager(8678):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-23 13:02:56.189: E/WindowManager(8678):  at android.view.Window$LocalWindowManager.addView(Window.java:424)
10-23 13:02:56.189: E/WindowManager(8678):  at android.app.Dialog.show(Dialog.java:241)
10-23 13:02:56.189: E/WindowManager(8678):  at android.app.ProgressDialog.show(ProgressDialog.java:107)
10-23 13:02:56.189: E/WindowManager(8678):  at android.app.ProgressDialog.show(ProgressDialog.java:90)
10-23 13:02:56.189: E/WindowManager(8678):  at com.example.androidspinnerfromsqlite.AndroidSpinnerFromSQLiteActivity$XmlParsing.onPreExecute(AndroidSpinnerFromSQLiteActivity.java:78)
10-23 13:02:56.189: E/WindowManager(8678):  at android.os.AsyncTask.execute(AsyncTask.java:391)
10-23 13:02:56.189: E/WindowManager(8678):  at com.example.androidspinnerfromsqlite.AndroidSpinnerFromSQLiteActivity.onCreate(AndroidSpinnerFromSQLiteActivity.java:57)
10-23 13:02:56.189: E/WindowManager(8678):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
10-23 13:02:56.189: E/WindowManager(8678):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
10-23 13:02:56.189: E/WindowManager(8678):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
10-23 13:02:56.189: E/WindowManager(8678):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
10-23 13:02:56.189: E/WindowManager(8678):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
10-23 13:02:56.189: E/WindowManager(8678):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 13:02:56.189: E/WindowManager(8678):  at android.os.Looper.loop(Looper.java:130)
10-23 13:02:56.189: E/WindowManager(8678):  at android.app.ActivityThread.main(ActivityThread.java:3687)
10-23 13:02:56.189: E/WindowManager(8678):  at java.lang.reflect.Method.invokeNative(Native Method)
10-23 13:02:56.189: E/WindowManager(8678):  at java.lang.reflect.Method.invoke(Method.java:507)
10-23 13:02:56.189: E/WindowManager(8678):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
10-23 13:02:56.189: E/WindowManager(8678):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
10-23 13:02:56.189: E/WindowManager(8678):  at dalvik.system.NativeStart.main(Native Method)

Don't know exactly where's the error coming.

Please help.

Thanks.

11
  • whats at this line number 200 Commented Oct 23, 2013 at 7:53
  • @Shiv please post your onPost and onPre codes Commented Oct 23, 2013 at 7:53
  • @DharaShah: mydb.insertData(state,district); Commented Oct 23, 2013 at 7:55
  • @SathishKumar: protected void onPostExecute(String result) { if (pDialog.isShowing()) pDialog.dismiss(); } And my prepost.. protected void onPreExecute() { pDialog = ProgressDialog.show(AndroidSpinnerFromSQLiteActivity.this, "Fetching Details..", "Please wait...", true); } Commented Oct 23, 2013 at 7:57
  • 2
    What's on the line 190 of your AndroidSpinnerFromSQLiteActivity? Commented Oct 23, 2013 at 8:06

2 Answers 2

2

Try this:

runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            loadStateSpinnerData();
                            loadDistrictSpinnerData();
                        }
                    });

Change this:

if(!stringList.contains(state) && !stringList1.contains(district))
                {
                    stringList.add(state);
                    stringList1.add(district);
                    DatabaseHandler mydb = new DatabaseHandler(getApplicationContext());
                    // inserting new label into database
                    mydb.insertData(state,district);
                    //mydb.close();
                }

to

if(!stringList.contains(state) || !stringList1.contains(district))
                {
                    stringList.add(state);
                    stringList1.add(district);
                    DatabaseHandler mydb = new DatabaseHandler(getApplicationContext());
                    // inserting new label into database
                    mydb.insertData(state,district);
                    //mydb.close();
                }
Sign up to request clarification or add additional context in comments.

8 Comments

thanks :) but I am not getting all districts name in my spinner only few names are coming.
this is my XML http://data.gov.in/sites/default/files/Date-Wise-Prices-all-Commodity.xml Might be there is some mistake in parsing that's why all district are not coming ??
@Shiv for Gujarat I have checked, the data is coming right in parsing, I think four names are there for district.
pastie.org/8423681 Is this condition is correct for not to repeat any state & district name in spinner list ?
As your edited answer if one of statement is correct then also it will enter in if's body. Please recheck it again. Its not giving me useful data.
|
1

Try this.. NodeList name as nameList1 then next line nameElement1 initilize as namelist.item(0) it'll take that one..

Element fstElmnt1 = (Element) node;
                NodeList nameList1 = fstElmnt1.getElementsByTagName("District");
                Element nameElement1 = (Element) nameList1.item(0);  //chenges here
                nameList1 = nameElement1.getChildNodes();
                district=((Node) nameList1.item(0)).getNodeValue();

7 Comments

thanks for telling this but I don't think it is the actual reason of error because I am still getting error.
@Shiv and also call these loadStateSpinnerData(); loadDistrictSpinnerData(); function in onPostExecute
ok and see my XML..have I parsed the data correctly? there might be some mistake in parsing. http://data.gov.in/sites/default/files/Date-Wise-Prices-all-Commodity.xml
Now data is showing in spinner :). I think the error was coming in doInBackground method as I was loading loadStateSpinnerData(); loadDistrictSpinnerData(); in that..
@Shiv call that both method in onPostExecute
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.