Orynuh
Orynuh

Reputation: 105

Pass context to Async class

I'm calling an Async class from my main activity class. When the POST has been executed I want to return the result back to the main activity.

public class MainActivity extends Activity implements OnClickListener, AsyncResponse{
    public Context context;
    PostKey asyncTask = new PostKey(context);

    public void onCreate(Bundle savedInstanceState) {
        asyncTask.delegate = this;
    }

    public void onClick(View v) {
        asyncTask.delegate = this;
        new PostKey(context).execute(keyValue);
    }

    public void processFinish(String output){
        //this you will received result fired from async class of    onPostExecute(result) method.
        Log.d("Result", output);
    }
}


public class PostKey extends AsyncTask<String, String, String> {
    public AsyncResponse delegate = null;
    public Context context;

    public PostKey(Context context){
        this.context = context.getApplicationContext();
    }

    @Override
    protected String doInBackground(String... params) {
        return postData(params[0]);
    }

    @Override
    protected void onPostExecute(String result){
        this.context = context.getApplicationContext();
        delegate = (AsyncResponse) context;
    }

    delegate.processFinish(result);
}

public interface AsyncResponse {
    void processFinish(String output);
}

Whenever I try to run the app I immediately get a fatal error caused by a nullpointer exception. The nullpointer refers to the following:

public PostKey(Context context){
    this.context = context.getApplicationContext();
}

& PostKey asyncTask = new PostKey(context);

In the second case I can get that context is empty, but I have to pass the variable here.

Upvotes: 0

Views: 513

Answers (3)

karimkhan
karimkhan

Reputation: 329

try to use this.context = getApplicationContext(); instead

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157457

Activity is already a Context, so you don't to keep a reference to it. Just use this. On the other hand the Activity has to go through its lifecycle before you can use the context. Remove

public Context context;
PostKey asyncTask = new PostKey(context);

and add

PostKey asyncTask = new PostKey(this);

in your onCreate. And please, add super.onCreate(savedInstanceState); as first thing in your onCreate

Upvotes: 2

luckwithu
luckwithu

Reputation: 143

Hello Oryna you passing null context value as in parameter just replace these lines with this

 new PostKey(context).execute(keyValue);

to

 new PostKey(MainActivity.this).execute(keyValue);

and the constructor for the async task replace the code

    public PostKey(Context context){
    this.context = context.getApplicationContext();
}

with

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

Upvotes: 0

Related Questions