如何通过onSaveInstanceState保存和检索图像的URI?

时间:2019-03-09 20:41:43

标签: java android uri android-bitmap

我正在尝试改变方向。此刻,当我旋转手机时,片段中的图像消失了。这显然是因为该活动已被破坏并重新创建。我决定不尝试保存像图像这样的大数据,而是通过在Uri方法中保存图像的onSaveInstanceState来解决此问题:

@Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("imageUri", imageUri);
    }

在片段的onCreateView中,我也想着空的可能性,试图检索Uri并将其粘贴回ImageView中。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_top_image, container, false);

        imageView = view.findViewById(R.id.meme_image_view);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedImage(v);
            }
        });

        topTextView = view.findViewById(R.id.top_text_view);
        bottomTextView = view.findViewById(R.id.bottom_text_view);

        if(savedInstanceState != null){
            if(imageUri != null){
                Uri savedUri = savedInstanceState.getParcelable("imageUri");
                imageView.setImageURI(savedUri);
            }
        }

        return view;
    }

由于某种原因,它不起作用。旋转手机时图像仍然丢失。

完整片段:

public class TopImageFragment extends Fragment {

    ImageView imageView;
    TextView topTextView, bottomTextView;
    public static final int PICK_IMAGE = 1;
    Uri imageUri;
    int counter = 0;
    String timeStamp = new SimpleDateFormat("yyyyMMdd").format(new Date());

    MemeViewModel memeViewModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_top_image, container, false);

        imageView = view.findViewById(R.id.meme_image_view);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedImage(v);
            }
        });

        topTextView = view.findViewById(R.id.top_text_view);
        bottomTextView = view.findViewById(R.id.bottom_text_view);

        if(savedInstanceState != null){
            Uri savedUri = savedInstanceState.getParcelable("imageUri");
            imageView.setImageURI(savedUri);
        }

        return view;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable("imageUri", imageUri);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        memeViewModel = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(MemeViewModel.class);

        memeViewModel.getTopText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
            @Override
            public void onChanged(@Nullable CharSequence charSequence) {
                topTextView.setText(charSequence);
            }
        });

        memeViewModel.getBottomText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
            @Override
            public void onChanged(@Nullable CharSequence charSequence) {
                bottomTextView.setText(charSequence);
            }
        });
    }

    public void selectedImage(View v) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE);
    }

    public void createBitmapAndSave(ImageView img) {

        BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
        Bitmap bitmap = bitmapDrawable.getBitmap();
        Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);

        String topText = topTextView.getText().toString();
        String bottomText = bottomTextView.getText().toString();

        Canvas canvas = new Canvas(mutableBitmap);
        TextPaint topPaint = new TextPaint();
        TextPaint bottomPaint = new TextPaint();
        Typeface typeface = getResources().getFont(R.font.impact);

        topPaint.setColor(Color.WHITE);
        topPaint.setStyle(Paint.Style.FILL);
        topPaint.setShadowLayer(10f, 10f, 10f, Color.BLACK);
        topPaint.setTextSize(topTextView.getTextSize());
        topPaint.setTypeface(typeface);

        bottomPaint.setColor(Color.WHITE);
        bottomPaint.setStyle(Paint.Style.FILL);
        bottomPaint.setShadowLayer(10f, 10f, 10f, Color.BLACK);
        bottomPaint.setTextSize(bottomTextView.getTextSize());
        bottomPaint.setTypeface(typeface);

        float topTextMeasurement = topPaint.measureText(topText);
        float bottomTextMeasurement = bottomPaint.measureText(bottomText);

        StaticLayout topLayout = new StaticLayout(topText, topPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER, 1.0f,
                0.0f, false);
        StaticLayout bottomLayout = new StaticLayout(bottomText, bottomPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
                1.0f, 0.0f, false);

        canvas.translate(0,0);
        topLayout.draw(canvas);

        canvas.translate(0, canvas.getHeight() - 210);
        bottomLayout.draw(canvas);
        counter++;

        File file;
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);

        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
        file = new File(path + "/SimpliMeme/" + timeStamp + "-" + counter + ".jpg");
        file.getParentFile().mkdir();

        try {
            OutputStream stream = new FileOutputStream(file);
            mutableBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            stream.flush();
            stream.close();
            Toast.makeText(getContext(), "Top Text: " + String.valueOf(topTextMeasurement) + " and bottom text: " + String.valueOf(bottomTextMeasurement),
                    Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Uri contentUri = Uri.fromFile(file);
        mediaScanIntent.setData(contentUri);
        Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
            imageUri = Objects.requireNonNull(data).getData();
            imageView.setImageURI(imageUri);
            memeViewModel.setSharedId(imageUri.getLastPathSegment());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(listener, new IntentFilter("CUSTOM_ACTION"));
    }

    private BroadcastReceiver listener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String data = intent.getStringExtra("DATA");
            createBitmapAndSave(imageView);
        }
    };

    @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(listener);
    }
}

解决方案

这些是我对onCreateView方法所做的更改。原来,我没有将检索到的Uri保存到imageUri字段

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ...

        if(savedInstanceState != null){
            imageUri = savedInstanceState.getParcelable("imageUri");
            imageView.setImageURI(imageUri);
        }

        ...
    }

1 个答案:

答案 0 :(得分:1)

替换:

outState.putString(String.valueOf(imageUri), "imageUri");

具有:

outState.putParcelable("imageUri", imageUri);

并替换:

String raw = savedInstanceState.getString("imageUri");
Uri savedUri = Uri.parse(raw);

具有:

Uri savedUri = savedInstanceState.getParcelable("imageUri");

put...()上的Bundle方法使用键,后跟值。您有值,然后是键。而且,对于Uri,您不需要将其与String之间进行转换。