0

程序有什么问题?当activity A跳转到activity B并从互联网请求数据更新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());
  }
};
4

1 回答 1

0

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

于 2013-07-20T10:25:22.147 回答