从图库选择的图像在ImageView中消失了。

huangapple go评论66阅读模式
英文:

Image Picked from Gallery ImageView Disappeard

问题

public class FirstFragment extends Fragment implements View.OnClickListener {
    ImageView imageButton1;
    ImageButton imageButton2;
    private Uri mImageUri;
    private File mSnapFile;

    private static final String ARG_URI_IMAGE_1 = "image1Uri";
    private static final String ARG_URI_IMAGE_2 = "image2Uri";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_first, container, false);
        imageButton1 = (ImageView) v.findViewById(R.id.firstimagebtn);
        imageButton2 = (ImageButton) v.findViewById(R.id.secondimagebtn);
        imageButton1.setOnClickListener(this::onClick);
        imageButton2.setOnClickListener(this::onClick);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String mImageUri = preferences.getString("image", null);
        if (mImageUri != null) {
            imageButton2.setImageURI(Uri.parse(mImageUri));
        } else {
            imageButton2.setImageResource(R.mipmap.ic_launcher);
        }
        return v;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.firstimagebtn:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 0);
                break;
            case R.id.secondimagebtn:
                Intent intent2 = new Intent(Intent.ACTION_PICK);
                intent2.setType("image/*");
                startActivityForResult(intent2, 1);
                break;
        }
    }

    private void handleImageSelect(@Nullable Intent intent) {
        if (saveContentLocally(intent)) {
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(mSnapFile));
                imageButton1.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                throw new IllegalStateException("Saved the image file, but it doesn't exist!");
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == Activity.RESULT_OK) {
                    handleImageSelect(data);
                }
                break;
            case 1:
                if (resultCode == Activity.RESULT_OK) {
                    mImageUri = data.getData();
                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putString("image", String.valueOf(mImageUri));
                    editor.commit();
                    imageButton2.setImageURI(mImageUri);
                    imageButton2.invalidate();
                }
                break;
        }
    }

    private boolean saveContentLocally(@Nullable Intent intent) {
        if (intent == null || intent.getData() == null) {
            return false;
        }
        InputStream inputStream;
        try {
            inputStream = getActivity().getContentResolver().openInputStream(intent.getData());
        } catch (FileNotFoundException e) {
            Toast.makeText(getActivity(), "Could not open file", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (inputStream == null) {
            Toast.makeText(getActivity(), "File does not exist", Toast.LENGTH_SHORT).show();
            return false;
        }
        try {
            copyFile(inputStream, mSnapFile);
        } catch (IOException e) {
            Toast.makeText(getActivity(), "Failed save file locally", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private static void copyFile(InputStream inputStream, File file) throws IOException {
        byte[] buffer = new byte[1024];
        int length;

        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
        }
    }
}
英文:

I have a tabLayout with ImageView and when I Pick A image from the gallery and display it to Imageview then when I close the app the selected image is gone then I need to pick an image again.

And I know this one looks the same as my question but still not working
https://stackoverflow.com/questions/18668377/saving-image-picked-from-gallery-for-future-use

I tried this code but the image still disappeared
https://github.com/martinsing/Image-Save-And-Retrieve-App

I also Read this other question but no one works
https://stackoverflow.com/questions/54519952/image-in-imageview-disappear

public class FirstFragment extends Fragment implements View.OnClickListener{
ImageView imageButton1;
ImageButton imageButton2;
private Uri mImageUri;
private File mSnapFile;
private static final String ARG_URI_IMAGE_1 = "image1Uri";
private static final String ARG_URI_IMAGE_2 = "image2Uri";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_first, container, false);
imageButton1 = (ImageView) v.findViewById(R.id.firstimagebtn);
imageButton2 = (ImageButton)v.findViewById(R.id.secondimagebtn);
imageButton1.setOnClickListener(this::onClick);
imageButton2.setOnClickListener(this::onClick);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
imageButton2.setImageURI(Uri.parse(mImageUri));
} else {
imageButton2.setImageResource(R.mipmap.ic_launcher);
}
return v;
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.firstimagebtn:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent,0);
break;
case R.id.secondimagebtn:
Intent intent2 = new Intent(Intent.ACTION_PICK);
intent2.setType("image/*");
startActivityForResult(intent2,1);
break;
}
}
private void handleImageSelect(@Nullable Intent intent) {
if (saveContentLocally(intent)) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(mSnapFile));
imageButton1.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
throw new IllegalStateException("Saved the image file, but it doesn't exist!");
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case 0:
if(resultCode == Activity.RESULT_OK){
handleImageSelect(data);
}
break;
case 1:
if(resultCode == Activity.RESULT_OK){
mImageUri = data.getData();
// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(mImageUri));
editor.commit();
// Sets the ImageView with the Image URI
imageButton2.setImageURI(mImageUri);
imageButton2.invalidate();
}
break;
}
}
/**
* Saves the file from the ACTION_PICK Intent locally to {@link #mSnapFile} to be accessed by our FileProvider
*/
private boolean saveContentLocally(@Nullable Intent intent) {
if (intent == null || intent.getData() == null) {
return false;
}
InputStream inputStream;
try {
inputStream = getActivity().getContentResolver().openInputStream(intent.getData());
} catch (FileNotFoundException e) {
Toast.makeText(getActivity(), "Could not open file", Toast.LENGTH_SHORT).show();
return false;
}
if (inputStream == null) {
Toast.makeText(getActivity(), "File does not exist", Toast.LENGTH_SHORT).show();
return false;
}
try {
copyFile(inputStream, mSnapFile);
} catch (IOException e) {
Toast.makeText(getActivity(), "Failed save file locally", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private static void copyFile(InputStream inputStream, File file) throws IOException {
byte[] buffer = new byte[1024];
int length;
try (FileOutputStream outputStream = new FileOutputStream(file)) {
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
}
}

答案1

得分: 1

不要使用ACTION_PICK,因为在重新启动后,获取的URI将不再有效。

相反,使用ACTION_OPEN_DOCUMENT,并在onActivityResult中获取可持续的URI权限。

英文:

Do not use ACTION_PICK as then the obtained uri is not valid anymore after restart.

Instead use ACTION_OPEN_DOCUMENT and take persistable uri permissions in onActivityResult.

huangapple
  • 本文由 发表于 2020年10月20日 22:26:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/64447263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定