我的
Android应用程序的代码段有一些麻烦.尝试设置ImageView对象的背景时,我会继续收到NullPointerException.
以下是代码:
public View getView(int position,View view,ViewGroup parent) { ImageView imageView; if (view == null) { imageView = new ImageView(mContext); } else { imageView = (ImageView) view; } imageView.setTag(position); return imageView; } private OnItemClickListener itemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent,View v,int position,long id) { ImageView imageView; //Variable i,here,is from a for loop. imageView = (ImageView)v.findViewWithTag(i); //I get a NullPointerException at the next line,"Log.d" Log.d("View 1",imageView.toString()); //If I get rid of the "Log.d" line above,//the NullPointerException occurs on the next line imageView.setBackgroundColor(Color.BLUE); imageView = (ImageView)v.findViewWithTag(position); Log.d("View 2",imageView.toString()); imageView.setBackgroundColor(Color.BLUE); }; }
我怀疑我的代码的问题是因为我传递了setTag()方法的什么参数以及我传递findViewWithTag()方法的参数.如果有人可以向我展示如何使用标签设置标签和查看视图的示例,我将非常感谢.
感谢您的时间.
编辑:这是错误日志.我不知道该放在哪里,所以我会把它放在这里.
05-04 21:47:24.314: ERROR/AndroidRuntime(335): FATAL EXCEPTION: main 05-04 21:47:24.314: ERROR/AndroidRuntime(335): java.lang.NullPointerException 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at com.jacksmartie.PhotoMem.MainActivity$1.onItemClick(MainActivity.java:79) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at android.widget.AdapterView.performItemClick(AdapterView.java:284) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1696) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at android.os.Handler.handleCallback(Handler.java:587) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at android.os.Handler.dispatchMessage(Handler.java:92) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at android.os.Looper.loop(Looper.java:123) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at android.app.ActivityThread.main(ActivityThread.java:4627) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at java.lang.reflect.Method.invokeNative(Native Method) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at java.lang.reflect.Method.invoke(Method.java:521) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 05-04 21:47:24.314: ERROR/AndroidRuntime(335): at dalvik.system.NativeStart.main(Native Method)`
解决方法
这条线是你的罪魁祸首的一部分:
com.jacksmartie.PhotoMem.MainActivity$1.onItemClick(MainActivity.java:79)
在这里放一个断点:
Log.d("View 1",imageView.toString());
看看你的imageview参考对象[imageView]是什么,我期望它是null,因为你没有正确链接它.
如果它为空,这意味着您的参考视图的链接不正确.如果是这样,那么你需要如此正确地分配它:
Button b = findViewById(R.id.Button01);
然而;因为你使用的是什么似乎是一个ListView,拉的是略有不同.这意味着你拉扯视图的方式是错误的,做一些研究,应该找到一些帮助清除它的东西!