title: Unable to access shared preference inside Service - Android
body: <p>Hi I am using the <code>GCMListener</code> service to listen to incoming messages. I am trying to access my shared preference in the service, with the help of <a href="https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo" rel="nofollow">TinyDB</a>. </p>
  
  <p>I get the following error when trying to access the shared preference.</p>
  
  <pre><code>java.lang.RuntimeException: Unable to instantiate service com.artqueen.aahaan.GCM.MyGcmListenerService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
              at android.app.ActivityThread.handleCreateService(ActivityThread.java:3271)
              at android.app.ActivityThread.access$1900(ActivityThread.java:182)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1558)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:145)
              at android.app.ActivityThread.main(ActivityThread.java:6141)
              at java.lang.reflect.Method.invoke(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:372)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
              at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:184)
              at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
              at com.artqueen.aahaan.Helper.TinyDB.&lt;init&gt;(TinyDB.java:31)
              at com.artqueen.aahaan.GCM.MyGcmListenerService.&lt;init&gt;(MyGcmListenerService.java:40)
              at java.lang.reflect.Constructor.newInstance(Native Method)
              at java.lang.Class.newInstance(Class.java:1650)
              at android.app.ActivityThread.handleCreateService(ActivityThread.java:3268)
              at android.app.ActivityThread.access$1900(ActivityThread.java:182)
              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1558)
              at android.os.Handler.dispatchMessage(Handler.java:102)
              at android.os.Looper.loop(Looper.java:145)
              at android.app.ActivityThread.main(ActivityThread.java:6141)
              at java.lang.reflect.Method.invoke(Native Method)
              at java.lang.reflect.Method.invoke(Method.java:372)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
  </code></pre>
  
  <p>I am using the <strong>GCMListenerService</strong> like this</p>
  
  <pre><code>public class MyGcmListenerService extends GcmListenerService {
  
      private static final String TAG = "MyGcmListenerService";
  
      TinyDB tinyDB = new TinyDB(MyGcmListenerService.this);
  
      @Override
      public void onMessageReceived(String from, Bundle data) {
          String message = data.getString("message");
  
          String user = data.getString("user","");
          Log.e("user = "," "+user);
  
          ArrayList&lt;String&gt; blockList = tinyDB.getListString("blockList");
  
  
         if(blockList.contains(user)){
             //dont show notification
         }else {
             //show notification
             sendNotification(user);
         }
      }
  </code></pre>
  
  <p>And for your reference, the <strong>TinyDB</strong> class looks like this</p>
  
  <pre><code>public class TinyDB {
  
      private SharedPreferences preferences;
      private String DEFAULT_APP_IMAGEDATA_DIRECTORY;
      private String lastImagePath = "";
  
      public TinyDB(Context appContext) {
          preferences = PreferenceManager.getDefaultSharedPreferences(appContext);
      }
  
  
      /**
       * Decodes the Bitmap from 'path' and returns it
       * @param path image path
       * @return the Bitmap from 'path'
       */
      public Bitmap getImage(String path) {
          Bitmap bitmapFromPath = null;
          try {
              bitmapFromPath = BitmapFactory.decodeFile(path);
  
          } catch (Exception e) {
              // TODO: handle exception
              e.printStackTrace();
          }
  
          return bitmapFromPath;
      }
  
  
      /**
       * Returns the String path of the last saved image
       * @return string path of the last saved image
       */
      public String getSavedImagePath() {
          return lastImagePath;
      }
  
  
      /**
       * Saves 'theBitmap' into folder 'theFolder' with the name 'theImageName'
       * @param theFolder the folder path dir you want to save it to e.g "DropBox/WorkImages"
       * @param theImageName the name you want to assign to the image file e.g "MeAtLunch.png"
       * @param theBitmap the image you want to save as a Bitmap
       * @return true if image was saved, false otherwise
       */
      public boolean putImage(String theFolder, String theImageName, Bitmap theBitmap) {
          if (theFolder == null || theImageName == null || theBitmap == null)
              return false;
  
          this.DEFAULT_APP_IMAGEDATA_DIRECTORY = theFolder;
          String mFullPath = setupFullPath(theImageName);
  
          if (!mFullPath.equals("")) {
              lastImagePath = mFullPath;
              return saveBitmap(mFullPath, theBitmap);
          }
  
          return false;
      }
  
  
      /**
       * Saves 'theBitmap' into 'fullPath'
       * @param fullPath full path of the image file e.g. "Images/MeAtLunch.png"
       * @param theBitmap the image you want to save as a Bitmap
       * @return true if image was saved, false otherwise
       */
      public boolean putImageWithFullPath(String fullPath, Bitmap theBitmap) {
          return !(fullPath == null || theBitmap == null) &amp;&amp; saveBitmap(fullPath, theBitmap);
      }
  
      /**
       * Creates the path for the image with name 'imageName' in DEFAULT_APP.. directory
       * @param imageName name of the image
       * @return the full path of the image. If it failed to create directory, return empty string
       */
      private String setupFullPath(String imageName) {
          File mFolder = new File(Environment.getExternalStorageDirectory(), DEFAULT_APP_IMAGEDATA_DIRECTORY);
  
          if (isExternalStorageReadable() &amp;&amp; isExternalStorageWritable() &amp;&amp; !mFolder.exists()) {
              if (!mFolder.mkdirs()) {
                  Log.e("ERROR", "Failed to setup folder");
                  return "";
              }
          }
  
          return mFolder.getPath() + '/' + imageName;
      }
  
      /**
       * Saves the Bitmap as a PNG file at path 'fullPath'
       * @param fullPath path of the image file
       * @param bitmap the image as a Bitmap
       * @return true if it successfully saved, false otherwise
       */
      private boolean saveBitmap(String fullPath, Bitmap bitmap) {
          if (fullPath == null || bitmap == null)
              return false;
  
          boolean fileCreated = false;
          boolean bitmapCompressed = false;
          boolean streamClosed = false;
  
          File imageFile = new File(fullPath);
  
          if (imageFile.exists())
              if (!imageFile.delete())
                  return false;
  
          try {
              fileCreated = imageFile.createNewFile();
  
          } catch (IOException e) {
              e.printStackTrace();
          }
  
          FileOutputStream out = null;
          try {
              out = new FileOutputStream(imageFile);
              bitmapCompressed = bitmap.compress(CompressFormat.PNG, 100, out);
  
          } catch (Exception e) {
              e.printStackTrace();
              bitmapCompressed = false;
  
          } finally {
              if (out != null) {
                  try {
                      out.flush();
                      out.close();
                      streamClosed = true;
  
                  } catch (IOException e) {
                      e.printStackTrace();
                      streamClosed = false;
                  }
              }
          }
  
          return (fileCreated &amp;&amp; bitmapCompressed &amp;&amp; streamClosed);
      }
  
      // Getters
  
      /**
       * Get int value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
       * @param key SharedPreferences key
       * @param defaultValue int value returned if key was not found
       * @return int value at 'key' or 'defaultValue' if key not found
       */
      public int getInt(String key, int defaultValue) {
          return preferences.getInt(key, defaultValue);
      }
  
      /**
       * Get parsed ArrayList of Integers from SharedPreferences at 'key'
       * @param key SharedPreferences key
       * @return ArrayList of Integers
       */
      public ArrayList&lt;Integer&gt; getListInt(String key) {
          String[] myList = TextUtils.split(preferences.getString(key, ""), "‚‗‚");
          ArrayList&lt;String&gt; arrayToList = new ArrayList&lt;String&gt;(Arrays.asList(myList));
          ArrayList&lt;Integer&gt; newList = new ArrayList&lt;Integer&gt;();
  
          for (String item : arrayToList)
              newList.add(Integer.parseInt(item));
  
          return newList;
      }
  
      /**
       * Get long value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
       * @param key SharedPreferences key
       * @param defaultValue long value returned if key was not found
       * @return long value at 'key' or 'defaultValue' if key not found
       */
      public long getLong(String key, long defaultValue) {
          return preferences.getLong(key, defaultValue);
      }
  
      /**
       * Get float value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
       * @param key SharedPreferences key
       * @param defaultValue float value returned if key was not found
       * @return float value at 'key' or 'defaultValue' if key not found
       */
      public float getFloat(String key, float defaultValue) {
          return preferences.getFloat(key, defaultValue);
      }
  
      /**
       * Get double value from SharedPreferences at 'key'. If exception thrown, return 'defaultValue'
       * @param key SharedPreferences key
       * @param defaultValue double value returned if exception is thrown
       * @return double value at 'key' or 'defaultValue' if exception is thrown
       */
      public double getDouble(String key, double defaultValue) {
          String number = getString(key);
  
          try {
              return Double.parseDouble(number);
  
          } catch (NumberFormatException e) {
              return defaultValue;
          }
      }
  
      /**
       * Get parsed ArrayList of Double from SharedPreferences at 'key'
       * @param key SharedPreferences key
       * @return ArrayList of Double
       */
      public ArrayList&lt;Double&gt; getListDouble(String key) {
          String[] myList = TextUtils.split(preferences.getString(key, ""), "â€šâ€—â€š");
          ArrayList&lt;String&gt; arrayToList = new ArrayList&lt;String&gt;(Arrays.asList(myList));
          ArrayList&lt;Double&gt; newList = new ArrayList&lt;Double&gt;();
  
          for (String item : arrayToList)
              newList.add(Double.parseDouble(item));
  
          return newList;
      }
  
      /**
       * Get String value from SharedPreferences at 'key'. If key not found, return ""
       * @param key SharedPreferences key
       * @return String value at 'key' or "" (empty String) if key not found
       */
      public String getString(String key) {
          return preferences.getString(key, "");
      }
  
      /**
       * Get parsed ArrayList of String from SharedPreferences at 'key'
       * @param key SharedPreferences key
       * @return ArrayList of String
       */
      public ArrayList&lt;String&gt; getListString(String key) {
          return new ArrayList&lt;String&gt;(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
      }
  
      /**
       * Get boolean value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
       * @param key SharedPreferences key
       * @param defaultValue boolean value returned if key was not found
       * @return boolean value at 'key' or 'defaultValue' if key not found
       */
      public boolean getBoolean(String key, boolean defaultValue) {
          return preferences.getBoolean(key, defaultValue);
      }
  
      /**
       * Get parsed ArrayList of Boolean from SharedPreferences at 'key'
       * @param key SharedPreferences key
       * @return ArrayList of Boolean
       */
      public ArrayList&lt;Boolean&gt; getListBoolean(String key) {
          ArrayList&lt;String&gt; myList = getListString(key);
          ArrayList&lt;Boolean&gt; newList = new ArrayList&lt;Boolean&gt;();
  
          for (String item : myList) {
              if (item.equals("true")) {
                  newList.add(true);
              } else {
                  newList.add(false);
              }
          }
  
          return newList;
      }
  
      // Put methods
  
      /**
       * Put int value into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param value int value to be added
       */
      public void putInt(String key, int value) {
          preferences.edit().putInt(key, value).apply();
      }
  
      /**
       * Put ArrayList of Integer into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param intList ArrayList of Integer to be added
       */
      public void putListInt(String key, ArrayList&lt;Integer&gt; intList) {
          Integer[] myIntList = intList.toArray(new Integer[intList.size()]);
          preferences.edit().putString(key, TextUtils.join("‚‗‚", myIntList)).apply();
      }
  
      /**
       * Put long value into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param value long value to be added
       */
      public void putLong(String key, long value) {
          preferences.edit().putLong(key, value).apply();
      }
  
      /**
       * Put float value into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param value float value to be added
       */
      public void putFloat(String key, float value) {
          preferences.edit().putFloat(key, value).apply();
      }
  
      /**
       * Put double value into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param value double value to be added
       */
      public void putDouble(String key, double value) {
          putString(key, String.valueOf(value));
      }
  
      /**
       * Put ArrayList of Double into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param doubleList ArrayList of Double to be added
       */
      public void putListDouble(String key, ArrayList&lt;Double&gt; doubleList) {
          Double[] myDoubleList = doubleList.toArray(new Double[doubleList.size()]);
          preferences.edit().putString(key, TextUtils.join("â€šâ€—â€š", myDoubleList)).apply();
      }
  
      /**
       * Put String value into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param value String value to be added
       */
      public void putString(String key, String value) {
          preferences.edit().putString(key, value).apply();
      }
  
      /**
       * Put ArrayList of String into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param stringList ArrayList of String to be added
       */
      public void putListString(String key, ArrayList&lt;String&gt; stringList) {
          String[] myStringList = stringList.toArray(new String[stringList.size()]);
          preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply();
      }
  
      /**
       * Put boolean value into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param value boolean value to be added
       */
      public void putBoolean(String key, boolean value) {
          preferences.edit().putBoolean(key, value).apply();
      }
  
      /**
       * Put ArrayList of Boolean into SharedPreferences with 'key' and save
       * @param key SharedPreferences key
       * @param boolList ArrayList of Boolean to be added
       */
      public void putListBoolean(String key, ArrayList&lt;Boolean&gt; boolList) {
          ArrayList&lt;String&gt; newList = new ArrayList&lt;String&gt;();
  
          for (Boolean item : boolList) {
              if (item) {
                  newList.add("true");
              } else {
                  newList.add("false");
              }
          }
  
          putListString(key, newList);
      }
  
  
      /**
       * Remove SharedPreferences item with 'key'
       * @param key SharedPreferences key
       */
      public void remove(String key) {
          preferences.edit().remove(key).apply();
      }
  
      /**
       * Delete image file at 'path'
       * @param path path of image file
       * @return true if it successfully deleted, false otherwise
       */
      public boolean deleteImage(String path) {
          return new File(path).delete();
      }
  
  
      /**
       * Clear SharedPreferences (remove everything)
       */
      public void clear() {
          preferences.edit().clear().apply();
      }
  
      /**
       * Retrieve all values from SharedPreferences. Do not modify collection return by method
       * @return a Map representing a list of key/value pairs from SharedPreferences
       */
      public Map&lt;String, ?&gt; getAll() {
          return preferences.getAll();
      }
  
  
      /**
       * Register SharedPreferences change listener
       * @param listener listener object of OnSharedPreferenceChangeListener
       */
      public void registerOnSharedPreferenceChangeListener(
              SharedPreferences.OnSharedPreferenceChangeListener listener) {
  
          preferences.registerOnSharedPreferenceChangeListener(listener);
      }
  
      /**
       * Unregister SharedPreferences change listener
       * @param listener listener object of OnSharedPreferenceChangeListener to be unregistered
       */
      public void unregisterOnSharedPreferenceChangeListener(
              SharedPreferences.OnSharedPreferenceChangeListener listener) {
  
          preferences.unregisterOnSharedPreferenceChangeListener(listener);
      }
  
  
      /**
       * Check if external storage is writable or not
       * @return true if writable, false otherwise
       */
      public static boolean isExternalStorageWritable() {
          return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
      }
  
      /**
       * Check if external storage is readable or not
       * @return true if readable, false otherwise
       */
      public static boolean isExternalStorageReadable() {
          String state = Environment.getExternalStorageState();
  
          return Environment.MEDIA_MOUNTED.equals(state) ||
                  Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
      }
  }
  </code></pre>
  
  <p>I am not able to figure out why I am not able to access my shared preference inside the service. Please help me out. Thanks in advance.</p>