Advertisement
LucasSousa

TinyDB

Sep 8th, 2017
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.51 KB | None | 0 0
  1. package br.main;
  2.  
  3. /**
  4.  * Criado por Lucas Sousa em 28/10/2015.
  5.  */
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.util.ArrayList;
  10. import java.util.Arrays;
  11. import java.util.Map;
  12.  
  13. import android.content.Context;
  14. import android.content.SharedPreferences;
  15. import android.graphics.Bitmap;
  16. import android.graphics.Bitmap.CompressFormat;
  17. import android.graphics.BitmapFactory;
  18. import android.os.Environment;
  19. import android.preference.PreferenceManager;
  20. import android.text.TextUtils;
  21. import android.util.Log;
  22.  
  23.  
  24. public class TinyDB {
  25.  
  26.     private SharedPreferences preferences;
  27.     private String DEFAULT_APP_IMAGEDATA_DIRECTORY;
  28.     private String lastImagePath = "";
  29.  
  30.     public TinyDB(Context appContext) {
  31.         preferences = PreferenceManager.getDefaultSharedPreferences(appContext);
  32.     }
  33.  
  34.  
  35.     /**
  36.      * Decodes the Bitmap from 'path' and returns it
  37.      * @param path image path
  38.      * @return the Bitmap from 'path'
  39.      */
  40.     public Bitmap getImage(String path) {
  41.         Bitmap bitmapFromPath = null;
  42.         try {
  43.             bitmapFromPath = BitmapFactory.decodeFile(path);
  44.  
  45.         } catch (Exception e) {
  46.             // TODO: handle exception
  47.             e.printStackTrace();
  48.         }
  49.  
  50.         return bitmapFromPath;
  51.     }
  52.  
  53.  
  54.     /**
  55.      * Returns the String path of the last saved image
  56.      * @return string path of the last saved image
  57.      */
  58.     public String getSavedImagePath() {
  59.         return lastImagePath;
  60.     }
  61.  
  62.  
  63.     /**
  64.      * Saves 'theBitmap' into folder 'theFolder' with the name 'theImageName'
  65.      * @param theFolder the folder path dir you want to save it to e.g "DropBox/WorkImages"
  66.      * @param theImageName the name you want to assign to the image file e.g "MeAtLunch.png"
  67.      * @param theBitmap the image you want to save as a Bitmap
  68.      * @return true if image was saved, false otherwise
  69.      */
  70.     public boolean putImage(String theFolder, String theImageName, Bitmap theBitmap) {
  71.         if (theFolder == null || theImageName == null || theBitmap == null)
  72.             return false;
  73.  
  74.         this.DEFAULT_APP_IMAGEDATA_DIRECTORY = theFolder;
  75.         String mFullPath = setupFullPath(theImageName);
  76.  
  77.         if (!mFullPath.equals("")) {
  78.             lastImagePath = mFullPath;
  79.             return saveBitmap(mFullPath, theBitmap);
  80.         }
  81.  
  82.         return false;
  83.     }
  84.  
  85.  
  86.     /**
  87.      * Saves 'theBitmap' into 'fullPath'
  88.      * @param fullPath full path of the image file e.g. "Images/MeAtLunch.png"
  89.      * @param theBitmap the image you want to save as a Bitmap
  90.      * @return true if image was saved, false otherwise
  91.      */
  92.     public boolean putImageWithFullPath(String fullPath, Bitmap theBitmap) {
  93.         return !(fullPath == null || theBitmap == null) && saveBitmap(fullPath, theBitmap);
  94.     }
  95.  
  96.     /**
  97.      * Creates the path for the image with name 'imageName' in DEFAULT_APP.. directory
  98.      * @param imageName name of the image
  99.      * @return the full path of the image. If it failed to create directory, return empty string
  100.      */
  101.     private String setupFullPath(String imageName) {
  102.         File mFolder = new File(Environment.getExternalStorageDirectory(), DEFAULT_APP_IMAGEDATA_DIRECTORY);
  103.  
  104.         if (isExternalStorageReadable() && isExternalStorageWritable() && !mFolder.exists()) {
  105.             if (!mFolder.mkdirs()) {
  106.                 Log.e("ERROR", "Failed to setup folder");
  107.                 return "";
  108.             }
  109.         }
  110.  
  111.         return mFolder.getPath() + '/' + imageName;
  112.     }
  113.  
  114.     /**
  115.      * Saves the Bitmap as a PNG file at path 'fullPath'
  116.      * @param fullPath path of the image file
  117.      * @param bitmap the image as a Bitmap
  118.      * @return true if it successfully saved, false otherwise
  119.      */
  120.     private boolean saveBitmap(String fullPath, Bitmap bitmap) {
  121.         if (fullPath == null || bitmap == null)
  122.             return false;
  123.  
  124.         boolean fileCreated = false;
  125.         boolean bitmapCompressed = false;
  126.         boolean streamClosed = false;
  127.  
  128.         File imageFile = new File(fullPath);
  129.  
  130.         if (imageFile.exists())
  131.             if (!imageFile.delete())
  132.                 return false;
  133.  
  134.         try {
  135.             fileCreated = imageFile.createNewFile();
  136.  
  137.         } catch (IOException e) {
  138.             e.printStackTrace();
  139.         }
  140.  
  141.         FileOutputStream out = null;
  142.         try {
  143.             out = new FileOutputStream(imageFile);
  144.             bitmapCompressed = bitmap.compress(CompressFormat.PNG, 100, out);
  145.  
  146.         } catch (Exception e) {
  147.             e.printStackTrace();
  148.             bitmapCompressed = false;
  149.  
  150.         } finally {
  151.             if (out != null) {
  152.                 try {
  153.                     out.flush();
  154.                     out.close();
  155.                     streamClosed = true;
  156.  
  157.                 } catch (IOException e) {
  158.                     e.printStackTrace();
  159.                     streamClosed = false;
  160.                 }
  161.             }
  162.         }
  163.  
  164.         return (fileCreated && bitmapCompressed && streamClosed);
  165.     }
  166.  
  167.     // Getters
  168.  
  169.     /**
  170.      * Get int value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
  171.      * @param key SharedPreferences key
  172.      * @param defaultValue int value returned if key was not found
  173.      * @return int value at 'key' or 'defaultValue' if key not found
  174.      */
  175.     public int getInt(String key, int defaultValue) {
  176.         return preferences.getInt(key, defaultValue);
  177.     }
  178.  
  179.     /**
  180.      * Get parsed ArrayList of Integers from SharedPreferences at 'key'
  181.      * @param key SharedPreferences key
  182.      * @return ArrayList of Integers
  183.      */
  184.     public ArrayList<Integer> getListInt(String key) {
  185.         String[] myList = TextUtils.split(preferences.getString(key, ""), "‚?‚");
  186.         ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList));
  187.         ArrayList<Integer> newList = new ArrayList<Integer>();
  188.  
  189.         for (String item : arrayToList)
  190.             newList.add(Integer.parseInt(item));
  191.  
  192.         return newList;
  193.     }
  194.  
  195.     /**
  196.      * Get long value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
  197.      * @param key SharedPreferences key
  198.      * @param defaultValue long value returned if key was not found
  199.      * @return long value at 'key' or 'defaultValue' if key not found
  200.      */
  201.     public long getLong(String key, long defaultValue) {
  202.         return preferences.getLong(key, defaultValue);
  203.     }
  204.  
  205.     /**
  206.      * Get float value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
  207.      * @param key SharedPreferences key
  208.      * @param defaultValue float value returned if key was not found
  209.      * @return float value at 'key' or 'defaultValue' if key not found
  210.      */
  211.     public float getFloat(String key, float defaultValue) {
  212.         return preferences.getFloat(key, defaultValue);
  213.     }
  214.  
  215.     /**
  216.      * Get double value from SharedPreferences at 'key'. If exception thrown, return 'defaultValue'
  217.      * @param key SharedPreferences key
  218.      * @param defaultValue double value returned if exception is thrown
  219.      * @return double value at 'key' or 'defaultValue' if exception is thrown
  220.      */
  221.     public double getDouble(String key, double defaultValue) {
  222.         String number = getString(key);
  223.  
  224.         try {
  225.             return Double.parseDouble(number);
  226.  
  227.         } catch (NumberFormatException e) {
  228.             return defaultValue;
  229.         }
  230.     }
  231.  
  232.     /**
  233.      * Get parsed ArrayList of Double from SharedPreferences at 'key'
  234.      * @param key SharedPreferences key
  235.      * @return ArrayList of Double
  236.      */
  237.     public ArrayList<Double> getListDouble(String key) {
  238.         String[] myList = TextUtils.split(preferences.getString(key, ""), "‚‗‚");
  239.         ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList));
  240.         ArrayList<Double> newList = new ArrayList<Double>();
  241.  
  242.         for (String item : arrayToList)
  243.             newList.add(Double.parseDouble(item));
  244.  
  245.         return newList;
  246.     }
  247.  
  248.     /**
  249.      * Get String value from SharedPreferences at 'key'. If key not found, return ""
  250.      * @param key SharedPreferences key
  251.      * @return String value at 'key' or "" (empty String) if key not found
  252.      */
  253.     public String getString(String key) {
  254.         return preferences.getString(key, "");
  255.     }
  256.  
  257.     /**
  258.      * Get parsed ArrayList of String from SharedPreferences at 'key'
  259.      * @param key SharedPreferences key
  260.      * @return ArrayList of String
  261.      */
  262.     public ArrayList<String> getListString(String key) {
  263.         return new ArrayList<String>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚?‚")));
  264.     }
  265.  
  266.     /**
  267.      * Get boolean value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
  268.      * @param key SharedPreferences key
  269.      * @param defaultValue boolean value returned if key was not found
  270.      * @return boolean value at 'key' or 'defaultValue' if key not found
  271.      */
  272.     public boolean getBoolean(String key, boolean defaultValue) {
  273.         return preferences.getBoolean(key, defaultValue);
  274.     }
  275.  
  276.     /**
  277.      * Get parsed ArrayList of Boolean from SharedPreferences at 'key'
  278.      * @param key SharedPreferences key
  279.      * @return ArrayList of Boolean
  280.      */
  281.     public ArrayList<Boolean> getListBoolean(String key) {
  282.         ArrayList<String> myList = getListString(key);
  283.         ArrayList<Boolean> newList = new ArrayList<Boolean>();
  284.  
  285.         for (String item : myList) {
  286.             if (item.equals("true")) {
  287.                 newList.add(true);
  288.             } else {
  289.                 newList.add(false);
  290.             }
  291.         }
  292.  
  293.         return newList;
  294.     }
  295.  
  296.     // Put methods
  297.  
  298.     /**
  299.      * Put int value into SharedPreferences with 'key' and save
  300.      * @param key SharedPreferences key
  301.      * @param value int value to be added
  302.      */
  303.     public void putInt(String key, int value) {
  304.         preferences.edit().putInt(key, value).apply();
  305.     }
  306.  
  307.     /**
  308.      * Put ArrayList of Integer into SharedPreferences with 'key' and save
  309.      * @param key SharedPreferences key
  310.      * @param intList ArrayList of Integer to be added
  311.      */
  312.     public void putListInt(String key, ArrayList<Integer> intList) {
  313.         Integer[] myIntList = intList.toArray(new Integer[intList.size()]);
  314.         preferences.edit().putString(key, TextUtils.join("‚?‚", myIntList)).apply();
  315.     }
  316.  
  317.     /**
  318.      * Put long value into SharedPreferences with 'key' and save
  319.      * @param key SharedPreferences key
  320.      * @param value long value to be added
  321.      */
  322.     public void putLong(String key, long value) {
  323.         preferences.edit().putLong(key, value).apply();
  324.     }
  325.  
  326.     /**
  327.      * Put float value into SharedPreferences with 'key' and save
  328.      * @param key SharedPreferences key
  329.      * @param value float value to be added
  330.      */
  331.     public void putFloat(String key, float value) {
  332.         preferences.edit().putFloat(key, value).apply();
  333.     }
  334.  
  335.     /**
  336.      * Put double value into SharedPreferences with 'key' and save
  337.      * @param key SharedPreferences key
  338.      * @param value double value to be added
  339.      */
  340.     public void putDouble(String key, double value) {
  341.         putString(key, String.valueOf(value));
  342.     }
  343.  
  344.     /**
  345.      * Put ArrayList of Double into SharedPreferences with 'key' and save
  346.      * @param key SharedPreferences key
  347.      * @param doubleList ArrayList of Double to be added
  348.      */
  349.     public void putListDouble(String key, ArrayList<Double> doubleList) {
  350.         Double[] myDoubleList = doubleList.toArray(new Double[doubleList.size()]);
  351.         preferences.edit().putString(key, TextUtils.join("‚‗‚", myDoubleList)).apply();
  352.     }
  353.  
  354.     /**
  355.      * Put String value into SharedPreferences with 'key' and save
  356.      * @param key SharedPreferences key
  357.      * @param value String value to be added
  358.      */
  359.     public void putString(String key, String value) {
  360.         preferences.edit().putString(key, value).apply();
  361.     }
  362.  
  363.     /**
  364.      * Put ArrayList of String into SharedPreferences with 'key' and save
  365.      * @param key SharedPreferences key
  366.      * @param stringList ArrayList of String to be added
  367.      */
  368.     public void putListString(String key, ArrayList<String> stringList) {
  369.         String[] myStringList = stringList.toArray(new String[stringList.size()]);
  370.         preferences.edit().putString(key, TextUtils.join("‚?‚", myStringList)).apply();
  371.     }
  372.  
  373.     /**
  374.      * Put boolean value into SharedPreferences with 'key' and save
  375.      * @param key SharedPreferences key
  376.      * @param value boolean value to be added
  377.      */
  378.     public void putBoolean(String key, boolean value) {
  379.         preferences.edit().putBoolean(key, value).apply();
  380.     }
  381.  
  382.     /**
  383.      * Put ArrayList of Boolean into SharedPreferences with 'key' and save
  384.      * @param key SharedPreferences key
  385.      * @param boolList ArrayList of Boolean to be added
  386.      */
  387.     public void putListBoolean(String key, ArrayList<Boolean> boolList) {
  388.         ArrayList<String> newList = new ArrayList<String>();
  389.  
  390.         for (Boolean item : boolList) {
  391.             if (item) {
  392.                 newList.add("true");
  393.             } else {
  394.                 newList.add("false");
  395.             }
  396.         }
  397.  
  398.         putListString(key, newList);
  399.     }
  400.  
  401.  
  402.     /**
  403.      * Remove SharedPreferences item with 'key'
  404.      * @param key SharedPreferences key
  405.      */
  406.     public void remove(String key) {
  407.         preferences.edit().remove(key).apply();
  408.     }
  409.  
  410.     /**
  411.      * Delete image file at 'path'
  412.      * @param path path of image file
  413.      * @return true if it successfully deleted, false otherwise
  414.      */
  415.     public boolean deleteImage(String path) {
  416.         return new File(path).delete();
  417.     }
  418.  
  419.  
  420.     /**
  421.      * Clear SharedPreferences (remove everything)
  422.      */
  423.     public void clear() {
  424.         preferences.edit().clear().apply();
  425.     }
  426.  
  427.     /**
  428.      * Retrieve all values from SharedPreferences. Do not modify collection return by method
  429.      * @return a Map representing a list of key/value pairs from SharedPreferences
  430.      */
  431.     public Map<String, ?> getAll() {
  432.         return preferences.getAll();
  433.     }
  434.  
  435.  
  436.     /**
  437.      * Register SharedPreferences change listener
  438.      * @param listener listener object of OnSharedPreferenceChangeListener
  439.      */
  440.     public void registerOnSharedPreferenceChangeListener(
  441.             SharedPreferences.OnSharedPreferenceChangeListener listener) {
  442.  
  443.         preferences.registerOnSharedPreferenceChangeListener(listener);
  444.     }
  445.  
  446.     /**
  447.      * Unregister SharedPreferences change listener
  448.      * @param listener listener object of OnSharedPreferenceChangeListener to be unregistered
  449.      */
  450.     public void unregisterOnSharedPreferenceChangeListener(
  451.             SharedPreferences.OnSharedPreferenceChangeListener listener) {
  452.  
  453.         preferences.unregisterOnSharedPreferenceChangeListener(listener);
  454.     }
  455.  
  456.  
  457.     /**
  458.      * Check if external storage is writable or not
  459.      * @return true if writable, false otherwise
  460.      */
  461.     public static boolean isExternalStorageWritable() {
  462.         return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
  463.     }
  464.  
  465.     /**
  466.      * Check if external storage is readable or not
  467.      * @return true if readable, false otherwise
  468.      */
  469.     public static boolean isExternalStorageReadable() {
  470.         String state = Environment.getExternalStorageState();
  471.  
  472.         return Environment.MEDIA_MOUNTED.equals(state) ||
  473.                 Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
  474.     }
  475. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement