title: Cannot Access shared preference in asynctask started from broadcast reciever
body: <p>I have an asynctask started from a broadcast receiver.</p>
  
  <p>The code:</p>
  
  <pre><code>public static class SrvPositioning extends Service {
  
          // An alarm for rising in special times to fire the
          // pendingIntentPositioning
          private AlarmManager alarmManagerPositioning;
          // A PendingIntent for calling a receiver in special times
          public PendingIntent pendingIntentPositioning;
  
          Location location;
          //GPSTracker gps;
  
  
  
          @Override
          public void onCreate() {
              super.onCreate();
              alarmManagerPositioning = (AlarmManager) 
                      getSystemService(Context.ALARM_SERVICE);
              Intent intentToFire = new Intent(
                      ReceiverPositioningAlarm.ACTION_REFRESH_SCHEDULE_ALARM);
              intentToFire.putExtra(ReceiverPositioningAlarm.COMMAND,
                      ReceiverPositioningAlarm.SENDER_SRV_POSITIONING);
              pendingIntentPositioning = PendingIntent.getBroadcast(this, 0,
                      intentToFire, 0);
  
  
  
          };
  
          @Override
          public void onStart(Intent intent, int startId) {
              try {
                  long interval = 3000;//3 secs
                  System.out.println("Service called");
                  int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
                  long timetoRefresh = SystemClock.elapsedRealtime();
                  alarmManagerPositioning.setInexactRepeating(alarmType,
                          timetoRefresh, interval, pendingIntentPositioning);
  
                  //Toast.makeText(this, "SrvPositioning fired", Toast.LENGTH_SHORT).show();
  
              } catch (NumberFormatException e) {
                  Toast.makeText(this,
                          "error running service: " + e.getMessage(),
                          Toast.LENGTH_SHORT).show();
              } catch (Exception e) {
                  Toast.makeText(this,
                          "error running service: " + e.getMessage(),
                          Toast.LENGTH_SHORT).show();
              }
          }
  
  
  
          @Override
          public void onDestroy() {
              this.alarmManagerPositioning.cancel(pendingIntentPositioning);
              // ReceiverPositioningAlarm.stopLocationListener();
          }
  
          @Override
          public IBinder onBind(Intent intent) {
              // TODO Auto-generated method stub
              return null;
          }
  
  
      }
  
  
      public static class ReceiverPositioningAlarm extends BroadcastReceiver {
  
          public static final String COMMAND = "SENDER";
          public static final int SENDER_ACT_DOCUMENT = 0;
          public static final int SENDER_SRV_POSITIONING = 1;
  
          public static final String ACTION_REFRESH_SCHEDULE_ALARM =
                  "ACTION_REFRESH_SCHEDULE_ALARM";
          //private static final Context _context=null;
          String jsonStr="";
  
  
          @Override
          public void onReceive(final Context context, Intent intent) {
              //Toast.makeText(context, "new request received by receiver",
              //Toast.LENGTH_SHORT).show();
  
              // create class object
  
              //SessionManager s=new SessionManager(context);
              //userid=s.getUserId();
              System.out.println("RecieverPositioning Alarm");
              //_context = context;
  
  
              new ChatScreen().new GetPeriodicChat(recieverid).execute();
          }
      }
  </code></pre>
  
  <p>Both the service and the broadcast receiver are inner classes of the class ChatScreen.</p>
  
  <p>I have a shared preference initialised within the onCreate() of the ChatScreen.java like:</p>
  
  <pre><code>@Override
  protected void onCreate(Bundle savedInstanceState) {
      // TODO Auto-generated method stub
      super.onCreate(savedInstanceState);
      setContentView(R.layout.chatscreen2);
      preftimestamp= ChatScreen.this.getSharedPreferences(Constants.ACCESS_TIMESTAMP, Context.MODE_PRIVATE);
  </code></pre>
  
  <p>Now when I try to access this shared preference in doInBackground() of the asynctask  <strong>GetPeriodicChat(recieverid)</strong>(The one started from the broadcast receiver),I encounter NPE.</p>
  
  <p>Here is the code of the asynctask:</p>
  
  <pre><code>public class GetPeriodicChat extends AsyncTask&lt;String,String,String&gt;{
      String r_id="";
  
      public GetPeriodicChat(String r_id) {
          // TODO Auto-generated constructor stub
          System.out.println("get periodic chat called");
          chatlisthashmapperiodically = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();
          preftimestamp= ChatScreen.this.getSharedPreferences(Constants.ACCESS_TIMESTAMP, Context.MODE_PRIVATE);
          this.r_id=r_id;
      }
      protected void onPreExecute() {
          super.onPreExecute();
          try{
              //showLoading(R.string.loading);
          }catch(Exception e){
              e.printStackTrace();
          }
  
      }
      @Override
      protected String doInBackground(String... params) {
          // TODO Auto-generated method stub
  
          urlgetallchatmessage=Constants.getmessagetimestamp;
          nameValuePairs = new ArrayList&lt;NameValuePair&gt;(2);
          nameValuePairs.add(new BasicNameValuePair("sender_id",userid));
          nameValuePairs.add(new BasicNameValuePair("receiver_id",r_id));//rec
  
          String last_timestamp =preftimestamp.getString(Constants.ACCESS_TIMESTAMP,null);
          System.out.println("Last timestamp in periodically--&gt;"+last_timestamp);
          nameValuePairs.add(new BasicNameValuePair("last_timestamp",last_timestamp));
  
  
          ServiceHandle sh = new ServiceHandle();
          String jsonResponse  = sh.makeServiceCall(urlgetallchatmessage, ServiceHandle.POST,nameValuePairs);
  
          // after getting  JSON string from the URL
          System.out.println(""+ jsonResponse );
          try {
  
              if ( jsonResponse  != null) 
              {
                  JSONObject c = new JSONObject( jsonResponse );
  
                  //JSONObject c = jsonObj;
                  successallchat=Integer.parseInt(c.getString("success"));
                  if(successallchat==1)
                  {
  
                      if(c.has(TAG_GETHISTORY_ARRAY)){
                          chatlistperiodically = c.getJSONArray(TAG_GETHISTORY_ARRAY);
  
                          // looping through All Contacts
                          for (int i = 0; i &lt;chatlistperiodically.length(); i++) {
                              JSONObject j_chat = chatlistperiodically.getJSONObject(i);
                              String timestamp= j_chat.getString(TAG_TIMESTAMP);
                              String chatmessage= j_chat.getString(TAG_MESSAGE);
                              String sender_id= j_chat.getString(TAG_SENDER_ID);
  
                              // creating new HashMap
                              HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
  
                              // adding each child node to HashMap key =&gt; value
                              map.put(TAG_TIMESTAMP,timestamp);
                              map.put(TAG_MESSAGE,chatmessage);
                              map.put(TAG_SENDER_ID,sender_id);
                              SharedPreferences.Editor editor = preftimestamp.edit();
                              //  System.out.println(projectid+"---&gt;In Projectactivity");
                              editor.putString(Constants.ACCESS_TIMESTAMP,timestamp);
                              editor.commit();
  
  
                              //map.put(TAG_PDESC,pdetails);
                              chatlisthashmapperiodically.add(map);
                          }
                      }   
                  }
              }
              else
              {
                  runOnUiThread(new Runnable() {
  
                      @Override
                      public void run() {
                          // TODO Auto-generated method stub
                          Toast.makeText(getBaseContext(), "Server not responding!", Toast.LENGTH_SHORT).show();
                      }
                  });
  
              }
          } catch (Exception e) 
          {
              e.printStackTrace();
          }
  
  
          return null;
      }//doInbacckground
  
  
      @SuppressLint("NewApi")
      protected void onPostExecute(String file_url) { 
  
  
          //removeLoading();
  
          if(successallchat==1)
          {
  
  
          }
  
      }//postexecute
  
      }//Asynctask
  </code></pre>
  
  <p>I encounter NPE on the line <code>preftimestamp= ChatScreen.this.getSharedPreferences(Constants.ACCESS_TIMESTAMP, Context.MODE_PRIVATE);</code> within the constructor of the asynctask.What can be the problem??If I didnt define the asynctask on the constructor,then also I am encountering the NPE.Please help.</p>