A.S
A.S

Reputation: 816

Get path of a drawable image so that I can post it to the backend

I have a set of icons stored in the drawable folder.

Based on users selection I'll be posting these icons to the backend.

When I try to retrieve the path for these drawables, I get the following error

HTTP FAILED: java.io.FileNotFoundException: (No such file or directory)

This is how I am getting the path

public String getURLForResource (int resourceId) {
        return Uri.parse("android.resource://"+ BuildConfig.APPLICATION_ID+"/" +resourceId).toString();
    }

File fileToUpload  = new File(getURLForResource(R.drawable.icon));

I have referred the following link says that it's not possible to retrieve the path for a drawable.

Any idea on how I can solve this problem?

Upvotes: 0

Views: 198

Answers (1)

Khemraj Sharma
Khemraj Sharma

Reputation: 58934

As solution you can write your drawable to file.

Convert drawable to bitmap

Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.your_drawable);

Save bitmap to file

String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path, "image" + System.currentTimeMillis() + ".jpg");
try (FileOutputStream out = new FileOutputStream(file)) {
    bm.compress(Bitmap.CompressFormat.PNG, 100, out);
    out.flush(); // Not really required
    out.close(); // do not forget to close the stream
} catch (IOException e) {
    e.printStackTrace();
}

You can use file now.

Upvotes: 1

Related Questions