Home > database >  How to load image from local storage using Glide
How to load image from local storage using Glide

Time:04-07

I would like to load to imageView one image from pictures directory. With this code I alway get error, however the file exist.

This is very primitive example. It is needed for bigger project, but I want to make it as simple as possible.

build.gradle (module - only important part of code):

android {
    compileSdk 32

    defaultConfig {
        minSdk 28
        targetSdk 32
        versionCode 1

dependencies {
 implementation "com.github.bumptech.glide:glide:4.13.0"
}

glide 4.13.0 should be lattest version

AndroidActivity.xml(only important part):

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

    <application
        android:requestLegacyExternalStorage="true"
        android:usesCleartextTraffic="true"

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 999) // to get permission read from external storage
  
        val image1: ImageView = findViewById(R.id.imageView)
        val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()).list()?.get(0)

        Glide.with(this)
            .asBitmap()
            .load(file)
            .into(image1)
}

When I debug my code I see that variable file exists and its name is IMG_20220317_085955.jpg

Error message:

java.io.FileNotFoundException(open failed: ENOENT (No such file or directory))
     call GlideException#logRootCauses(String) for more detail
          Cause (1 of 1): class java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)
I/Glide: Root cause (1 of 3)
    java.io.FileNotFoundException: /IMG_20220317_085955.jpg: open failed: ENOENT (No such file or directory)
        at libcore.io.IoBridge.open(IoBridge.java:492)

CodePudding user response:

To get full path I used

 val file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString()   "/"   Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).list()
            ?.get(0)
            .toString()

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) will generate path Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).list()?.get(0) get first image (if exists)

  • Related