Q:

Cannot Access shared preference in asynctask started from broadcast reciever

I have an asynctask started from a broadcast receiver.
The 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();
        }
    }

Both the service and the broadcast receiver are inner classes of the class ChatScreen.
I have a shared preference initialised within the onCreate() of the ChatScreen.java like:
@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);

Now when I try to access this shared preference in doInBackground() of the asynctask  GetPeriodicChat(recieverid)(The one started from the broadcast receiver),I encounter NPE.
Here is the code of the asynctask:
public class GetPeriodicChat extends AsyncTask<String,String,String>{
    String r_id="";

    public GetPeriodicChat(String r_id) {
        // TODO Auto-generated constructor stub
        System.out.println("get periodic chat called");
        chatlisthashmapperiodically = new ArrayList<HashMap<String, String>>();
        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<NameValuePair>(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-->"+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 <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<String, String> map = new HashMap<String, String>();

                            // adding each child node to HashMap key => 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+"--->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

I encounter NPE on the line preftimestamp= ChatScreen.this.getSharedPreferences(Constants.ACCESS_TIMESTAMP, Context.MODE_PRIVATE); 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.

A:

Update your AsyncTask to this:
public class GetPeriodicChat extends AsyncTask<String,String,String>{
    String r_id="";

    public GetPeriodicChat(String r_id, Context context) {
        ...
        // ************ Instead of ChatScreen.this pass Context object in constuctor and use it here.
        preftimestamp= context.getSharedPreferences(Constants.ACCESS_TIMESTAMP, Context.MODE_PRIVATE); 
        ...
    } 
}//Asynctask 

Usage:
new ChatScreen().new GetPeriodicChat(recieverid, context).execute();

Pass Activity context to your AsyncTask as a parameter. You will not have access to your Activity context outside the activity until and unless you define a static Context variable in your activity which is not the best practise to do.

