在适配器内调用类返回android中的Null Pointer异常

时间:2013-12-28 10:34:49

标签: android android-arrayadapter

我尝试使用setOnClickListener事件调用我的适配器(getview方法)中的另一个类 但它给了我java.lang.NullPointException

这是我的适配器getview方法:

ImageButton bIntent = (ImageButton) vi.findViewById(R.id.bIntent);
bIntent.setTag(position);
bIntent.setOnClickListener(new OnClickListener() {

    public void onClick(View arg0) {
        Intent myIntent = new Intent(activity.getParent(),MyClass.class);
        Bundle MyBundle = new Bundle();
        MyBundle.putInt("Key","200");
        myIntent.putExtras(MyBundle);
        activity.startActivity(myIntent );
    }
});

但是当我在我的片段中使用这个函数时没有错误apear并且它可以工作。

Intent myIntent = new Intent(getActivity(),MyClass.class);
startActivity(myIntent);

和错误日志:

12-28 13:57:54.023: W/dalvikvm(3021): threadid=1: thread exiting with uncaught exception (group=0x40018578)
12-28 13:57:54.023: W/System.err(3021): java.lang.NullPointerException
12-28 13:57:54.023: W/System.err(3021):     at android.content.ComponentName.<init>(ComponentName.java:75)
12-28 13:57:54.023: W/System.err(3021):     at android.content.Intent.<init>(Intent.java:2823)
12-28 13:57:54.023: W/System.err(3021):     at com.Myapp.MyAdapter$2.onClick(MyAdapter.java:224)
12-28 13:57:54.023: W/System.err(3021):     at android.view.View.performClick(View.java:2485)
12-28 13:57:54.023: W/System.err(3021):     at android.view.View$PerformClick.run(View.java:9080)
12-28 13:57:54.023: W/System.err(3021):     at android.os.Handler.handleCallback(Handler.java:587)
12-28 13:57:54.023: W/System.err(3021):     at android.os.Handler.dispatchMessage(Handler.java:92)
12-28 13:57:54.023: W/System.err(3021):     at android.os.Looper.loop(Looper.java:130)
12-28 13:57:54.023: W/System.err(3021):     at android.app.ActivityThread.main(ActivityThread.java:3687)
12-28 13:57:54.023: W/System.err(3021):     at java.lang.reflect.Method.invokeNative(Native Method)
12-28 13:57:54.023: W/System.err(3021):     at java.lang.reflect.Method.invoke(Method.java:507)
12-28 13:57:54.023: W/System.err(3021):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
12-28 13:57:54.023: W/System.err(3021):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
12-28 13:57:54.023: W/System.err(3021):     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

我认为你的activity对象在这里为空。

您的代码MyBundle.putInt("Key","200");

也是如此

你传递了两个字符串。putInt不接受它..将200作为int

像这样改变你的方法..

public void onClick(View view) {
    Context context = view.getContext();
    Intent myIntent = new Intent(context,MyClass.class);
    Bundle MyBundle = new Bundle();
    MyBundle.putInt("Key",200);
    myIntent.putExtras(MyBundle);
    context.startActivity(myIntent );
}