2012-05-27 51 views
0

我試圖做一個簡單的webreader工作在AsyncTast,回調給人以NullPointException

主線程

public class main extends Activity implements CallBackListener{ 
... 
     WebReader wr = new WebReader(); 
     wr.execute("http://www.google.com"); 
... 
    @Override 
    public void callback(String res) 
    { 
     Log.e("eee",res); 
    } 
... 
} 

... 
interface CallBackListener 
{ 
void callback(String res); 
} 

和webreader

class WebReader extends AsyncTask<String, Void, String>{ 


    CallBackListener mListener; 

     public void setListener(CallBackListener listener){ 
     mListener = listener; 
     } 


    @Override 
    protected String doInBackground(String... urls) { 

     String response = ""; 

      DefaultHttpClient client = new DefaultHttpClient(); 
      HttpGet httpGet = new HttpGet(urls[0]); 
      try { 
       HttpResponse execute = client.execute(httpGet); 
       InputStream content = execute.getEntity().getContent(); 

       BufferedReader buffer = new BufferedReader(
         new InputStreamReader(content)); 
       String s = ""; 
       while ((s = buffer.readLine()) != null) { 
        response += s; 
       } 

      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

     return response; 
    } 


    @Override 
    protected void onPostExecute(String result) { 
     Log.e("s3","ss"+result); 
     mListener.callback(result); // null point here 
    } 



} 

但它在與nullpoint墜毀mListener.callback ...任何想法可能是錯誤的?

謝謝!

+1

你在哪裏調用setListener()? – Simon

+0

你有沒有調試你的代碼。 「mListener」在setLintener中初始化還是爲null? – rizzz86

回答

2

您未設置偵聽器。你應該有這樣的事情:

WebReader wr = new WebReader(); 
wr.setListener(new YourCallbackListener()); 
wr.execute("http://www.google.com"); 
+0

明白了!它應該是「wr.setListener(this);」 –