2011-08-25 58 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(); 
}