我创建了一个活动,之后我创建了一个线程,它从电话簿中读取数据,进行一些字符串操作并根据规则在主 UI 上创建各种按钮。
我有下面的代码,但有一些应用程序如何终止。
谁能帮帮我吗。
public class Phone extends Activity {
/** Called when the activity is first created. */
ProgressDialog pbarDialog;
LinearLayout ll;
Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
setContentView(sv);
pbarDialog = new ProgressDialog(this);
pbarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pbarDialog.setMessage("Reading from Phone Book");
pbarDialog.setCancelable(false);
pbarDialog.show();
pbarDialog.incrementProgressBy(0);
new TheTask().execute();
}
private class TheTask extends AsyncTask<Void, Integer, Void>{
@Override
protected void onPreExecute() {
pbarDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pbarDialog.setMessage("Reading from Phone Book");
pbarDialog.setCancelable(false);
pbarDialog.show();
pbarDialog.incrementProgressBy(0);
}
@Override
protected Void doInBackground(Void... params) {
ReadPhoneBook();
return null;
}
@Override
protected void onPostExecute(Void result) {
pbarDialog.dismiss();
}
}
private void ReadPhoneBook() {
int i=0;
int count=0;
//this is a temp function, it just creates buttons, does not read the phone book.
for (i=0;i<10;i++)
{
b = new Button(this);
b.setText("Testing");
b.setId(1);
final Activity self = this;
b.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
initiateACall(v,self);
}
});
ll.addView(b);
if (i%3 == 0){
pbarDialog.incrementProgressBy(30*i/3);
}
}
}
我收到以下错误:
util.concurrent.FutureTask.run(FutureTask.java:137) 06-24 21:52:36.436: 错误/AndroidRuntime(297): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 06-24 21:52:36.436: ERROR/AndroidRuntime(297): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 06-24 21:52:36.436: ERROR/AndroidRuntime(297): at java .lang.Thread.run(Thread.java:1096) 06-24 21:52:36.436: ERROR/AndroidRuntime(297): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: 只有创建视图层次结构的原始线程可以触摸它的观点。06-24 21:52:36.436: ERROR/AndroidRuntime(297): at android.view.ViewRoot.checkThread(ViewRoot.java:2802) 06-24 21:52:36.436: ERROR/AndroidRuntime(297): at android. view.ViewRoot.requestLayout(ViewRoot.java:594) 06-24 21:52:36.436: