2
votes

I don't know what's going on, but I am getting an exception and the app freezes.

Main activity:

public class MainAcitivty extends FragmentActivity implements OnClickListener
{
    // ...

    public interface OnItemSelectedListener
    {
        public void onItemSelected(int resourceId);
    }

    OnItemSelectedListener mCallback;

    @Override
    public void onClick(View v)
    {
        if (v.getId() == R.id.my_imageView)
        {
            mCallback.onItemSelected(R.id.my_imageView);
        }
    }
}

Fragment:

public MyFragment extends Fragment implements MainAcitivty.OnItemSelectedListener
{
   @Override
   public void onItemSelected(int resourceId)
   {
       Log.i("INFO", "Selected: " + resourceId);
   }
}

If I click the selected button, the app freezes and the following Exception is throw:

E/AndroidRuntime(21649): FATAL EXCEPTION: main

E/AndroidRuntime(21649): java.lang.NullPointerException

E/AndroidRuntime(21649): at com.example.MainActivity.onClick(MainActivity.java:53)

E/AndroidRuntime(21649): at android.view.View.performClick(View.java:4232)

E/AndroidRuntime(21649): at android.view.View$PerformClick.run(View.java:17298)

E/AndroidRuntime(21649): at android.os.Handler.handleCallback(Handler.java:615)

E/AndroidRuntime(21649): at android.os.Handler.dispatchMessage(Handler.java:92)

E/AndroidRuntime(21649): at android.os.Looper.loop(Looper.java:137)

E/AndroidRuntime(21649): at android.app.ActivityThread.main(ActivityThread.java:4921)

E/AndroidRuntime(21649): at java.lang.reflect.Method.invokeNative(Native Method)

E/AndroidRuntime(21649): at java.lang.reflect.Method.invoke(Method.java:511)

E/AndroidRuntime(21649): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)

E/AndroidRuntime(21649): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

E/AndroidRuntime(21649): at dalvik.system.NativeStart.main(Native Method)

2
mCallback is not initiated - Honza Musil

2 Answers

4
votes

in MyActivity add method

    public void addListener(MainAcitivty.OnItemSelectedListener listener){
        mCallback = listener;
    }

and invoke this method in onViewCreated() of MyFragment.
((MyActivity) getActivity).addListener(this);

1
votes

I don't know which line 53 is but your mCallback is probably null. Check that before dereferencing it.