method ‘void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)‘ on a null object refe
Posted 闲言_
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了method ‘void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)‘ on a null object refe相关的知识,希望对你有一定的参考价值。
异常产生环境
在android 使用dialog 引入Spinner 控件时产生异常
异常描述
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:5637)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
at cn.bloghut.StudentList.add(StudentList.java:122)
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:397)
at android.view.View.performClick(View.java:5637)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
异常原因
- 因为我把Spinner 嵌在dialog 里面了,获取Spinner 的使用使用findViewById(R.id.spinner); 肯定是获取不到的。
- 正确的获取代码
view.findViewById(R.id.spinner);
- 代码调式如下:
- 奇怪的是sprinner 为空,用一个null 调用setAdapter 方法,却不报空指针异常而是 onClick(AppCompatViewInflater 异常
解决办法
- 修改获取控件的代码即可
spinner = (Spinner) view.findViewById(R.id.spinner);
以上是关于method ‘void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)‘ on a null object refe的主要内容,如果未能解决你的问题,请参考以下文章
方法必须具有签名“String method() ...[etc]...”但具有签名“void method()”
method ‘void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)‘ on a null object refe
Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setHomeButtonEnabled(boo
Attempt to invoke virtual method 'void com.loopj.android.image.SmartImageView.setImageUrl(java.l
8D8: Default interface methods are only supported starting with Android N (--min-api 24): void(示例代码(