0

I'm trying to send an image that has been created using Canvas. there is no problem with the image and it can be displayed in ImageView.


this is the error I get:

D/onFailure: /storage/emulated/0/sign_3.png: open failed: ENOENT (No such file or directory)

I got the error even though I got permission to write and read external storage. where I found out from the following logs:

V/ContentValues: Permission is granted

this is my code to send the image:

mainactivityBinding.ivSignature.invalidate();
BitmapDrawable drawable = (BitmapDrawable) 
mainactivityBinding.ivSignature.getDrawable();
Bitmap bitmap = drawable.getBitmap();

if(isStoragePermissionGranted()){
      String root = Environment.getExternalStorageDirectory().toString();
        File myDir = new File(root);
        myDir.mkdirs();

        String fname = "sign_"+ Preferences.getKeyIdLogin(getBaseContext()) +".png";
        file = new File (myDir, fname);
        if (file.exists ()) file.delete ();
        try {
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        };
}

String token = Preferences.getKeyTokenLogin(getBaseContext());
RequestBody postToken = RequestBody.create(okhttp3.MultipartBody.FORM, token);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Partbody = MultipartBody.Part.createFormData("upload", file.getName(), reqFile);

Call<ResponseSign> call =getApi().postSign(postToken, body);
        call.enqueue(new Callback<ResponseSign>() {
            @Override
            public void onResponse(Call<ResponseSign> call, Response<ResponseSign> response) {
                String message = response.body().getMessage();
                Log.d("RESPON", "onResponse: " + message);
        }

            @Override
            public void onFailure(Call<ResponseEditProfil> call, Throwable t) {
                String message = response.body().getMessage();
                Log.d("RESPON", "onResponse: " + message);
            }
        });

this is the code for the given storage permission:

public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG,"Permission is granted");
                return true;
            } else {

                Log.v(TAG,"Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
            Log.v(TAG,"Permission is granted");
            return true;
        }
    }

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
            //resume tasks needing this permission
        }
    }

this is my Retrofit Interface:

    @Multipart
    @POST("postSign")
    Call<ResponseSign> postSign(@Part("token") RequestBody token, 
                                @Part MultipartBody.Part image);

this is the contents of my manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myapps">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:requestLegacyExternalStorage="true"
       android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I tried this app on android 11.
what should I do so that the image can be sent to the server? does the image really have to be saved in a file? or it can be sent directly without having to save to a file?

it's my first time trying to upload an image to the server, so sorry if there are some basics I don't understand.

Thank you.

qina
  • 13
  • 5
  • You are not using File.exists() before you try to upload it. Further you have no Toast() in that catch block to inform the user. Also you continue if there was a catch instead of stopping then. Please adapt your code. – blackapps Jun 16 '21 at 17:24
  • I've changed my code and did what you suggested. Turns out the error was on the device I was using. the device I use doesn't have external memory so I added a code to check whether the device has external memory or not. If it has external memory it will store in external memory and if not, it will be stored in internal memory. Thank you for responding to my question. I really appreciate it. – qina Jun 18 '21 at 12:37

1 Answers1

0

I know where I went wrong, I should have checked whether my device has external memory or not. If the device does not have external memory, the file will be stored on the internal memory.

if you want to know how to check internal and external memory you can see here: how to check internal and external storage if exist

qina
  • 13
  • 5