SaltySea SaltySea - 1 month ago 18x
Android Question

getApplicationContext on a null reference in AppCompatActivity using Picasso

I'm loading a picture from a url into a bitmap. This code below worked on previous classes that extended Fragment. This time, I'm just copying the code and trying to use it in a class that extends AppCompatActivity. The only difference is how I'm getting context.

public void loadBitmap(String url) {
if (loadtarget == null) loadtarget = new Target() {
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

public void onBitmapFailed(Drawable errorDrawable) {

public void onPrepareLoad(Drawable placeHolderDrawable) {
mContext = MyActivity.this;
Picasso.with(mContext).load(url).into(loadtarget); //giving me null

In the original code, where I used it in a Fragment, I had it as


So now, since this class extends AppCompatActivity, I thought I could use "this" or MyActivity.this but that didn't work. I've tried initializing a Context variable "mContext" in onCreate and right before I load the image into the bitmap (like above) but neither worked. I've tried this.getApplicationContext() and I've also tried to pass mContext as a parameter in the loadBitmap() method but that didn't work either.

My URL string is correct. I'm just not sure how to tackle this problem after trying, what seems like, everything.

Last piece of information, the exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(
at com.salty.seas.Driver.MyActivity.loadBitmap(
at com.salty.seas.Driver.MyActivity$1.onKeyEntered(
at com.firebase.geofire.GeoQuery$
at android.os.Handler.handleCallback(
at android.os.Handler.dispatchMessage(
at android.os.Looper.loop(
at java.lang.reflect.Method.invoke(Native Method)


In the comments to the question you said that the activity, the loadBitmap() belongs to, you actually instantiate yourself (in some other fragment) and use it as an utility class.

You should never create activites manually as they are managed by android and they have a lifecycle android maintains.

In your case the activity is not in a correct state (one of its internal fields is null), that's why you get NPE.

For utility methods create utility classes and call those from wherever you want.