2013-07-20 65 views
0

程序有什麼問題?當活動A跳轉到活動B並向Internet請求數據以更新Android UI時,UI無法更新。然後ADT顯示錯誤:如何糾正我的Android程序?

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

下面的代碼:

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()); 
    } 
}; 
+3

當您在此處或在Google上搜索此錯誤時,您學到了什麼? – Simon

+0

'StatusesAPI'是否在不同的線程上執行網絡請求? –

+0

@LukasKnuth它在這個活動中執行。我是Android初學者,我不知道如何糾正它。 – Mop

回答

0

我沒有經過詳細的代碼挖(請提取它的努力張貼到SO之前),但它看起來你是在另一個線程上做某事(Request偵聽器可能被稱爲異步?),並且從那裏你不允許訪問UI。
簡單的解決方案:製作一個全球的Handler並在onCreate()中創建它,然後在異步方法中,而不是隻執行代碼,通過處理程序發佈它。這將改變線程上下文(即允許你訪問UI)。

+0

感謝您的回答 – Mop