0

I am trying to organize about 50 images in the "logo" folder, not in "drawable", but I don't know how to get the base path of the folder.

I tried:

String path = "src/main/logo/ataturk.png";
File imgFile = new File(path);
if (imgFile.exists()) {
    ImageView imgLogo = myView.findViewById(R.id.imageView_logo);
    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    imgLogo.setImageBitmap(myBitmap);
}

but it's not working.

Pang
  • 9,564
  • 146
  • 81
  • 122
Lomado
  • 3
  • 1

1 Answers1

0

You cannot access file under a package folder. So put them under assets folder like; /src/main/assets/logo/SUB_DIR/FILENAME.png

Then you can access them getContext().getResources().getAssets().open('logo/SUB_DIR/FILENAME.png')

To check if file exists on asset folder use the following code;

private boolean fileExists(String folder, String fileName) {

    try {
        String[] files = getResources().getAssets().list(folder);

        for(String file : files) {
            if(file.equals(fileName)) {
                return true;
            }
        }

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

    return false;
}

Call that method as follows

img = (ImageView) findViewById(R.id.imgSDCard);
if(fileExists("logo/sub", "sd_card_enable.png")) {
        // asset folder has file
        try {
            img.setImageDrawable(Drawable.createFromStream(getAssets().open("logo/sub/sd_card_enable.png"), "sd_card_enable.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Copy your files into the assets folder like following picture; (logo is a DIR, and sub is a DIR inside logo)

enter image description here

ddassa
  • 309
  • 1
  • 6
  • not working with me , i moved them to drawable folder String path = "android.resource://" + BuildConfig.APPLICATION_ID + "/drawable/img.png"; File imgFile = new File(path); if (imgFile.exists()) { ImageView imgLogo = myView.findViewById(R.id.imageView_logo); Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); imgLogo.setImageBitmap(myBitmap); } but it look like file not exist – Lomado Mar 20 '18 at 15:00
  • What you trying to do? You dont need to check files in drawable exists or not. If id is there, means file is there. Android wont create ids for files that does not exists. If you can express what you actually trying to achieve might be able to help! – ddassa Mar 20 '18 at 16:02
  • I have update the answer, please have a look, but still my question is what is your end goal? Just curious – ddassa Mar 20 '18 at 16:15