user1959076
user1959076

Reputation: 409

Context and GetSharedPreferences on Android

I am using Andengine on Android. I have two classes (Main and functions) which are shown below.

Main:

private Context myContext;
.
.
if (functions.Sonido(myContext)) {
   mSound.play();
}

Functions:

    public boolean Sonido(Context C) {
    prefs =  C.getSharedPreferences(Filename, Context.MODE_PRIVATE);
    valor = prefs.getString("Sound", null);

    if (valor == "YES") {
        return true;
    }else{
        return false;
    }
    }

The editor does not give any error but I get run-time errors. Please assist me to resolve them.

Upvotes: 0

Views: 408

Answers (2)

Simon Schubert
Simon Schubert

Reputation: 2028

Why so complicated?

public boolean Sonido(Context context) {
    prefs =  context.getSharedPreferences(Filename, Context.MODE_PRIVATE);
    return prefs.getBoolean("Sound", false);;
}

Because of your error log (The method Sonido(Context) in the type functions is not applicable for the arguments (new TiledSprite(){})) you have to call Sonido like this:

if (functions.Sonido(MainActivity.this)) {
   mSound.play();
}

If its not working show us your logcat in the ddms.

Another thing: Do not match Strings like this:

if (valor == "YES")

Better this like:

if (valor.equals("YES")) /*OR in your case*/ "YES".equals(valor)

Upvotes: 3

SalGad
SalGad

Reputation: 3011

You need to add a check if valor is not null as that is the default SharedPreferences value. Try modifying your function code to this:

public boolean Sonido(Context C) {
prefs =  C.getSharedPreferences(Filename, Context.MODE_PRIVATE);
valor = prefs.getString("Sound", null);

if (valor != null){
    if (valor.equals("YES")) {
        return true;
    }else{
        return false;
    }
} else {
return false;
}
}

Also check if the context is being sent correctly. Usually you can use this.getApplicationContext() to send the current context in if you're in an Activity/Fragment

Upvotes: 1

Related Questions