Search code examples
androidandroid-cameraandroid-gallery

Can't replace image view, for image from a camera or gallery (It doesn't work)


I Can't replace the image for other image from gallery or camera, when I show the images from my gallery and selected a image this doesn't replace the image. Also, when I intent capture a image with the camera this doesn't show and I can't take a picture. I want replace the image in a fragment and this is the code of the fragment. In the case of the camera at first I think that is probably for I didn't add correctly manifest of the camera, but then I saw this and I think that is correctly.

public class SettingsFragment extends Fragment {
    private ImageView ivImage;
    private String userChoosenTask;
    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    private Button btnSelect;
    public SettingsFragment() {
    }
    private void cameraIntent(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }
    private void galleryIntent(){
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Selecciona una imagen"), SELECT_FILE);
    }
    @SuppressWarnings("deprecation")
    public void onSelectFromGalleryResult(Intent data){
        Bitmap bm = null;
        if(data != null){
            try{
                bm = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(),data.getData());
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        ivImage.setImageBitmap(bm);
    }

    private void onCaptureImageResult(Intent data){
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG,90, bytes);
        File destination = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+".jpg");
        FileOutputStream fo;
        try{
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        ivImage.setImageBitmap(thumbnail);
    }private void SelectImage(){
        final CharSequence[] items = {"Realizar foto", "Selecciona una imagen", "Cancelar"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("Añadir foto");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(getContext());
                if(items[item].equals("Realizar una foto")){
                    userChoosenTask = "Realizar una foto";
                    if(result)
                        cameraIntent();
                }else if(items[item].equals("Selecciona una imagen")){
                    userChoosenTask = "Selecciona una imagen";
                    if(result){
                        galleryIntent();
                    }
                }else if(items[item].equals("Cancelar")){
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_perfil, container, false);
        final Fragment settings = new Sett();
        final Fragment datospersonales = new datospersonales();
        btnSelect = (Button) rootView.findViewById(R.id.btnSelectPhoto);


        final FragmentManager fragmentManager = getFragmentManager();
        final ImageButton optsel = (ImageButton) rootView.findViewById(R.id.optsel);
        final Button alerta = (Button) rootView.findViewById(R.id.alerta);

        btnSelect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                SelectImage();
            }
        });


        optsel.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragmentContainer, settings).commit();
            }
        });
        alerta.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Notification();
            }
        });
        ivImage = (ImageView) rootView.findViewById(R.id.ivImage);
        return rootView;
    }
    public void Notification(){
        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(getContext())
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setContentTitle("C4Growth")
                .setContentText("Alerta bullying activada");
        NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1,notificationBuilder.build());
    }


    public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults){
        switch (requestCode){
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    if(userChoosenTask.equals("Realizar una foto")){
                        cameraIntent();
                    }else if(userChoosenTask.equals("Selecciona una imagen")){
                        galleryIntent();
                    }
                }else{

                }
                break;
        }
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        if(requestCode == Activity.RESULT_OK){
            if(requestCode == SELECT_FILE){
                onSelectFromGalleryResult(data);
            }else if(requestCode == REQUEST_CAMERA){
                onCaptureImageResult(data);
            }
        }
    }

}

Solution

  • I have been looking at your code! here what you can do with it! to get things done!

    step 1: override a method of onActvityCreated() and use click listener there and use the context of your parent activity to get its onActivityResult method in your fragment and that will do it!

    check this Stack thread too it has nice solution in it that I am trying to tell!

    step 2:

    for more check this blog I found it a little helpful blog link credit goes to "Rex St. John" for this

    NOTE : Try this and if that does not work come in comments I will try work it out with you ^_^