gpt4 book ai didi

java - 线程中出现错误并且未显示我的 toast

转载 作者:行者123 更新时间:2023-12-01 12:03:22 25 4
gpt4 key购买 nike

我是 Android 新手。我的应用程序在 sleep 运行 (5000) 后因错误而崩溃,然后我的 toast 没有显示在我的 finally block 中。是什么导致我的代码中出现这些错误?

public class LoginActivity extends ActionBarActivity {

TextView textview;
Toast toast;

@Override
protected void onCreate(Bundle ThisisLoginActivity) {
super.onCreate(ThisisLoginActivity);
setContentView(R.layout.activity_login);

textview = (TextView) findViewById(R.id.textView1);

Thread thread = new Thread() {
public void run() {
try{
sleep(5000);
} catch(InterruptedException e) {
e.printStackTrace();
}
finally {
toast = Toast.makeText(getApplicationContext(), "Sleep Runing", Toast.LENGTH_SHORT);
toast.show();
}
}
};
thread.start();
}
}

这是我的 LogCat:

01-08 22:30:32.782: E/Trace(3503): error opening trace file: No such file or directory (2)
01-08 22:30:33.322: I/Choreographer(3503): Skipped 47 frames! The application may be doing too much work on its main thread.
01-08 22:30:33.402: D/gralloc_goldfish(3503): Emulator without GPU emulation detected.
01-08 22:30:33.531: I/Choreographer(3503): Skipped 62 frames! The application may be doing too much work on its main thread.
01-08 22:30:39.122: I/Choreographer(3503): Skipped 31 frames! The application may be doing too much work on its main thread.
01-08 22:30:39.272: I/Choreographer(3503): Skipped 43 frames! The application may be doing too much work on its main thread.
01-08 22:30:45.772: W/dalvikvm(3503): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
01-08 22:30:45.792: E/AndroidRuntime(3503): FATAL EXCEPTION: Thread-153
01-08 22:30:45.792: E/AndroidRuntime(3503): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-08 22:30:45.792: E/AndroidRuntime(3503): at android.os.Handler.<init>(Handler.java:197)
01-08 22:30:45.792: E/AndroidRuntime(3503): at android.os.Handler.<init>(Handler.java:111)
01-08 22:30:45.792: E/AndroidRuntime(3503): at android.widget.Toast$TN.<init>(Toast.java:324)
01-08 22:30:45.792: E/AndroidRuntime(3503): at android.widget.Toast.<init>(Toast.java:91)
01-08 22:30:45.792: E/AndroidRuntime(3503): at android.widget.Toast.makeText(Toast.java:238)
01-08 22:30:45.792: E/AndroidRuntime(3503): at com.example.incrementdecrement.LoginActivity$1.run(LoginActivity.java:48)
01-08 22:30:46.462: I/Choreographer(3503): Skipped 34 frames! The application may be doing too much work on its main thread.

最佳答案

您无法从另一个线程直接操作用户界面。主线程负责所有 UI 更改。

有关类似问题的解决方案,请参阅:Android: Toast in a thread

关于java - 线程中出现错误并且未显示我的 toast ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27850593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com