我正在开发一个Android应用程序,我想在其中显示用户详细信息,其中包括用户的个人资料图片。现在我只想在ImageView
上的图库中显示所选图像。我通过互联网搜索并找到了以下代码,但它似乎对我不起作用。这是代码:
public class UserProfile extends android.support.v4.app.Fragment {
UserLocalStore userLocalStore;
TextView etUsername, etGender, etMob, etMail;
Button bLogout;
ImageView imageView;
private static final int RESULT_LOAD = 999;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.user_profile_layout,container,false);
imageView = (ImageView) view.findViewById(R.id.userImage);
etUsername = (TextView) view.findViewById(R.id.etUsername);
etGender = (TextView) view.findViewById(R.id.etGender);
etMob = (TextView) view.findViewById(R.id.etMob);
etMail = (TextView) view.findViewById(R.id.etMail);
bLogout = (Button) view.findViewById(R.id.bLogout);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD);
}
});
bLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
Intent loginIntent = new Intent(getActivity(), SplashScreenTabbed.class);
startActivity(loginIntent);
}
});
try {
userLocalStore = new UserLocalStore(getActivity());
User user = userLocalStore.getLoggedInUser();
etUsername.setText(user.username);
etGender.setText(user.gender);
etMob.setText(user.mobile);
etMail.setText(user.email);
}catch (Exception e){e.printStackTrace();Toast.makeText(getActivity(),"Can't Connect To Server",Toast.LENGTH_SHORT).show();}
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try{
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == Activity.RESULT_OK && data != null) {
String path = getPathFromCameraData(data, this.getActivity());
Bitmap bitmap = BitmapFactory.decodeFile(path);
// Set the Image in ImageView after decoding the String
imageView.setImageBitmap(bitmap);
}
else
{
Toast.makeText(getActivity(), "Hey pick your image first",Toast.LENGTH_LONG).show();
}
} catch (Exception e)
{
Toast.makeText(getActivity(), "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public static String getPathFromCameraData(Intent data, Context context) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return picturePath;
}
}
当我在活动中使用它时,此代码可以正常工作,但它在片段中不起作用。如果我从图库中选择图像,那么它将进入catch()
块,否则它将打印来自else
部分的消息。请帮帮我们!
答案 0 :(得分:2)
这是我的例子。这是经过测试的代码。
public class ImageSelector extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.createevent,container,false);
imgcover = (ImageView) view.findViewById(R.id.newcover_img);
btnupload = (Button) view.findViewById(R.id.newcover_upload);
btnupload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImg = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImg,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
imgcover = (ImageView) findViewById(R.id.newcover_img);
imgcover .setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
}
}
帮助你。
答案 1 :(得分:0)
private static int RESULT_LOAD_IMG = 1;
imageView_profilepic = (ImageView).findViewById(R.id.imageView_Profile_Pic);
imageView_profilepic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMG);
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == getActivity().RESULT_OK
&& null != data) {
// Get the Image from data
decodeUri(data.getData());
} else {
Toast.makeText(getActivity(), "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public void decodeUri(Uri uri) {
ParcelFileDescriptor parcelFD = null;
try {
parcelFD = getActivity().getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor imageSource = parcelFD.getFileDescriptor();
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(imageSource, null, o);
// the new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2);
imageView_profilepic.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// handle errors
} catch (IOException e) {
// handle errors
} finally {
if (parcelFD != null)
try {
parcelFD.close();
} catch (IOException e) {
// ignored
}
}
}
答案 2 :(得分:0)
嗯,这是一个愚蠢的错误/异常:
09-17 21:09:46.381 2292-2292/app.usrete.jayant.delvemitt W/System.err﹕ java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/16 from pid=2292, uid=10062 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
,我没有在清单中添加读取权限。添加它解决了这个问题。顺便说一句,谢谢你们帮助我。