我试图从galery照片添加到一个ImageView
,但我得到这个错误:
了java.lang.RuntimeException:失败递送结果ResultInfo {谁= NULL,请求= 1,结果= -1,数据=意向{DAT =含量://媒体/外部/图像/培养基/ 1}}至{活动hotMetter。包/ hotMetter.pack.GetPhoto}:显示java.lang.NullPointerException
这是我的代码:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
Bitmap bitmap=null;
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
tv.setText(selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
我得到的selectedImagePath="mnt/sdcard/DCIM/myimage"
但img.setImageURI(selectedImageUri);
我得到的错误。
我也用一个Bitmap
,并试图设置从图像SetImageBitmap
,但我得到了同样的错误。
logcat的:
05-06 19:41:34.191: E/AndroidRuntime(8466): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/1 }} to activity {hotMetter.pack/hotMetter.pack.GetPhoto}: java.lang.NullPointerException
05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532)
05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574)
05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.access$2000(ActivityThread.java:117)
05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961)
05-06 19:41:34.191: E/AndroidRuntime(8466): at android.os.Handler.dispatchMessage(Handler.java:99)
05-06 19:41:34.191: E/AndroidRuntime(8466): at android.os.Looper.loop(Looper.java:123)
05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-06 19:41:34.191: E/AndroidRuntime(8466): at java.lang.reflect.Method.invokeNative(Native Method)
05-06 19:41:34.191: E/AndroidRuntime(8466): at java.lang.reflect.Method.invoke(Method.java:507)
05-06 19:41:34.191: E/AndroidRuntime(8466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-06 19:41:34.191: E/AndroidRuntime(8466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-06 19:41:34.191: E/AndroidRuntime(8466): at dalvik.system.NativeStart.main(Native Method)
05-06 19:41:34.191: E/AndroidRuntime(8466): Caused by: java.lang.NullPointerException
05-06 19:41:34.191: E/AndroidRuntime(8466): at hotMetter.pack.GetPhoto.onActivityResult(GetPhoto.java:55)
05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.Activity.dispatchActivityResult(Activity.java:3908)
05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528)
建议please.Thanks!
Answer 1:
调试模式运行应用程序,并设置一个断点,如果(requestCode == SELECT_PICTURE)
检查每个变量作为您逐步完成,以确保按预期被设定。 如果您收到一个NPE img.setImageURI(selectedImageUri);
那么无论img
或selectedImageUri
未设置。
Answer 2:
简单的传球Intent
第一:
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
你会得到你的图片路径onActivityResult
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
完整的源代码在这里
Answer 3:
尝试以下方法:
import java.io.FileDescriptor;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ImageGalleryDemoActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.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 && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
Bitmap bmp = null;
try {
bmp = getBitmapFromUri(selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageBitmap(bmp);
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
Answer 4:
@ parag代码的伟大工程。 但是,在加载一些大的图像,你可能会失败。 您应该使用;
imageView.setImageBitmap(getScaledBitmap(picturePath, 800, 800));
代替;
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
这里是我的方法,你可以使用。
private Bitmap getScaledBitmap(String picturePath, int width, int height) {
BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
sizeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, sizeOptions);
int inSampleSize = calculateInSampleSize(sizeOptions, width, height);
sizeOptions.inJustDecodeBounds = false;
sizeOptions.inSampleSize = inSampleSize;
return BitmapFactory.decodeFile(picturePath, sizeOptions);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
Answer 5:
这是为了得到画廊和作物屁股图像以及最简单的方法
步骤1:对StartActivity结果
imageUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
}
});
步骤2:处理结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == 1) {
final Bundle extras = data.getExtras();
if (extras != null) {
//Get image
Bitmap ProfilePic = extras.getParcelable("data");
imageUser.setImageBitmap(ProfilePic);
TextView t=(TextView)findViewById(R.id.textoverimage);
t.setText("image Selected");
}
}
}
Answer 6:
我认为,最简单的方法是用库ContentManager。 该库从一个设备库,云或相机获取的照片或视频。 与来自云异步负载和修复的错误对一些问题的设备。
通过摇篮下载: compile 'com.github.stfalcon:contentmanager:0.4.3'
您可以找到文档https://github.com/stfalcon-studio/ContentManager
Answer 7:
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView);
}
public void btn_gallery(View view) {
Intent intent =new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent,100);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==100 && resultCode==RESULT_OK)
{
Uri uri = data.getData();
img.setImageURI(uri);
}
}
}
Answer 8:
我觉得你的ImageView的IMG不会被实例化其为null编译器; 这就是为什么一个NullPointerException异常升高
你在你的活动调用
img = (ImageView) findViewById(R.id.my_imageview);
其中my_imageview是您的ImageView控件的ID!
Answer 9:
原来答案是你的道路已经加入前缀像Uri.parse(“文件://” + file.getPath);
Answer 10:
下面是代码,这为我工作。
Button buttonLoadImage = (Button) findViewById(R.id.button4);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.putExtra("crop", "true");
intent.putExtra("scale", true);
intent.putExtra("outputX", 256);
intent.putExtra("outputY", 256);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);}});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) {
if (requestCode == RESULT_LOAD_IMAGE && data != null) {
Uri imageUri = data.getData();
imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageURI(imageUri);}}}
在清单文件中添加
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Answer 11:
下面放代码在按钮单击事件
Intent ImageIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI); //implicit intent
UploadImage.this.startActivityForResult(ImageIntent,99);
下面放码startActivityforResult事件
Uri ImagePathAndName = data.getData();
imgpicture.setImageURI(ImagePathAndName);
Answer 12:
@Parag肖汉soltution运作良好,但我有问题 - 一些文件管理器应用程序在意图对象返回“文件:/// ......”而不是“内容:// ...” - 这是使用查询所需。
还有就是我对这个问题简短的解决方案:
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
if("content".equals(contentUri.getScheme())) {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else{
return contentUri.getPath();
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
基于@Parag解决方案,
这里部分解决方案(@nobre) 安卓获取文件URI从内容URI?
这里parital溶液(@Nikolay) 从URI从mediastore获取文件名和路径
Answer 13:
parag,肖汉和devrim答案是完美的,但我改变onActivityResult没有光标,它使代码更美好。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(getScaledBitmap(selectedImage,800,800));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
private Bitmap getScaledBitmap(Uri selectedImage, int width, int height) throws FileNotFoundException {
BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
sizeOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions);
int inSampleSize = calculateInSampleSize(sizeOptions, width, height);
sizeOptions.inJustDecodeBounds = false;
sizeOptions.inSampleSize = inSampleSize;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, sizeOptions);
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested one
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
文章来源: Android get image from gallery into ImageView