空指针异常:用于Xmlpullparser的setinput函数,使用StringReader分配空值

时间:2013-08-22 23:04:42

标签: android xml-parsing nullpointerexception ui-thread stringreader

我遇到的问题是解析器分配空值但是当检查对象字段时(feed变量)它不是null。代码如下。任何帮助表示赞赏。

导致错误的

行是:xpp.setInput(new StringReader(mwordItem.getFeed()));

package com.example.wffd;

import android.os.Bundle;
import android.os.AsyncTask;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;

import java.net.URL;
import java.net.HttpURLConnection;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;




public class WffdhomeActivity extends Activity {

    Button updateButton;
    TextView wdTextView, cwTextView;
    WordItem myWordItem ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wffdhome);
        updateButton = (Button)findViewById(R.id.button1);
        wdTextView = (TextView)findViewById(R.id.textView2);
        cwTextView = (TextView)findViewById(R.id.textView3);
        myWordItem= new WordItem();


        updateButton.setOnClickListener(new View.OnClickListener() {
      public void onClick(View view) {
        try {
            URL url = new URL("http://www.dictionary.reference.com/wordoftheday/wotd.rss");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            new FeedGrab(myWordItem).execute(urlConnection);
            update_screen(myWordItem);

            cwTextView.setText(myWordItem.getWord());
            wdTextView.setText(myWordItem.getDefinition());
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      }
      });

    }

    private class FeedGrab extends AsyncTask<HttpURLConnection,Void,Boolean>{

        WordItem aWordItem;

        public FeedGrab( WordItem mWordItem){

            this.aWordItem=mWordItem;
        }

        protected Boolean doInBackground(HttpURLConnection... urls) {
            try {
                InputStream in = new BufferedInputStream(urls[0].getInputStream());
                aWordItem.setFeed(readStream(in));

            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
            finally {

               urls[0].disconnect();
           }
            return true;
        }

         private String readStream(InputStream is) throws IOException {
                StringBuilder sb = new StringBuilder();  
                BufferedReader r = new BufferedReader(new InputStreamReader(is),1000);  
                for (String line = r.readLine(); line != null; line =r.readLine()){  
                    sb.append(line);  
                }  
                is.close();  
                return sb.toString();
            }


    }
    public void update_screen( WordItem mwordItem)throws XmlPullParserException, IOException
    {
         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
         factory.setNamespaceAware(true); 
         XmlPullParser xpp = factory.newPullParser();
         xpp.setInput( new StringReader ( mwordItem.getFeed()) );


         int eventType = xpp.getEventType();
         String tag_id="item";
         boolean in_item = false,in_description = false;

         String tag_def="description";



         while (eventType != XmlPullParser.END_DOCUMENT) {

        if((eventType == XmlPullParser.START_TAG) )
          {
            if(tag_id.equalsIgnoreCase(xpp.getName()))  
                    {
                        in_item = true;
                    }else if(tag_def.equalsIgnoreCase(xpp.getName()))
                    {
                        in_description= true;
                    }


          } else if(eventType == XmlPullParser.END_TAG) {
              System.out.println("End tag "+xpp.getName());

          } else if((eventType == XmlPullParser.TEXT ) &&(in_description & in_item)) {
              mwordItem.processString(xpp.getText());
              in_description=false;
              in_item = false;
          }
          eventType = xpp.next();
         }
         System.out.println("End document");
     }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.wffdhome, menu);
        return true;
    }




}

WordItemClass:

package com.example.wffd;

public class WordItem {
    private String word;
    private String definition;
    private String feed;

    public String getFeed() {
        return feed;
    }
    public void setFeed(String feed) {
        this.feed = feed;
    }

    public String getWord() {
        return word;
    }
    public void setWord(String word) {
        this.word = word;
    }
    public String getDefinition() {
        return definition;
    }
    public void setDefinition(String definition) {
        this.definition = definition;
    }
    public void processString(String text){
        String[] phrase = text.split(":");
    this.setWord(phrase[0]);
    this.setDefinition(phrase[1]);

    }


}

编辑:不确定这是否是堆栈跟踪..但是在这里:

Thread [<1> main] (Suspended (exception NullPointerException))  
    <VM does not provide monitor information>   
    WffdhomeActivity.update_screen(WordItem) line: 110  
    WffdhomeActivity$1.onClick(View) line: 51   
    Button(View).performClick() line: 4204  
    View$PerformClick.run() line: 17355 
    Handler.handleCallback(Message) line: 725   
    ViewRootImpl$ViewRootHandler(Handler).dispatchMessage(Message) line: 92 
    Looper.loop() line: 137 
    ActivityThread.main(String[]) line: 5041    
    Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
    Method.invoke(Object, Object...) line: 511  
    ZygoteInit$MethodAndArgsCaller.run() line: 793  
    ZygoteInit.main(String[]) line: 560 

**更新:使用调试器mwordItem.getfeed()返回null但feed字符串包含数据。不知道这里发生了什么

**更新@andy256:我认为使用aWordItem作为对myWordItem的引用并修改feed变量我已经解决了这个问题显然这不是我所做的。如何从异步线程传递值?我尝试通过onpostexecute传递值但没有成功。

protected void onPostExecute(WordItem result){

        this.aWordItem=result;
        return;
    }

1 个答案:

答案 0 :(得分:1)

堆栈跟踪显示

  

WffdhomeActivity.update_screen(WordItem)行:110
  WffdhomeActivity $ 1.onClick(查看)行:51

第110行的内容是null

xpp.setInput( new StringReader ( mwordItem.getFeed()) );

由于似乎设置了xpp,请查看mwordItem。它来自第51行的调用,其中myWordItem被传递。在发布的代码中,永远不会设置myWordItem

因此,根据您发布的代码:myWordItemnull