执行显示IllegalArgumentException的“doInBackground()”

时间:2012-06-23 14:11:56

标签: android android-asynctask

我的应用程序从新闻网页下载标题并将其显示在列表视图中,有点像RSSReader,现在当我尝试运行它但显示错误时。

代码: -

public class RSSReaderActivity extends ListActivity
{   List headlines, links;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        new DoSomeTask().execute();
    }
    // DoSomeTask class will do all the work on another thread so there will be no
    // ANR and UI hanging.
    private class DoSomeTask extends AsyncTask<Void, Void, Void>
    {

        /* (non-Javadoc)
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                headlines = new ArrayList();
                links = new ArrayList();

                URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews");

                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                factory.setNamespaceAware(false);
                XmlPullParser xpp = factory.newPullParser();

                    // We will get the XML from an input stream
                xpp.setInput(getInputStream(url), "UTF_8");


                boolean insideItem = false;

                    // Returns the type of current event: START_TAG, END_TAG, etc..
                int eventType = xpp.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) 
                {
                        if (eventType == XmlPullParser.START_TAG) 
                    {

                        if (xpp.getName().equalsIgnoreCase("item")) 
                        {
                            insideItem = true;
                        } 
                        else if (xpp.getName().equalsIgnoreCase("title")) 
                        {
                            if (insideItem)
                                headlines.add(xpp.nextText()); //extract the headline
                        } 
                        else if (xpp.getName().equalsIgnoreCase("link")) 
                        {
                            if (insideItem)
                                links.add(xpp.nextText()); //extract the link of article
                        }
                    }
                    else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item"))
                    {
                        insideItem=false;
                    }

                    eventType = xpp.next(); //move to next element
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            return null;
        }
        protected void onPostExecute(Void params) 
        {
            try{
             // Binding data
            ArrayAdapter adapter = new ArrayAdapter(RSSReaderActivity.this,
                    android.R.layout.simple_list_item_1, headlines);

            setListAdapter(adapter);
            }catch (Exception e) {}

        }   
    }

    public InputStream getInputStream(URL url) {
           try {
               return url.openConnection().getInputStream();
           } catch (IOException e) {
               return null;
             }
        }

        protected void onListItemClick(ListView l, View v, int position, long id) {
           Uri uri = Uri.parse((String) links.get(position));
           Intent intent = new Intent(Intent.ACTION_VIEW, uri);
           startActivity(intent);
        }
}

logcat的: -

06-23 19:37:57.505: W/dalvikvm(7450): threadid=8: thread exiting with uncaught exception (group=0x400207d8)
06-23 19:37:57.785: E/AndroidRuntime(7450): FATAL EXCEPTION: AsyncTask #1
06-23 19:37:57.785: E/AndroidRuntime(7450): java.lang.RuntimeException: An error occured while executing doInBackground()
06-23 19:37:57.785: E/AndroidRuntime(7450):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at java.lang.Thread.run(Thread.java:1096)
06-23 19:37:57.785: E/AndroidRuntime(7450): Caused by: java.lang.IllegalArgumentException
06-23 19:37:57.785: E/AndroidRuntime(7450):     at org.kxml2.io.KXmlParser.setInput(KXmlParser.java:1040)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at mohit.apps.rssreaderfast.RSSReaderActivity$DoSomeTask.doInBackground(RSSReaderActivity.java:56)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at mohit.apps.rssreaderfast.RSSReaderActivity$DoSomeTask.doInBackground(RSSReaderActivity.java:1)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
06-23 19:37:57.785: E/AndroidRuntime(7450):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-23 19:37:57.785: E/AndroidRuntime(7450):     ... 4 more

所以是的,错误是在doInBackground()中,因为我是新的多线程编程,请指出我的代码问题是什么。感谢。

3 个答案:

答案 0 :(得分:1)

问题很可能出在这段代码的某处:

try {
       return url.openConnection().getInputStream();
    } catch (IOException e) {
       return null;
}

来自KXmlParser的源代码:

if (is == null)
    throw new IllegalArgumentException();

正在发生的事情是在调用url.openConnection().getInputStream();时抛出异常导致方法返回null,而XMLPullParser的setInput反过来又抛出InvalidArgumentException,从源头看。尝试将catch块中的stacktrace打印到控制台(Log.e("some_tag", "some message", e);,然后返回null并查看异常是什么,并从那里开始。

另外,要解决“UTF_8”与“UTF-8”辩论,另一张海报出现了,只需使用xpp.setInput(getInputStream(url), HTTP.UTF_8);

答案 1 :(得分:1)

以下行中有错误

xpp.setInput(getInputStream(url), "UTF_8");

UTF_8替换为UTF-8

同时删除setContentView(R.layout.main);

下面是snippt。

package org.sample;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SampleActivity extends ListActivity {
    List headlines, links;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new DoSomeTask().execute();
    }

    // DoSomeTask class will do all the work on another thread so there will be
    // no
    // ANR and UI hanging.
    private class DoSomeTask extends AsyncTask<Void, Void, Void> {

        /*
         * (non-Javadoc)
         * 
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                headlines = new ArrayList();
                links = new ArrayList();

                URL url = new URL("http://feeds.pcworld.com/pcworld/latestnews");

                XmlPullParserFactory factory = XmlPullParserFactory
                        .newInstance();
                factory.setNamespaceAware(false);
                XmlPullParser xpp = factory.newPullParser();

                // We will get the XML from an input stream
                xpp.setInput(getInputStream(url), "UTF-8");

                boolean insideItem = false;

                // Returns the type of current event: START_TAG, END_TAG, etc..
                int eventType = xpp.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    if (eventType == XmlPullParser.START_TAG) {

                        if (xpp.getName().equalsIgnoreCase("item")) {
                            insideItem = true;
                        } else if (xpp.getName().equalsIgnoreCase("title")) {
                            if (insideItem)
                                headlines.add(xpp.nextText()); // extract the
                                                                // headline
                        } else if (xpp.getName().equalsIgnoreCase("link")) {
                            if (insideItem)
                                links.add(xpp.nextText()); // extract the link
                                                            // of article
                        }
                    } else if (eventType == XmlPullParser.END_TAG
                            && xpp.getName().equalsIgnoreCase("item")) {
                        insideItem = false;
                    }

                    eventType = xpp.next(); // move to next element
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(Void params) {
            try {
                // Binding data
                ArrayAdapter adapter = new ArrayAdapter(AbcActivity.this,
                        android.R.layout.simple_list_item_1, headlines);

                setListAdapter(adapter);
            } catch (Exception e) {
            }

        }
    }

    public InputStream getInputStream(URL url) {
        try {
            return url.openConnection().getInputStream();
        } catch (IOException e) {
            return null;
        }
    }

    protected void onListItemClick(ListView l, View v, int position, long id) {
        Uri uri = Uri.parse((String) links.get(position));
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }
}

答案 2 :(得分:-1)

Phew ... atlast its fixed。

我刚刚改变了

xpp.setInput(getInputStream(url), "UTF_8");

xpp.setInput(url.openConnection().getInputStream(), "UTF_8");

和Viola:)