Search code examples
androidandroid-recyclerviewandroid-cameraandroid-viewholder

How to open camera , or call startActivityForResult from a button in recycleriew item


I am trying to open the camera while clicking on the button Photo , but this button is in an adapter of a recyclerview , and I couldn't call startActivityForResult , is there any way to do it ? or something else to start the camera and take pictures as the same way , please explain me how to handle that and why I couldn't call startActivityForResult , I saw previous answer and I didn't got it well , here is my code ,

thank you.

class DommageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

TextView dommage,componant,side;
Button act_photo;

public DommageViewHolder(View itemView) {
    super(itemView);
    dommage=(TextView)itemView.findViewById(R.id.dommage_value);
    componant=(TextView)itemView.findViewById(R.id.componant_value);
    side=(TextView)itemView.findViewById(R.id.side_value);
    act_photo = (Button)itemView.findViewById(R.id.btn_photo_dommage);

    act_photo.setOnClickListener(this);
}

public void bind(DommageGlobale myObject) {
    dommage.setText(myObject.getDammage());
    componant.setText(myObject.getComponant());
    side.setText(myObject.getSide());

}

public interface OnCameraButtoClick{
    void onClick();
}

@Override
public void onClick(View view) {
    if(view.getId() == act_photo.getId()){

    }

}



}

Solution

  • Try this code :

    Call following method inside your if(view.getId() == act_photo.getId()){ HERE }

    public void OpenCamera(){
     Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                view.getContext().startActivity(intent);
    }
    

    don't forget to add permission to your AndroidManifest.xml file :

    <uses-permission android:name="android.permission.CAMERA"/>
    

    Additionally for Marshmallow onwards you need to handle Runtime permission. I hope this will help.