How to get saved photo from external storage and set it to an ImageView

JAVA CODE

public class MainActivity extends AppCompatActivity {

TextView mTextView;
Button mButton;
ImageView mImageView;
private File imageFile;

private static final int REQUEST_CODE=123;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mTextView= (TextView) findViewById(R.id.idTextView);
    mButton= (Button) findViewById(R.id.idButton);
    mImageView= (ImageView) findViewById(R.id.idImageView);

    Typeface mTypeFace=Typeface.createFromAsset(getAssets(),"fonts/contra-italic.ttf");
    mTextView.setTypeface(mTypeFace);

    //String path=Environment.getExternalStorageDirectory()+"/nabeel.jpg";

   File file=new File(Environment.getExternalStorageDirectory()+"/nabeel.jpg");
    if (file.exists())
    {
        mImageView.setImageURI(Uri.fromFile(file));

    }


    Toast.makeText(this,file.getAbsolutePath(),Toast.LENGTH_LONG).show();


    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            imageFile= new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"nabeel.jpg");
            Uri uri=Uri.fromFile(imageFile);

            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent,REQUEST_CODE);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode==REQUEST_CODE){

        switch (resultCode){

            case AppCompatActivity.RESULT_OK:
                Toast.makeText(this,"File stored at " +imageFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
                break;
            case AppCompatActivity.RESULT_CANCELED:
                Toast.makeText(this,"File not stired Properly",Toast.LENGTH_LONG).show();
                break;
        }
    }
}

}

Question

From the above code i can take picture using a button and saved it to an external storage but i want to show that image with the ImageView once it has been saved.... tried with

Still not working and not able to show image in the imageview How can i show the captured image with imageview as soon as it get saved to the external storage

Worked with Picasso library

i have coded somthing like this but still cant make the image visible

      File file=new 
      File(Environment.getExternalStorageDirectory()
      .getAbsolutePath()+"/nabeel.jpg");

      Toast.makeText(MainActivity.this,file.getAbsolutePath(),
      Toast.LENGTH_LONG).show();

    Picasso.with(this).load(file.getAbsolutePath()).into(mImageView);

The toast message show the exact path for the image but not displays in the image view how can i make this work

QUESTION 2

I have noticed that when i use the below line to get a path i doesn't shows image

   preview_Picture_File_directory=
    Environment.getExternalStorageDirectory().getAbsolutePath();

But as u used a code to get path and it show the image as well

   preview_Picture_File_directory = 
   getExternalFilesDir("images").getAbsolutePath();

What is the diffrence between this two????

1 answer

  • answered 2018-03-11 16:25 Rabee

    Try the following:

    public class Demo9 extends AppCompatActivity {
    
    private Button b;
    private ImageView iv;
    private CheckBox cb;
    private TextView tv;
    
    private final int PICTURE_ACTIVITY_CODE = 1;
    private File preview_Picture_File_directory = null;
    private File captured_image_file;
    private boolean flag = false;
    private String file_path_image_file;
    private boolean flag_1 = false;
    
    private String foldername = "My_Images";
    private String file_name = "x";
    private String file_extension = "jpg";
    
    
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo9);
    
        iv = (ImageView) findViewById(R.id.iv);
        cb = (CheckBox) findViewById(R.id.cb);
        tv = (TextView) findViewById(R.id.tv);
    
        b = (Button) findViewById(R.id.b);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    
                if(cb.isChecked()) {
                    preview_Picture_File_directory = getExternalFilesDir(foldername);//creates a folder inside /Android/data/(your package name)/files directory----More : https://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
                }else{
                    preview_Picture_File_directory = Environment.getExternalStoragePublicDirectory(foldername);//creates a folder inside root (same place where Android folder above is created)----More: https://developer.android.com/reference/android/os/Environment.html#getExternalStoragePublicDirectory(java.lang.String)
                }
    
                String p = Environment.getExternalStorageDirectory().getAbsolutePath(); // get you to the root directory where Android and foldername(case 2) are created----More : https://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory()
                Log.e("getExternalStorageDirec","*********"+p);
    
                captured_image_file = new File(preview_Picture_File_directory.getAbsolutePath() + "/" + file_name + "." + file_extension);
    
                if(!cb.isChecked()){ // check box is not checked, using Environment.getExternalStoragePublicDirectory(foldername) to create a new folder called foldername - need to check if this new folder exists.
                    if(!preview_Picture_File_directory.exists()) {
                        flag_1 = preview_Picture_File_directory.mkdirs();
                    }
                }else{ // No need to check if this folder exists.
                    flag_1 = true;
                }
    
                if(flag_1) {
                    if (!captured_image_file.exists()) { // file doesn't exist
                        Log.e("File doesn't exists", "Creating File");
                        try {
                            flag = captured_image_file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                            flag = false;
                        }
                    } else {
                        flag = true; // file will be over-written
                    }
                    if (flag) {
                        Log.e("Creation", "Succeeded");
                        file_path_image_file = captured_image_file.getAbsolutePath();
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        Uri outputFileUri = Uri.fromFile(captured_image_file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                        startActivityForResult(intent, PICTURE_ACTIVITY_CODE);
    
                    }
                }
            }
        });
    
    }
    
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == PICTURE_ACTIVITY_CODE) {
            if (resultCode == RESULT_OK) {
                Uri inputFileUri = Uri.fromFile(captured_image_file);
                Bitmap image = BitmapFactory.decodeFile(inputFileUri.getPath());
                tv.setText("path:  "+preview_Picture_File_directory+"/"+file_name+"."+file_extension);
                iv.setImageBitmap(image);
            }else{
                // handle partially created file
                }
    
            }
        }
    
    }
    

    demo9.xml-----------------

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center">
    
    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        tools:ignore="contentDescription"
        android:id="@+id/iv"/>
    
    <Button
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:text="Take Pic"
        android:id="@+id/b"/>
    
    <LinearLayout
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:weightSum="100">
    
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="20"
        android:checked="true"
        android:id="@+id/cb"/>
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_weight="80"
        android:textSize="20sp"
        android:text="xxxxxxxx"
        android:id="@+id/tv"/>
    
    </LinearLayout>
    
    </LinearLayout>