2012-03-14 50 views
1

我有一個應用程序將訪問網絡。我決定使用Spring Android作爲RestAPI,並且在Thread的幫助下已經得到了這個簡單演示的工作。我的問題是,我該如何改變它來填充一個實際的ListView,而不是隻記錄對象的輸出?這裏的其他一些問題使我相信AsyncTask可能是答案,但我仍然對如何更新UI有點困惑,因爲我瞭解其他線程無法觸摸它。Android - 正確的多線程/ UI更新

這是我現在有,減去創建RestTemplate,併發出請求的功能,因爲我認爲這是不相關的:

public void onCreate(Bundle savedInstanceState) 
    { 
    super.onCreate(savedInstanceState); 

    new Thread(new Runnable() { 
     public void run() 
     { 
     // create a RestTemplate. This is used to communicate with the server. 
     RestTemplate restTemplate = getRestTemplate(); 

     String url = "http://192.168.2.14:8888/"; 

     JSONData[] jsonData = restTemplate.getForObject(url, JSONData[].class); 

     for(JSONData d : jsonData) 
     { 
      Log.d("TEST", d.getName() + " " + d.getId()); 
     } 
     } 
    }).start(); 

    setContentView(R.layout.main); 
    } 

回答

2

有幾個選項,列在非常漂亮的文章(Android) Painless ThreadingAsyncTask是其中一個選項,它似乎符合您的需求,並且在UI線程上運行了多種方法,例如onPreExecuteonPostExecuteonProgressUpdate

+0

非常感謝您,無痛穿線文章正是我所需要的。 'AsyncTask'就是這樣! – Josh 2012-03-14 13:46:12

4

如果想將UI從不同的線程改變,你可以使用Handler或Activity.runOnUiThread()。