2011-08-25 61 views
1

我編寫了此代碼以從json解析器獲取內容。第一次,我有「listInfo = jp.info();」和「listContent = jp.content();」在onCreate()方法中,但通過這種方式,應用程序在加載時有一個延遲!所以,我添加了runJP()方法以獲得更快的速度,但現在我無法獲取listInfo和listContent的內容!我必須做什麼?Android:從線程中獲取內容

private ArrayList<HashMap<String, String>> listInfo = new ArrayList<HashMap<String, String>>(); 
private ArrayList<HashMap<String, HashMap<Integer, String>>> listContent = new ArrayList<HashMap<String, HashMap<Integer, String>>>(); 
public JSONParser jp = new JSONParser(); 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.map); 

    mapView = (MapView) findViewById(R.id.mapview); 
    mapView.setBuiltInZoomControls(true); 

    runJP(); 

    mapLocationOverlay = new MapLocationOverlay(this); 
    mapView.getOverlays().add(mapLocationOverlay); 
    mapView.invalidate(); 
} 

private void runJP() { 
    new Thread(new Runnable() { 
     public void run() { 
      listInfo = jp.info(); 
      listContent = jp.content(); 
     } 
    }).start(); 
} 
+0

你什麼意思,你不能把列表信息和listContent的內容?爲什麼不?你的應用崩潰了嗎?變量是否爲null?如果發生異常,您能發佈異常嗎?你是否瀏覽了你的代碼,看看runJP中究竟發生了什麼? – Jack

+0

沒有應用程序不崩潰!與jsonparser我把coords和標題形式jsonarray。與runJP()方法我不能從listInfo和listContent採取數據。如果listInfo和listContent在onCreate()方法中(沒有線程),那麼我會獲取數據! – John

回答

0

使用Handler將解析的數據從線程發送到活動。在Runnable結束時,您可以創建消息,將消息的對象設置爲包含2個對象的數組,然後您將在Handler中收到消息。

0

你也可以使用.runOnUiThread(runnable)對UI線程更新UI:

private void runJP() { 
    new Thread(new Runnable() { 
     public void run() { 
      listInfo = jp.info(); 
      listContent = jp.content(); 
      // added 
      YourActivity.this.runOnUiThread(new Runnable() { 
       public void run() { 
        // here you can safely update the UI 
       } 
      }); 
     } 
    }).start(); 
}