2014-02-22 23 views
1

處理程序,因爲這傳遞:處理程序作爲參數傳遞給線程構造函數,當試圖通過處理程序來發送消息我得到空指針異常

public void getUserYouTubeFeed() { 
    new Thread(new GetYouTubeUserVideosTask(responseHandler, username, i)).start(); 
} 

Handler responseHandler = new Handler() { 
    public void handleMessage(Message msg) { 
     populateListWithVideos(msg); 
    } 
}; 

和線程

的run方法
public class GetYouTubeUserVideosTask implements Runnable { 
    // A handler that will be notified when the task is finished 
    private final Handler replyTo; 

    public GetYouTubeUserVideosTask(Handler replyTo, String username, int frag) { 
     this.replyTo = replyTo; 
    } 

    @Override 
    public void run() { 
     // some code here 
     Library lib = new Library(username, videos); 
     // Pack the Library into the bundle to send back to the Activity 
     Bundle data = new Bundle(); 
     data.putSerializable(LIBRARY, lib); 

     // Send the Bundle of data (our Library) back to the handler (our Activity) 
     //Message msg = Message.obtain(); 
     Message msg = new Message(); 
     msg.setData(data); 
     // getting null pointer exception here 
     replyTo.sendMessage(msg); 
    } 
} 
+0

第一個代碼片段中的順序是正確的? – CSchulz

回答

0

有同樣的問題。我想在一個單獨的.java文件中創建一個客戶端線程類。然而,爲了工作,它需要知道主UI線程的處理程序。不幸的是,由於Java不支持指針,通過從UI處理程序到您的自定義類,併爲其分配:

public GetYouTubeUserVideosTask(Handler replyTo, String username, int frag) { 
    this.replyTo = replyTo; 
} 

簡單地創建了處理程序,並將它與你的線程副本(而不是鏈接到主UI處理程序)。

發送到線程(或主UI)的消息需要一個Looper,它從消息隊列調度消息,然後消息處理程序可以處理這些消息。主用戶界面默認有一個與其關聯的消息循環,通過Looper.getMainLooper()進行訪問,因此,您可以簡單地在主UI中創建一個線程可以發佈到的處理程序。線程,但是,沒有默認消息循環,所以當你嘗試撥打:

replyTo.sendMessage(msg); // NullPointerException 

你實際上是試圖將消息發送到您的新線程的處理程序不有消息循環相關與它導致例外。

您可以查看Looper文檔以瞭解如何爲您的線程創建消息循環,但請記住:線程中的循環處理程序和處理程序僅處理消息到您的線程(這是您可以如何在線程之間進行通信) 。

相關問題