saeed norouzi saeed norouzi -4 years ago 141
Android Question

My Context gives me a null reference pointer

I am trying to define a Context in my main Activity and use it in my AsyncTask, but it gives a null reference?

Here I test it in my main Activity and the same error occur in my AsyncTask:

public class MainActivity extends AppCompatActivity {


public Context mContext;

public Context getContext(Context context) {

this.mContext = context;
mContext.getContentResolver();// null object reference error
return mContext;
}

Answer Source

AppCompatActivity is a Context

You do not need that field. Just use MainActivity.this where you do need a Context within that class.


Second problem - If mContext.getContentResolver(); is throwing null pointer, then you just passed a null context into that method...

Essentially, why do you pass a parameter to a get method?

public Context getContext(Context context) { <-- null

    this.mContext = context; // <-- null
    mContext.getContentResolver();//  <-- Just used null... exception!
    return mContext; // <-- null, and this is parameter you just provided, anyway...

Alternatively,

How can getContentResolver() be called in Android?

Just directly call getContentResolver() directly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download