Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.io.IOException: No such file or directory (save image)

I upload the photos I selected from the device to ftp. But despite the photo I have chosen from the device, I get the "no such file directory" error. Although I give the application permissions, it does not save it to IMAGE_DIRECTORY that I have chosen in the application. So I get this error. What is the reason why it did not save the file, even though I gave the permissions?

Error line: f.createNewFile();

error code:

W/System.err: java.io.IOException: No such file or directory
        at java.io.UnixFileSystem.createFileExclusively0(Native Method)
        at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
        at java.io.File.createNewFile(File.java:1008)
        at com.example.stechome.ui.hesabim.HesabimFragment.saveImage

Fragment

public class asdFragment extends Fragment {

    private static final String IMAGE_DIRECTORY = "/asdasd";
    public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;

    private int GALLERY = 1, CAMERA1 = 2;

 private boolean checkAndRequestPermissions() {
        int permissionACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_NETWORK_STATE);
        int permissionWRITE_EXTERNAL_STORAGE = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permissionREAD_EXTERNAL_STORAGE = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.READ_EXTERNAL_STORAGE);
        int permissionCAMERA = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.CAMERA);
        int permissionACCESS_FINE_LOCATION = ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION);

        List<String> listPermissionsNeeded = new ArrayList<>();

        if (permissionACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(android.Manifest.permission.ACCESS_NETWORK_STATE);
        }

        if (permissionWRITE_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (permissionREAD_EXTERNAL_STORAGE != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        if (permissionCAMERA != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
        }

        if (permissionACCESS_FINE_LOCATION != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    }

 public String saveImage(Bitmap myBitmap) {
        Random r = new Random();
        int min=100000;
        int maks=1000000;

        int random = r.nextInt((maks-min)+1)+min;


        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG,100,bytes);
        File wallpaperDirectory = new File(
                Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
        // have the object build the directory structure, if needed.
        if (!wallpaperDirectory.exists()) {
            wallpaperDirectory.mkdirs();
        }

        try {
            File f = new File(wallpaperDirectory, "ProfilFoto"+"foto"+random+".jpg");

            f.createNewFile();

            ////
            ///resmi kaydetmek localde kaydetmek için
            /// sadece galeriden görüntü aldıracağımız için kapatıyoruz.
            ///
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(getActivity(),
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
            //   Toast.makeText(this, f.getAbsolutePath(), Toast.LENGTH_SHORT).show();
            /*UploadVideo async = new UploadVideo(f.getAbsolutePath());
            async.execute();*/
            currentimgPath=f.getAbsolutePath();
            dosyaAd=f.getName();
            SharedPreferences sharedPref = getActivity().getSharedPreferences("sharedPref",Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("dosyaAdProfil", dosyaAd);
            System.out.println("dosyaAdProfil" + dosyaAd);
            editor.commit();
            return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";
    }

private void showPictureDialog(){
       /* AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("İşlem Seçiniz");
        String[] pictureDialogItems = {
                "Galeri'den Seç",
                "Kamera'dan Al" };
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                choosePhotoFromGallary();

                                break;
                            case 1:
                                takePhotoFromCamera();
                                break;
                        }
                    }
                });
        pictureDialog.show();*/
        if (!checkAndRequestPermissions()) {
            return;
        }
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getActivity());
        pictureDialog.setTitle("İşlem Seçiniz");
        String[] pictureDialogItems = {
                "Galeri'den Seç"};
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                choosePhotoFromGallary();
                                break;
                        }
                    }
                });
        pictureDialog.show();
    }

    public void choosePhotoFromGallary() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(galleryIntent, GALLERY);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_CANCELED) {
            return;
        }
        if (requestCode == GALLERY) {
            if (data != null) {
                Uri contentURI = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), contentURI);
                    // String path = saveImage(bitmap);
                    //  String pth=contentURI.getPath();

                    imageview.setImageBitmap(bitmap);
                    filept=getRealPathFromURI(contentURI);

                    //Toast.makeText(this, filept, Toast.LENGTH_SHORT).show();
                    saveImage(bitmap);




                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(getActivity(), "İşlem Başarısız!", Toast.LENGTH_SHORT).show();
                }
            }

        } else if (requestCode == CAMERA1) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            imageview.setImageBitmap(thumbnail);
            saveImage(thumbnail);
            Toast.makeText(getActivity(), "Görüntü Seçildi!", Toast.LENGTH_SHORT).show();


        }
    }
    public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().managedQuery( contentUri,
                proj, // Which columns to return
                null,       // WHERE clause; which rows to return (all rows)
                null,       // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
    }
    private void takePhotoFromCamera() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA1);
        // dispatchTakePictureIntent();
    }
like image 969
stakabekor Avatar asked Dec 10 '22 01:12

stakabekor


2 Answers

add this to manifest in application tag android:requestLegacyExternalStorage="true"

like image 175
s.j Avatar answered Jan 31 '23 23:01

s.j


There were major changes on how files can be accessed on Android 10

See https://developer.android.com/training/data-storage

You need to use MediaStore or Storage Access Framework (SAF), details https://developer.android.com/training/data-storage/shared for files outside of your App's private directories.

As you are storing photo then MediaStore would be the way to access pictures https://developer.android.com/training/data-storage/shared/media

Though as a quick fix is to temporarily opt out https://developer.android.com/training/data-storage/compatibility but this will only work until Android 11

Some better examples at https://proandroiddev.com/working-with-scoped-storage-8a7e7cafea3

like image 36
Andrew Avatar answered Feb 01 '23 00:02

Andrew