【开发记录】Android中Toast的使用
1.背景:写手机APP登录功能,需要在登录失败时,提示用户。直接百度搜,说可以使用Toast类
2.方法:常规使用方法,第一个参数就是你显示的页面类。
Toast.makeText(LoginActivity.this,"用户名或者密码错误!",Toast.LENGTH_LONG).show();
报错:
2021-04-09 16:29:38.129 15300-15348/com.example.myapplication1 E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: com.example.myapplication1, PID: 15300
java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
at android.widget.Toast.getLooper(Toast.java:179)
at android.widget.Toast.<init>(Toast.java:164)
at android.widget.Toast.makeText(Toast.java:492)
at android.widget.Toast.makeText(Toast.java:480)
at com.example.myapplication1.ui.login.LoginActivity$3$1.onResponse(LoginActivity.java:133)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
继续百度:原博主是直接在onclick()中写这段代码,但是我是在异步的get请求写的,get请求是一个新的子线程,这应该是报错的原因,添加两段代码后成功运行。
Looper.prepare();
Toast.makeText(LoginActivity.this,"用户名或者密码错误!",Toast.LENGTH_LONG).show();
Looper.loop();