在我的Android应用程序中,我正在尝试使用ASYNC任务...每当我在doInBackground(...)中设置EditText的任何TextView的文本....我得到一个错误,但当我设置同样在onCreate,它工作.. :( 这是代码:
public class RemoteFiles extends Activity {
EditText etrmm ;
TextView t;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote_files);
initVars();
new ConnectToServer().execute(null);
}
protected void initVars(){
etrmm =(EditText)findViewById(R.id.etRM);
etrmm.setText("UnSET");
t=(TextView)findViewById(R.id.RM);
t.setText("UnsET");
}
public class ConnectToServer extends AsyncTask<String, Integer, Void> {
//private ProgressDialog pd = new ProgressDialog(RemoteFiles.this);
private ProgressDialog pdd ;
@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
for(int i=0;i<20;i++){
publishProgress(5);
try {
Thread.sleep(88);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
etrmm.setText("Edittext SET");
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pdd.dismiss();
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// pd.setMessage("Connecting to server... ");
// pd.show();
pdd = new ProgressDialog(RemoteFiles.this);
pdd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pdd.setMax(100);
pdd.show();
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
pdd.incrementProgressBy(values[0]);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_remote_files, menu);
return true;
}}
这是布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/RM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".RemoteFiles" />
<EditText
android:id="@+id/etRM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
<requestFocus />
</EditText>
logcat说android.view.ViewRoot $ CalledFromWrongThreadException
答案 0 :(得分:1)
doInBackground(String ... params)不在UI线程上运行,因此您无法为edittext设置文本
如果要设置edittext值,请返回doInBackGround中的值并使用onPostExecute中的参数值并将其设置为onPostExecute()
答案 1 :(得分:0)
您无法在UI
中执行doInBackground()
项内容。这应该在任何其他方法中完成。为了您的目的,可能onPostExecture()
查看AsyncDocs,doInBackground()
未在主(UI
)主题上运行
答案 2 :(得分:0)
AsyncTask的onpreExecute和onPostExecute方法运行UI线程。您可以在此处更改UI。 doInBackground不在UI线程上运行。它用于执行长时间运行操作。在后台线程中运行。您无法从doinBackground中的后台线程更新ui。
在asynctask的onPostExecute方法中在textview中设置文本。
开发者网站中的文档包含有关THE 4 STEPS标题下主题的详细信息。 http://developer.android.com/reference/android/os/AsyncTask.html