当我按下按钮时,我有一个按钮,我开始一个新活动myActivity
。我希望myActivity
的布局预览从myDataBase
检索到的一些数据,但是当我更改TextView
程序崩溃的文本时,这是我的代码。
public class myActivity extends Activity {
TextView tv1;
myDataBase DB;
String s;
String reqName
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
tv1 = (TextView)findViewById(R.id.testtest);
Bundle bundle = getIntent().getExtras();
reqName = bundle.getString("someKey");
DB = new myDataBase(this);
new GetSomeData().execute(reqName);
}
public class GetSomeData extends AsyncTask<String,Integer ,String>
{
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
String name = reqName;
DB.open();
s = DB.getData(name);
DB.close();
}
catch(Exception e)
{
e.printStackTrace();
}
tv1.setText(s); // this line makes the program crash
return s;
}
}}
我觉得程序崩溃是因为交叉线程(我不确定!), 我怎么解决这个问题?是否有更好的想法来预览数据库中的数据?
答案 0 :(得分:1)
您不能从后台线程修改UI元素。 AsyncTasks
的{{1}}方法在后台线程中运行,这就是您收到错误的原因。
相反,请将您希望设置为doInBackground()
的{{1}}从String
方法返回到TextView
方法,然后将doInBackground()
设置为您的onPostExecute()
String
那里。这是有效的,因为TextView
在主线程中运行,也称为“UI线程”。
onPostExecute()