java.lang.RuntimeException: Can not toast on a thread that has not called Looper.prepare()终极解决方案

源代码:

Thread thread = new Thread(() -> {
     
    MySQLUtil mySQLUtil = new MySQLUtil(this);
    mySQLUtil.getConnection("cce-18");
    ArrayList<String> res = null;
    res = mySQLUtil.getMajorGpaRank(idMyself, major, finalYear, finalSemester_, course_nature);
    if(res == null) {
     
         ToastUtil.showMessage(getApplicationContext(), "暂无成绩信息!");
    }else {
     ...}
});
thread.start();
try {
     
    thread.join();
} catch (InterruptedException e) {
     
    e.printStackTrace();
}

网上看了很多解决办法,都是在Toast的前后加上:

Looper.prepare();
ToastUtil.showMessage(getApplicationContext(), "暂无成绩信息!");
Looper.loop();

实验之后发现会卡在原来的界面,正确的解决办法:开一个runOnUiThread,如下所示:

runOnUiThread(() -> {
     
    ToastUtil.showMessage(getApplicationContext(), "暂无成绩信息!");
});

你可能感兴趣的:(Android,runOnUiThread,android,Toast,Looper)