NullPointerException 与 StringReader

NullPointerException with StringReader

我需要你的帮助。我正在尝试解析来自 xml 的一些数据并将它们列在列表视图中。我得到 url 地址并将其发送到 AsyncTask 中的 StringReader。但是,它是 reader 变量中的 null。我不知道为什么。我知道这确实是一个愚蠢的问题,但它令人沮丧但很重要。有人可以解决这个问题吗?这是我的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Intent intent = getIntent();
    String st = intent.getStringExtra("State");

    String url = "http://whoismyrepresentative.com/getall_reps_bystate.php?state="+st;


    /** The parsing of the xml data is done in a non-ui thread */
    ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

    /** Start parsing xml data */
    listViewLoaderTask.execute(url);
    Log.e("URL",url);

}

private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

    /** Doing the parsing of xml data in a non-ui thread */
    @Override
    protected SimpleAdapter doInBackground(String... url) {

        StringReader reader = new StringReader(url[0]);//NULL HERE
        System.out.print("READER"+reader);
        XmlParser countryXmlParser = new XmlParser();
        System.out.print("countryXmlParser"+countryXmlParser);
        List<HashMap<String, String>> countries = null;

        try{
            /** Getting the parsed data as a List construct */
            countries = countryXmlParser.parse(reader);
            Log.e("@@@","222");
        }catch(Exception e){
            Log.d("Exception",e.toString());
        }

        /** Keys used in Hashmap */
        String[] from = { "rep","details"};

        /** Ids of views in listview_layout */
        int[] to = { R.id.tv_country,R.id.tv_country_details};

        /** Instantiating an adapter to store each items
         *  R.layout.listview_layout defines the layout of each item
         */
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);

        return adapter;
    }

    @Override
    protected void onPostExecute(SimpleAdapter adapter) {

        /** Getting a reference to listview of main.xml layout file */
        ListView listView = ( ListView ) findViewById(R.id.lv_countries);

        /** Setting the adapter containing the country list to listview */
        listView.setAdapter(adapter); // ERROR THIS LINE

这是我的 XmlParser class:

private static final String ns = null;

/** This is the only function need to be called from outside the class */
public List<HashMap<String, String>> parse(Reader reader)
        throws XmlPullParserException, IOException{
    try{
        System.out.print("READER"+reader);
        Log.e("###","111");
        XmlPullParser parser = Xml.newPullParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
        Log.e("###", "222");
        parser.setInput(reader);
        Log.e("###", "333");
        parser.nextTag();
        Log.e("###", "444");
        return readCountries(parser);
    }finally{
    }
}

/** This method read each country in the xml data and add it to List */
private List<HashMap<String, String>> readCountries(XmlPullParser parser)
        throws XmlPullParserException,IOException{

    List<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();

    parser.require(XmlPullParser.START_TAG, ns, "result");

    while(parser.next() != XmlPullParser.END_TAG){
        if(parser.getEventType() != XmlPullParser.START_TAG){
            continue;
        }

        String name = parser.getName();
        if(name.equals("rep")){
            list.add(readCountry(parser));
        }
        else{
            skip(parser);
        }
    }
    return list;
}

/** This method read a country and returns its corresponding HashMap construct */
private HashMap<String, String> readCountry(XmlPullParser parser)
        throws XmlPullParserException, IOException{

    parser.require(XmlPullParser.START_TAG, ns, "rep");

    String countryName = parser.getAttributeValue(ns, "name");
    String party = parser.getAttributeValue(ns, "party");
    //Log.d("LOG_NAME", parser.getAttributeValue(ns, name));

    String details =    "Party : " + party;
    Log.d("LOG_NAME", details);
    Log.d("LOG_NAME1", countryName);
    HashMap<String, String> hm = new HashMap<String, String>();
    hm.put("rep", countryName);
    //hm.put("flag", flag);
    hm.put("details",details);

    return hm;
}

这是我的 logcat:

09-18 21:37:53.258    1933-1933/com.example.hoon.myrepresentative E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93)
        at android.widget.ListView.setAdapter(ListView.java:466)
        at com.example.hoon.myrepresentative.ListRepActivity$ListViewLoaderTask.onPostExecute(ListRepActivity.java:102)
        at com.example.hoon.myrepresentative.ListRepActivity$ListViewLoaderTask.onPostExecute(ListRepActivity.java:57)
        at android.os.AsyncTask.finish(AsyncTask.java:631)
        at android.os.AsyncTask.access0(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4921)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
        at dalvik.system.NativeStart.main(Native Method)

我参考这个site

国家似乎是空的。请参考SimpleAdapter实现

public int getCount() {
    return mData.size();
}

mData 是你的国家。请贴上logcat,这样我们就可以看到在解析xml.

时抛出了什么样的异常

我不太确定给 StringReader() 一个 url 作为参数是否能完成这项工作。我做了完全相同的事情,但我使用 HttpURLConnection 来阅读网页。这就是我所做的:

url = "URL for xml file online"    
URL url_new = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url_new.openConnection();
connection.setRequestMethod("GET");
BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
String xml_string = convertInputStreamToString(inputStream);

编辑:阅读一些关于 StringReader 的内容。它以一个字符串作为参数,并从中生成一个字符流。 URL 作为字符串提供给它,它可能构成 URL 本身的字符流,而不是 URL 指向的字符流。所以 StringReader 无论如何也无济于事。