Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: saving files to specific folder for later retrieval

I am working on a drawing part, and have written the following code to save the image to the designated camera folder. However, I would rather like to create a new folder using the app name and save the image to the folder. How could that be made?

I would also like to later on retrieve the image files from that specific folder too.

Thanks!

Current code:

     String fileName = "ABC";

      // create a ContentValues and configure new image's data
      ContentValues values = new ContentValues();
      values.put(Images.Media.TITLE, fileName);
      values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
      values.put(Images.Media.MIME_TYPE, "image/jpg");

      // get a Uri for the location to save the file
      Uri uri = getContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);

      try 
      {                                               
         OutputStream outStream = getContext().getContentResolver().openOutputStream(uri);

         bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);

         outStream.flush(); // empty the buffer
         outStream.close(); // close the stream
like image 313
pearmak Avatar asked Jan 16 '13 17:01

pearmak


People also ask

How can we saving and loading the files in Android?

Use Context. getFilesDir() . Your application can read and write files in that folder and they'll automatically get deleted if your application gets uninstalled. From that point forward, you can create, delete and read from files like any other Java application.


1 Answers

Try this it might help you.

public void saveImageToExternalStorage(Bitmap image) {
    String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/directoryName";
    try
    {
        File dir = new File(fullPath);
        if (!dir.exists()) {
        dir.mkdirs();
        }
        OutputStream fOut = null;
        File file = new File(fullPath, "image.png");
        if(file.exists())
            file.delete();
        file.createNewFile();
        fOut = new FileOutputStream(file);
        // 100 means no compression, the lower you go, the stronger the compression
        image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        fOut.flush();
        fOut.close();
    }
    catch (Exception e)
    {
        Log.e("saveToExternalStorage()", e.getMessage());
    }
}
like image 69
Ajay S Avatar answered Oct 05 '22 13:10

Ajay S