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 🙂
Do not use Application context – as it will break your ActivityStack.
I would recommend to add Activity parameter to this static method:
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;
That is a good practice to make such static helpers to avoid creating intents and startActivities from different parts of your code.
Good luck.