如何更正我的Android程序?

时间:2013-07-20 08:40:01

标签: android

该计划有什么问题?当活动A跳转到活动B并从Internet请求数据以更新Android UI时,UI无法更新。然后adt显示错误:

  

android.view.ViewRootImpl $ CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能触及其视图。

以下是代码:

public class MyStatusesActivity extends Activity {
  Button re;
  TextView mystatuses;
  StatusesAPI sa;
  ProgressDialog progressDialog;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.my_statuses);
    initView();
    action();
    userTimeline();
  }
  private void action() {
    // TODO Auto-generated method stub
    re.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
      // TODO Auto-generated method stub
      MyStatusesActivity.this.finish();
    }
  });
}
private void initView() {
  // TODO Auto-generated method stub
  progressDialog = ProgressDialog.show(this,null, "加载中...",true, true);
  mystatuses = (TextView) findViewById(R.id.mystatuses);
  re = (Button) findViewById(R.id.re);
}
public void userTimeline() {
  // TODO Auto-generated method stub
  sa = new StatusesAPI(SplashActivity.accessToken);
  sa.userTimeline(SharePre.readUID(this), 0, 0, 20, 1, false, FEATURE.ALL, false, listener);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.my_statuses, menu);
  return true;
}
RequestListener listener = new RequestListener(){
  @Override
  public void onComplete(String arg0) {
    // TODO Auto-generated method stub
    Log.i("sina", arg0);
    try {
      JSONObject jsonObject = new JSONObject(arg0);
      JSONArray jsonArray = jsonObject.getJSONArray("statuses");
      JSONObject jsonOb = jsonArray.getJSONObject(0);
      mystatuses.setText(jsonOb.getString("text"));
      progressDialog.dismiss();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  @Override
  public void onError(WeiboException arg0) {
    // TODO Auto-generated method stub
    Log.i("sina", "WeiboException:"+arg0.getMessage());
  }

  @Override
  public void onIOException(IOException arg0) {
    // TODO Auto-generated method stub
    Log.i("sina", "IOException:"+arg0.getMessage());
  }
};

1 个答案:

答案 0 :(得分:0)

我没有详细挖掘你的代码(请在将它发布到SO之前尽量抽象它),但似乎你在不同的线程上做某事(请求侦听器可能被称为异步?)并且那里你不允许访问用户界面。
简单的解决方案:创建一个全局Handler并在onCreate()中创建它,然后在异步方法中,而不是仅执行代码,通过处理程序发布它。这将改变Thread上下文(即允许您访问UI)。