I want to load an image in an image view from the gallery on the phone and I have written the code java:
public class MainActivity extends AppCompatActivity {
private static int RESULT_LOAD_IMAGE = 1;
Button btnTry , btnAdd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = findViewById(R.id.btnAdd);
btnTry = findViewById(R.id.btnTry);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//The integer argument is a "request code" that identifies your request. When you receive the result Intent,
// the callback provides the same request code so that your app can properly identify the result and determine how to handle it.
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i ,RESULT_LOAD_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && requestCode == RESULT_OK && null != data){
Uri selectImage = data.getData();
String[] filePathcolumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectImage , filePathcolumn , null , null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathcolumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView ivMemeImage = findViewById(R.id.ivMemeImage);
ivMemeImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
}
when I run the app and hit the add button image does not load in the image view. and I have given both the read and write permission in the manifest.
You can display your image using your Uri. you only need to do is set your imageView.setImageUri(selectedImage)
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
your_imageView.setImageURI(selectedImage);
}
is this code you have done in android studio?
if(requestCode == RESULT_LOAD_IMAGE && requestCode == RESULT_OK && null != data)
it should be
if(requestCode == RESULT_LOAD_IMAGE && requestCode == RESULT_OK && data!=null)
Your code should give you compile time error
check out Picasso library .. http://square.github.io/picasso/
load image from a URI into imageview with one line of code:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.