altern4te
altern4te

Reputation: 23

My image can't be loaded into my ImageView. What went wrong?

I'm trying to load a specific image from my directory into the ImageView on my app, but it's not working. The whole thing became blank. Can someone please take a look and see where my code went wrong? Thanks!

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image_viewer);

    ImageView imageView = (ImageView) findViewById(R.id.iv);

    try {
       //this toast below appears
        Toast.makeText(getApplicationContext(), "try",  Toast.LENGTH_LONG).show(); 

       //below is the path for the image
        Uri uri = Uri.parse("file://sdcard/myFoodDiary/snaps/default.jpg");

        System.out.println("Image URI: " + uri.toString());
        imageView.setImageURI(uri);

    } catch (Exception e) {
        // TODO: handle exception
        Toast.makeText(getApplicationContext(), "oops", Toast.LENGTH_LONG).show();
    }

}

Upvotes: 0

Views: 377

Answers (2)

Phantômaxx
Phantômaxx

Reputation: 38098

I think this is not a valid path:

Uri.parse("file://sdcard/myFoodDiary/snaps/default.jpg");

Try

Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/myFoodDiary/snaps/default.jpg");

But I'd better do something like

File file = new File (Environment.getExternalStorageDirectory() + "/myFoodDiary/snaps/default.jpg");
ImageView imageView = (ImageView) findViewById(R.id.iv);
imageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));

Upvotes: 2

altern4te
altern4te

Reputation: 23

For anyone interested, correct codes as Artoo Detoo states:

File file = new File (Environment.getExternalStorageDirectory() + "/myFoodDiary/snaps/default.jpg");
ImageView imageView = (ImageView) findViewById(R.id.icon);
imageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));

Upvotes: 0

Related Questions