-1

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;
} 
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
saeed
  • 21
  • 4

3 Answers3

1

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.

Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

Your first problem that I see is that there is no existence of the method getContentResolver() so in turn it would make the object reference null because there is no such method maybe. If there is a getContentResolver method then you should include that in your example :)

beastlyCoder
  • 2,349
  • 4
  • 25
  • 52
0

Are you trying to set or get the Context? I would have a separate method for getting and another for setting.

public void setContext(Context context) {
    Objects.requireNotNull(context);
    this.mContext = context;
    mContext.getContentResolver();// Not sure if this should do anything?
}

public Context getContext() {
    return mContext;
} 
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130