package com.example.sugandhabansal.gallerypickimage;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private static final int SELECTED_PIC = 1;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
}
public void btnClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, SELECTED_PIC);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECTED_PIC:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filepath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(filepath);
Drawable drawable = new BitmapDrawable(Resources.getSystem(), bitmap);
imageView.setBackground(drawable);
}
break;
default:
break;
}
}
}
这是MainActivity.java文件。代码基本上从库中加载图像并将其显示在布局的imageview部分中。 当我在我的智能手机上运行apk时,在选择之后在imageview部分中没有看到图像,并且在调试之后看到位图等于null。 有人可以帮助我解决这个问题,因为我无法解决这个问题。
答案 0 :(得分:2)
如果上面的内容没问题且你仍然得到null结果,请尝试以下代码:
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));