2015-09-23 38 views
0

我已經做了REST Web服務,讓我接觸的一些信息,如號碼,年齡......我得到所有這些信息,在此功能CodenameOne連接請求等待postResponse

public static void getRest(String search) { 
    if(search.equals("")){ 
     json="http://localhost:8080/com.vogella.jersey.first/rest/jsonServices/print/"; 
    } else { 
     json="http://localhost:8080/com.vogella.jersey.first/rest/jsonServices/print/"+search; 
    } 

    ConnectionRequest req = new ConnectionRequest() { 

     @Override 
     protected void postResponse() { 

     } 

     @Override 
     protected void readResponse(InputStream input) throws IOException { 
      JSONParser p = new JSONParser(); 
      Map<String, Object> h = p.parseJSON(new InputStreamReader(input)); 
      ArrayList object=new ArrayList(); 

      for (Entry<String, Object> entry : h.entrySet()) { 
       object = (ArrayList) entry.getValue(); 

       int i=object.size();   
      } 

      for(int i=0; i<object.size();i++){ 
       LinkedHashMap s= (LinkedHashMap) object.get(i); 
       Risultati.add(s); 
      } 
     } 
    }; 

    req.setUrl(json); 
    req.setPost(false); 
    req.addRequestHeader("Accept", "application/json"); 
    InfiniteProgress prog = new InfiniteProgress(); 
    Dialog dlg = prog.showInifiniteBlocking(); 
    req.setDisposeOnCompletion(dlg); 
    NetworkManager.getInstance().addToQueue(req); 

Risultati是的屬性類:ArrayList<LinkedHashMap> Risultati;

的問題是,當我調用函數getRest("")這樣:

getRest(""); 
Label contatto=null; 
for(int j=0;j<Risultati.size();j++){ 
    LinkedHashMap s=Risultati.get(j); 
    String nome=(String) s.get("firstName"); 
    String cognome=(String) s.get("lastName"); 
    String numero =(String) s.get("numero"); 
    contatto=new Label(nome+" "+cognome+" "+numero); 
} 
hi.addComponent(contatto); 

事實是Risultati是空,如果我評論的週期我注意到內部函數readResponse執行後......我不知道我在做什麼錯

回答

1

我認爲重點是,你打電話NetworkManager.getInstance().addToQueue(req)。根據it's documentation,它會將一個連接請求(您剛剛創建的連接請求)添加到隊列中。在連接請求被添加到隊列後,它會返回,這意味着請求可能會或可能不會在那段時間被執行。

你必須有選擇來解決這個問題。在我看來,最好的辦法是請求後更新用戶界面已經完成,如CodeOne手冊the "File System, Storage, Network & Parsing" chapter描述:

req.addResponseListener(new ActionListener() { 
    public void actionPerformed(ActionEvent ev) { 
     NetworkEvent e = (NetworkEvent)ev; 
     // ... process the response 
    } 
}); 

或者,你可以用addToQueueAndWait(req)更換呼叫addToQueue(req)。後一種方法一直等到請求在隊列中被處理。後一種方法的缺點是,當請求正在處理時,用戶界面可能會凍結,因爲UI線程在網絡I/O上被阻塞。

+1

很好的答案。然而,一個挑剔的是,最後一段是不準確的。 addToQueueAndWait會在不阻塞UI線程的情況下「正確」阻止UI線程(是的,這就是禪),請參閱:http://www.codenameone.com/blog/callserially-the-edt-invokeandblock-part-1.html和http:/ /你確實需要展現無限進步或其他東西...... –