Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context inside AsyncTask

I'm currently attempting to put my authorisation code for an app into an external class, so I'm not repeating myself whenever it is required and to tidy up the code.

The problem that I am having is that I can't seem to access my Session variables from inside the AsyncTask. I would love to try and figure it out myself to better understand the situation, but another problem is that there is no error in LogCat, so I have no idea what's going wrong! My authorise class is below:

public class AuthoriseMe extends AsyncTask<Object, Void, String> {

    public Context context;

    protected String doInBackground(Object... params) {

    Log.i(TAG, "I GOT HERE");
    SessionManager session = new SessionManager(context);
    Log.i(TAG, "I GOT PAST HERE");

        String authorized = "";
        HashMap<String, String> app = session.getAPPDetails();
        String appid = app.get(SessionManager.KEY_APPID);
        String secret = app.get(SessionManager.KEY_SECRET);
    }
}

The code I'm using to start the AsyncTask is below, where another class is calling authoriseMe();

public void authoriseMe() {
    AuthoriseMe authorise = new AuthoriseMe();
    authorise.execute();
}

authoriseMe() is being called as I have logged the process, but it looks like the line "SessionManager session = new SessionManager(context);" is where the problem is happening, as if I take that line out I get 'I GOT PAST HERE' in my logical.

My constructor for the SessionManager looks like this:

// Constructor
public SessionManager(Context context){
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

From what I can see it looks like an issue with context within the asyncTask. Is there any way around this? Has anyone any previous experience of this?

like image 777
Steve Vincent Avatar asked Apr 30 '26 22:04

Steve Vincent


1 Answers

I do not see you initialize your context memeber. Just add proper constructor:

public AuthoriseMe(Context context) {
    this.context = context;
}

and then instead of

AuthoriseMe authorise = new AuthoriseMe();

do

AuthoriseMe authorise = new AuthoriseMe(context);

and you are done. Alternatively you can just obtain the context by calling getApplication() or getApplicationContext() (be sure to read this question), which should be sufficient for most cases.

like image 72
Marcin Orlowski Avatar answered May 02 '26 13:05

Marcin Orlowski