1

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);
            }
        }
    }

}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • from your code I can see you are trying to get a pic and then saving it in the gallery and then reFetching it in for the ImageView! can you please share some more code or logcat error! please. – Rizwan Atta Apr 28 '18 at 07:47
  • I have a proposed solution that you are fetching the data right! there is no bug there but you are trying to get the image from imageResult to your fragment! and I can see you are using click listener in the Fragment's View method! that works but you should try using your click code in ONACTIVITYCREATED method of fragment – Rizwan Atta Apr 28 '18 at 07:49
  • In the logcat I don't see any important error, when I selected the photo from my gallery this selected correctly but didn't replace the old photo, I want replace the photo in this fragment, how I can solution? If I try my click code of the replace in a oncreate the aplication crash @rizwan-atta – Desirée Rodríguez Apr 28 '18 at 08:11
  • overRide an other method in fragment called "onActivityCreated" and put click listener there and retry – Rizwan Atta Apr 28 '18 at 08:17
  • I don't have any method in my fragment calls onActivityCreated, only I have onCreated and onCreatedView :( @rizwan-atta, where I put this method? – Desirée Rodríguez Apr 28 '18 at 08:26
  • check the override docs of fragment – Rizwan Atta Apr 28 '18 at 08:29
  • I understand when I should use in my fragment method calls onActivityCreated, which would my fragment if I add this method? @rizwan-atta – Desirée Rodríguez Apr 28 '18 at 08:46

1 Answers1

1

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 ^_^

Rizwan Atta
  • 3,222
  • 2
  • 19
  • 31
  • I intent follow the solutions but my fragment still doesn't work correctly :( @rizwan-atta – Desirée Rodríguez Apr 28 '18 at 09:14
  • I changed a little be my code, in the cameraintent() and galleryintent() before I had startActivityForResult(intent, REQUEST_CAMERA); and now I have frag.startActivityForResult(intent,REQUEST_CAMERA); I don't found the error :( @rizwan-atta – Desirée Rodríguez Apr 28 '18 at 12:04