**
小白使用bundle在線程之間傳遞數據。
**
實現從雲端數據庫中拿出數據,並將數據傳遞給UI主線程,並更新UI界面。
因爲Android 3.0以後使用網絡相關的東西不能直接在主線程實現。所以需要創建一個子線程,從雲數據庫中獲取數據。
創建一個GetDataThread線程類
public class GetDataThread extends Thread {
//重點
private Handler handler ;
private String type;
/* 傳入兩個參數,第一個是用於通信的handler,第二個是動態類型 */
public GetDataThread(Handler h,String type){
this.handler = h ;
this.type = type;
}
}
想要在線程間傳遞數據,最主要的是需要把主線程的Handler傳進GetDataThread類中,而不是直接new一個新的handler。
在拿到handler後就能在handler中存放數據了。
Bundle bundle = new Bundle();
Message message=new Message();
//listitem是一個ArrayList<>
bundle.putSerializable("listitem",listitem);
這裏需要注意向bundle中存放不同類型的數據,要使用不同的方法。
字符串用putString。。等,詳情百度。。
在主線程中,只要聲明一個全局變量handler並重寫handleMessage方法,在方法的msg中就可以獲取數據了。
@SuppressLint("HandlerLeak")
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
List<Map<String,Object>> listitem = (List<Map<String, Object>>) bundle.getSerializable("listitem");
}
};