Save image to internal storage

2020-02-15 java android

I want to save some images in internal storage. Here is my code:

Bitmap bitmap = ((BitmapDrawable)iv_add.getDrawable()).getBitmap();
            File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
            file = new File(file, "UniqueFileName"+".jpg");
            try{
                OutputStream stream = null;
                stream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
                stream.flush();
                stream.close();
            }catch (IOException e)
            {
                e.printStackTrace();
            }

As I understood, the picture needs to go into internal_storage/android/data/project_name/file. When I choose a picture from my gallery and click the button to save it, nothing happens and the program starts lagging. What can I do?

Answers

This line is your problem.

ContextWrapper wrapper = new ContextWrapper(getApplicationContext());

You are not supposed to create the context wrapper yourself.

        File file = getApplicationContext().getDir("Images",MODE_PRIVATE);
        file = new File(file, "UniqueFileName"+".jpg");
        try{
            OutputStream stream = null;
            stream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
            stream.flush();
            stream.close();
        }catch (IOException e)
        {
            e.printStackTrace();
        }

Related