如何将视图修改为主类的代码

时间:2014-09-08 04:10:45

标签: java android textview

因此,由于我对Android开发完全陌生,我想为我的新Moto 360(Google Wear)创建一个简单的应用程序,以显示从网页中提取的一些内容。不幸的是,我收到了这个错误:

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

如何将修改TextView文本值的部分移动到主类?

public class MyActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.round_activity_my);

    TextView mTextView = (TextView)findViewById(R.id.text);

    myAsyncTask mTask = new myAsyncTask();
    mTask.execute("http://ephemeraltech.com/demo/android_tutorial20.php");


    /* final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(WatchViewStub stub) {
            mTextView = (TextView) stub.findViewById(R.id.text);
        }
    }); */
}

并且AsyncTask类是

private class myAsyncTask extends AsyncTask<String,Void,Void> {

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected Void doInBackground(String... str) {
        TextView mTextView = (TextView)findViewById(R.id.text);
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://ephemeraltech.com/demo/android_tutorial20.php");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream webs = entity.getContent();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(webs,"iso-8859-1"),8);
                mTextView.setText(reader.readLine());
                webs.close();
            } catch(Exception e){
                mTextView.setText("HI");
            }
        } catch (Exception e) {
            mTextView.setText(e.toString());
        }

        return null;
    }

}

protected void onPostExecute(String str) {
}

}

2 个答案:

答案 0 :(得分:2)

您无法从doInBackground更新用户界面。将该代码移至onPostExecute

//In doInBackground

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(webs,"iso-8859-1"),8);
    resultText = reader.readLine();
    webs.close();
} catch(Exception e){
    resultText = "HI";
}
.  
.
.
// onPostExecute method
protected void onPostExecute(String str) {
    mTextView.setText(resultText);
}

resultText声明为全局字符串

答案 1 :(得分:1)

doInBackground()方法在后台线程上执行 - 而不是UI线程。只有UI线程才能修改视图。

AyncTask类提供onProgressUpdate()方法和onPostExecute()方法,该方法挂钩到UI线程以分别显示进度或结果。

如果要在执行AsyncTask时显示进度,请将用于设置TextView中文本的代码移动到onProgressUpdate()方法。如果您希望它在执行AsyncTask结束时显示,则将其移至onPostExecute()。