简体   繁体   中英

Override method in a non Activity class, Android

I'm working on an app which uses default Camera app for taking a photo. Now I want to check is there were taken the photo.

I read on SO that that could be done with this method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  ...
    }

My problem is when I put that method in my class which isnt an Activity class I got error:

"The method onActivityResult(..) must override or implement a supertype method"

I already check, my compiler is set to java 1.6. and my jre is set to 1.6.

What should I do?

You need an Activity on order to receive the result of the camera action. Why do you want to put the code in some other class? If it is just for re-use/organisation then why not just call your other class from your Activity ?

public class SomeOtherClass {
    public static void someOtherMethod(int requestCode, int resultCode, Intent data){
        ...
    }
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    SomeOtherClass.someOtherMethod(requestCode,resultCode,data);
    ...
}

You can only get the result from an Activity inside another Activity or Fragment. Therefore you can only extend onActivityResult() from a class that extends Activity or one of it's descendants (This is actually java-related and not android-related). Also, you must extend and define onActivityResult() in the same activity where you call startActivityForResult().

If you need to execute code in another class that does not extend Activity, you can simply implement your own method and call it from inside onActivityResult()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  if(requestCode == MY_REQUEST_CODE && resultCode == RESULT_OK)
   {
     MyClass object = new MyClass(); //or maybe it's already instantiated and it is defined as a field
     object.myCustomMethod(data); //pass it data or one of it's extras
   }

}

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