问题描述
- 如何在运行时给spinner中添加items?
- 我想在一个spinner中添加另一个类的list中的items。使用的下面的代码但是给出null pointer exception。
ArrayAdapter<Address> adapter = new ArrayAdapter<Address>( this android.R.layout.simple_spinner_item HomePage.NearPlaces);adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item);Place.setAdapter(adapter);
LogCat 输出:
INFO/ActivityManager(96): Starting: Intent { cmp=com.emx.OnDaMove/.SpotMe } from pid 20881WARN/ActivityManager(96): Activity pause timeout for HistoryRecord{40705eb0 com.emx.OnDaMove/.HomePage}DEBUG/AndroidRuntime(20881): Shutting down VMWARN/dalvikvm(20881): threadid=1: thread exiting with uncaught exception (group=0x40015560)ERROR/AndroidRuntime(20881): FATAL EXCEPTION: mainERROR/AndroidRuntime(20881): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emx.OnDaMove/com.emx.OnDaMove.SpotMe}: java.lang.NullPointerExceptionERROR/AndroidRuntime(20881): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)ERROR/AndroidRuntime(20881): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)ERROR/AndroidRuntime(20881): at android.app.ActivityThread.access$1500(ActivityThread.java:117)ERROR/AndroidRuntime(20881): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)ERROR/AndroidRuntime(20881): at android.os.Handler.dispatchMessage(Handler.java:99)ERROR/AndroidRuntime(20881): at android.os.Looper.loop(Looper.java:130)ERROR/AndroidRuntime(20881): at android.app.ActivityThread.main(ActivityThread.java:3683)ERROR/AndroidRuntime(20881): at java.lang.reflect.Method.invokeNative(Native Method)ERROR/AndroidRuntime(20881): at java.lang.reflect.Method.invoke(Method.java:507)ERROR/AndroidRuntime(20881): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)ERROR/AndroidRuntime(20881): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)ERROR/AndroidRuntime(20881): at dalvik.system.NativeStart.main(Native Method)ERROR/AndroidRuntime(20881): Caused by: java.lang.NullPointerExceptionERROR/AndroidRuntime(20881): at com.emx.OnDaMove.SpotMe.onCreate(SpotMe.java:42)ERROR/AndroidRuntime(20881): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)ERROR/AndroidRuntime(20881): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)ERROR/AndroidRuntime(20881): ... 11 more
解决方案
//设置下拉列表的风格adapter = ArrayAdapter.createFromResource(thisR.array.business android.R.layout.simple_spinner_item);adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); /** * 设置第一组下拉列表内容 */ hangye1 = (Spinner)this.findViewById(R.id.spinner_hangye1); hangye1.setPrompt(""所属行业""); //将adapter添加到spinner中 hangye1.setAdapter(adapter); //添加事件Spinner事件监听 hangye1.setOnItemSelectedListener(selectHangye1); //设置默认值 hangye1.setVisibility(View.VISIBLE);
R.array.business是在资源文件里定义的下拉列表里的选项
解决方案二:
把要添加的值添加到Adapter中, 然后通知list adapter 的数据发生了改变
时间: 2024-09-30 03:03:52