1

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

导致错误的行是: 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;
    }




}

词项类:

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 但提要字符串包含数据。不知道这里发生了什么

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

受保护的无效 onPostExecute(WordItem 结果){

        this.aWordItem=result;
        return;
    }
4

1 回答 1

1

堆栈跟踪显示

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

所以第 110 行的内容是null

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

既然xpp好像已经设置好了,请看mwordItem。它来自第 51 行的调用,在哪里myWordItem通过。在发布的代码中,myWordItem永远不会设置。

因此,从您发布的代码中:myWordItemnull.

于 2013-08-23T01:30:19.420 回答