我正在创建一个简单的Android应用程序,让用户从图库中选择一个图像。
我使用Picasso从onActivityResult中加载图像,使用data.getData();
但是如果我打开另一个片段,然后我又返回到它,它不会加载所选择的图像。
我已经尝试将filePath放入文件中,正如您现在所看到的,它已转换为字符串,但没有任何反应。 Log说String包含这样的内容:
/storage/emulated/0/DCIM/Camera/IMG_20170517_120403.jpg
以下是代码:
片段
package com.garro.vanderbiltchatapp.Fragments;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.garro.vanderbiltchatapp.R;
import com.garro.vanderbiltchatapp.Utils.ImageFilePath;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
/**
* Created by garro on 16/05/2017.
*/
public class FragmentPresentation extends Fragment {
private static final int SELECT_IMAGE = 102 ;
private static final String TAG = "FragmentPresentation";
private ImageView smallImageView, largeImageView;
private TextView userTextView;
private ProgressBar progressBar;
private FirebaseUser user;
String selectedImagePath;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_presentation, container, false);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().setTitle(R.string.title_presentation);
getActivity().setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
smallImageView = (ImageView)getActivity().findViewById(R.id.smallImageViewPresentation);
largeImageView = (ImageView)getActivity().findViewById(R.id.largeImageViewPresentation);
userTextView = (TextView)getActivity().findViewById(R.id.userTextView);
progressBar = (ProgressBar)getActivity().findViewById(R.id.progressBar);
user = FirebaseAuth.getInstance().getCurrentUser();
// Here I try to reload the Image but nothing happens
try{
if(!selectedImagePath.equals("")){
Picasso
.with(getActivity())
.load(selectedImagePath)
.placeholder(R.drawable.logo)
.into(largeImageView);
}
}catch (NullPointerException e){
e.printStackTrace();
}
largeImageView.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, getString(R.string.select_picture)),SELECT_IMAGE);
}
});
if (user != null) {
// Here we set the userLabel to the current user email
userTextView.setText(user.getEmail());
Picasso.with(getActivity())
.load(user.getPhotoUrl())
.placeholder(R.drawable.logo)
.error(R.drawable.logo)
.fit()
.centerInside()
.into(smallImageView, new Callback() {
@Override
public void onSuccess() {
Bitmap imageBitmap = ((BitmapDrawable)
smallImageView.getDrawable()).getBitmap();
RoundedBitmapDrawable imageDrawable =
RoundedBitmapDrawableFactory.create(getResources(), imageBitmap);
imageDrawable.setCircular(true);
imageDrawable.setCornerRadius(
Math.max(imageBitmap.getWidth(),
imageBitmap.getHeight()) / 2.0f);
smallImageView.setImageDrawable(imageDrawable);
}
@Override
public void onError() {
}
});
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_IMAGE)
{
if (resultCode == Activity.RESULT_OK)
{
if (data != null)
{
progressBar.setVisibility(View.VISIBLE);
largeImageView.setClickable(false);
Picasso
.with(getActivity())
.load(data.getData())
.placeholder(R.drawable.logo)
.into(largeImageView, new Callback() {
@Override
public void onSuccess() {
progressBar.setVisibility(View.GONE);
largeImageView.setClickable(true);
Uri selectedImageUri = data.getData();
//MEDIA GALLERY
selectedImagePath = ImageFilePath.getPath(getActivity(), selectedImageUri);
Log.i(TAG, ""+selectedImagePath);
// I will do nothing with this but
// it's only to show how to get the right Path from
// gallery
}
@Override
public void onError() {
}
});
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(getActivity(), "Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
}

ImageFilePath.java
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
/**
* Created by garro on 17/05/2017.
*/
public class ImageFilePath {
/**
* Method for return file path of Gallery image
*
* @param context
* @param uri
* @return path of the selected image file from gallery
*/
public static String getPath(final Context context, final Uri uri)
{
// DocumentProvider
if (DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}

片段布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp">
<ImageView
android:id="@+id/largeImageViewPresentation"
android:layout_width="match_parent"
android:layout_height="200dp"
android:clickable="true"
android:src="@drawable/logo"/>
<ImageView
android:id="@+id/smallImageViewPresentation"
android:layout_margin="5dp"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="@drawable/logo"
app:layout_anchor="@+id/largeImageViewPresentation"
app:layout_anchorGravity="top|left" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
app:layout_anchor="@+id/largeImageViewPresentation"
app:layout_anchorGravity="top|right" />
</android.support.design.widget.CoordinatorLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="@string/welcome"
android:textStyle="bold|italic"
android:textSize="30sp"
android:textColor="@color/colorPrimaryDark"
android:layout_weight="1"/>
<TextView
android:id="@+id/userTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="@string/User"
android:textStyle="bold|italic"
android:textSize="30sp"
android:textColor="@color/colorPrimary"
android:layout_weight="1"/>
</LinearLayout>
&#13;
为什么在重新创建片段或应用程序停止后重新加载图像?
此应用使用FirebaseDatabase,如果将图像存储在FirebaseStorage并检索它可能很有用,我就去做。但我该怎么办?
请告诉我最好的解决方案。
非常感谢。