SpecialSnowflake SpecialSnowflake - 3 months ago 45
Android Question

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()'

I have a class dedicated to managing sharedpreferences, however I keep getting a NPE on one of my calls. Heres the class,

public class UserManager extends Activity{

Context mContext;

UserManager(Context mContext){
this.mContext = mContext;
}


public boolean getFromMatches(String userUid, String matchUid){
SharedPreferences spMatches = mContext.getSharedPreferences(getString(R.string.match_key), Context.MODE_PRIVATE);
if(spMatches.contains(userUid + matchUid)){
return true;
}else{
return false;
}
}


}

This is what is passed from my main activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);

userManager = new UserManager(getApplicationContext());
}


The NPE is received at this line:

SharedPreferences spMatches = mContext.getSharedPreferences(getString(R.string.match_key), Context.MODE_PRIVATE);

Answer

replace the getFromMatches function with this

public boolean getFromMatches(String userUid, String matchUid){
     SharedPreferences spMatches =  mContext.getSharedPreferences(mContext.getString(R.string.match_key), Context.MODE_PRIVATE);
     if(spMatches.contains(userUid + matchUid)){
        return true;
     }else{
       return false;
     }
}

for calling getString or any resources you will need Context

Comments