Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call startActivityForResult from static method

Tags:

android

I have a buttonlistener, and when the user clicks the button I want to start a camera intent. At the moment I have this:

public class ButtonListener implements View.OnClickListener 
{
private ArrayList<String> connectedItems;
private String identifier = null;
private Context context;
private EnteredValues enteredValues;

public ButtonListener(Context c, String identifier, ArrayList<String> connectedItems) {
    this.connectedItems = connectedItems;
    this.identifier = identifier;
    this.context = c;
}

public void onClick(View v) {
    if (identifier.equals(ButtonItem.takePhoto)) {
        MainActivity.takePhoto();
    }

}

Now I want to call a method in my mainActivity and there I want to start startActivityForResult, but I get an error that I can't call startActivityForResult from a static method.

public class mainActivity extends Activity{
...
   public static void takePhoto(){
       startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE));
          break;

       //Here I get the error..
   }

}

What is the best practice to fix this sort of problem? pass a mainActivity object to my buttonListener or are there other options?

Many thx :)

like image 440
Robby Smet Avatar asked Dec 12 '22 22:12

Robby Smet


1 Answers

Do not use Application context - as it will break your ActivityStack. I would recommend to add Activity parameter to this static method:

public static void takePhoto(Activity activity, int requestCode){
   activity.startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE), requestCode);
}

Than just pass Activity from your listener. You'll have to pass Activity instance to it, instead of simple Context, as only Activity can make startActivityForResult() calls.

So clickListener code will change as follows: public class ButtonListener implements View.OnClickListener { private ArrayList connectedItems; private String identifier = null; private Activity activity; private EnteredValues enteredValues;

public ButtonListener(Activity activity, String identifier, ArrayList<String> connectedItems) {
    this.connectedItems = connectedItems;
    this.identifier = identifier;
    this.activity = activity;
}

public void onClick(View v) {
    if (identifier.equals(ButtonItem.takePhoto)) {
        MainActivity.takePhoto(activity, 100);
    }
} 

That is a good practice to make such static helpers to avoid creating intents and startActivities from different parts of your code.

Good luck.

like image 116
AlexN Avatar answered Jan 01 '23 00:01

AlexN