[問題] facebook的request使用notify/wait取資料

看板AndroidDev作者 (somebody)時間12年前 (2013/10/18 04:12), 編輯推噓1(108)
留言9則, 4人參與, 最新討論串1/2 (看更多)
((FaceBook SDK版本3.0 Facebook的request應該是用另外一個thread去執行的 所以無法在發出request的下一行直接使用回傳的資料(會有NullException之類的 因此我想說使用notify()跟wait()的方法 在request發出後 main thread中先讓要回傳資料call wait() notify則寫在request的Oncomplete() 預期的效果應該是讓main thread先用wait放到佇列 等到request完成後忽叫notify再回到main thread執行 這樣才能後續將得到資料的list做成listview 但實際的狀況是程式就卡住了 卡在wait()那裡 觀念上應該哪裡有錯 跪請各位指導了 附上程式碼 friendslist = new ArrayList<FriendInfo>(); getfriendinfo(); //此函式包含facebook的request synchronized(friendslist){ try { friendslist.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void getfriendinfo() { Bundle aa = new Bundle(); aa.putString("fields", "picture,id,name"); new RequestAsyncTask(new Request(session, "me/friends", aa , HttpMethod.GET, new Request.Callback(){ @Override public void onCompleted(Response response) { /* 這部分是將從facebook取得的資料存到 friendslist 程式碼略 */ synchronized(friendslist){ friendslist.notify(); } } })).execute(); } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.164.131.70

10/18 04:33, , 1F
就我理解 android由main thread負責管理畫面 而您讓listv
10/18 04:33, 1F

10/18 04:33, , 2F
iew進入wait那當然畫面就當掉
10/18 04:33, 2F
所以main thread是不能夠進入wait的嗎? 我想說後來會call notify 應該會喚醒main thread 總的來說 我想找一個方法使我可以確定已經確定從facebook取得資料 這樣才能在main thread改UI 不知道有沒有其他機制可以做到這件事呢@@? 也有試過把wait另外開一個Thread 再用join去等她執行結束 但也是會當掉 以下程式碼 Thread tt = new Thread(new Runnable(){ public void run(){ synchronized(friendslist){ try{ friendslist.wait(); }catch(InterruptException e){} } } }); tt.start(); try{ tt.join(); }catch(InterruptException e){} ※ 編輯: whow 來自: 218.164.131.70 (10/18 05:02)

10/18 09:03, , 3F
因為notify的地方應該也是在main thread,但是因為你的
10/18 09:03, 3F

10/18 09:03, , 4F
wait卡住main thread了,其實不需要用wait/notify
10/18 09:03, 4F

10/18 09:04, , 5F
而且一般UI程式設計,都會不希望main(UI) thread卡住的
10/18 09:04, 5F

10/18 13:10, , 6F
那個RequestAsyncTask繼承AsyncTask不是嗎?
10/18 13:10, 6F

10/18 13:11, , 7F
那就把你想給main thread做的事 放到onPostExecute
10/18 13:11, 7F

10/18 20:29, , 8F
嗯我記得當初好像是因為一些原因所以沒選擇寫在一起
10/18 20:29, 8F

10/18 20:30, , 9F
我先搜尋一下原因 有問題再來回報 謝謝各位大大!!
10/18 20:30, 9F
文章代碼(AID): #1IO4IP5G (AndroidDev)
文章代碼(AID): #1IO4IP5G (AndroidDev)