公共(public) TextView name_place; 私有(private) ImageView 照片;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
name_place = (TextView) findViewById(R.id.name);
foto = (ImageView) findViewById(R.id.foto);
settings = getSharedPreferences("USER_INFO", 0);
UserName = settings.getString("USER_NAME",null);
UserId = settings.getString("USER_ID",null);
...
new Thread(new Runnable() {
public void run() {
while(true){
setupThings();
try {
Thread.sleep(5000);
}catch(Exception e){}
}
}
}).start();
}
public void setupThings(){
UserName = settings.getString("USER_NAME",null);
UserId=settings.getString("USER_ID",null);
try {
name_place.setText("" + UserName.toString());
}catch(Exception e){
Log.w("LOG",name_place.getText().toString());
}
}`
我的问题是为什么 TRY block 中的 setText() 不起作用,但 CATCH block 中的 getText() 工作得很好。
(只有一个 xml - Activity_main.xml)
最佳答案
My question is why setText() in TRY block doesnt work, but getText() in CATCH block works perfectly fine.
您一定遇到了异常,日志显示。无法从非 UI 线程触摸 View 。
您需要仅使用 UI 线程在设备屏幕上进行视觉更改。
替换这个
new Thread(new Runnable() {
public void run() {
while(true){
setupThings();
try {
Thread.sleep(5000);
}catch(Exception e){}
}
}
}).start();
与
setupThings();
仅删除onCreate中的其他线程启动部分。当您使用 UI 线程在屏幕“setText”中进行视觉更改时,这不会崩溃。
尝试看看结果。
其次:
如果您想先在后台执行某些操作,然后根据其结果更新用户界面。使用异步任务。谷歌它是如何运作的。有成千上万的例子。
第三:
从代码的角度来看,你做了很多错误的事情。
1)错误的命名约定。
2) 不要使用通用的 catch(Exception ex) block 。在不记录崩溃堆栈的情况下至少不为空。
3)不使用AsyncTasks。
关于java - GetText() 工作正常,但 setText() 会使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22425539/