简体   繁体   中英

Why am I getting class cast exception? Android

I'm working on an android app that is supposed to load the gallery and grab an image and display it in an image view. I had it working but changed from Activities to Fragments to use the ViewPager and since then it has been crashing. I believe it is because I'm using a method intended for Activities on Fragments.

public class Fragment_1 extends Fragment {
private static int RESULT_LOAD_IMAGE = 1;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    Button buttonLoadImage = (Button) getView().findViewById(
            R.id.buttonLoadPicture);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Log.v("ButtonPress: ", "Pressed");

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            Log.v("ButtonPress: ", "intent=" + i);

            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });
    return inflater.inflate(R.layout.fragment_1, container, false);

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK    && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) getView().findViewById(R.id.imgView);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }

}

}

The error I'm receiving is:

05-05 22:17:59.214: E/AndroidRuntime(32610): FATAL EXCEPTION: main
05-05 22:17:59.214: E/AndroidRuntime(32610): Process: com.example.hashtagged, PID: 32610
05-05 22:17:59.214: E/AndroidRuntime(32610): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hashtagged/com.example.hashtagged.Fragment_1}: java.lang.ClassCastException: com.example.hashtagged.Fragment_1 cannot be cast to android.app.Activity
05-05 22:17:59.214: E/AndroidRuntime(32610):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2131)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at android.app.ActivityThread.access$800(ActivityThread.java:145)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at android.os.Handler.dispatchMessage(Handler.java:102)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at android.os.Looper.loop(Looper.java:136)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at android.app.ActivityThread.main(ActivityThread.java:5142)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at java.lang.reflect.Method.invokeNative(Native Method)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at java.lang.reflect.Method.invoke(Method.java:515)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at dalvik.system.NativeStart.main(Native Method)
05-05 22:17:59.214: E/AndroidRuntime(32610): Caused by: java.lang.ClassCastException: com.example.hashtagged.Fragment_1 cannot be cast to android.app.Activity
05-05 22:17:59.214: E/AndroidRuntime(32610):    at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
05-05 22:17:59.214: E/AndroidRuntime(32610):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2122)
05-05 22:17:59.214: E/AndroidRuntime(32610):    ... 11 more

Try inflate the View first on OnCreateView, like this:

private Button mButtonLoadImage;

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  View view = inflater.inflate(R.layout.fragment_1, container, false);
  mButtonLoadImage = (Button) view.findViewById(R.id.buttonLoadPicture);
  return view;
}

And set onClickListener inside onViewCreated:

@Override public void onViewCreated(View view, Bundle savedInstanceState) {
  super.onViewCreated(view, savedInstanceState);
  mButtonLoadImage.setOnClickListener(onClickLoad);
}

//Good practice
private View.OnClickListener onClickLoad = new View.OnClickListener() {
  @Override public void onClick(View view) {
    //TODO action here
  }
};

You are using onActivityResult() method of the activity class in your Fragment class. That is why you are getting this error. onActivityResult should be defined in your activity class of the your fragment class not on the fragment itself. See this link for how to do it. here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM