Reputation: 1653
I move from Activity A to Activity B by intent.I am storing some values in shared preferences in Activity B.In activity A oncreate() i am fetching the values of the shared preferences to compare with some conditions however it gives me null pointer exception as expected (As i do not go to Activity B).However i want to write a condition to fetch the data from shared preferences if the value is not null.Can some one please say how can i achieve this? Following is my code:
In Activity B:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MerchantLogin.this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("showdialog_login", "dontshow");
editor.commit();
In Activity A:
@Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences prefs =null;
prefs = PreferenceManager.getDefaultSharedPreferences(LoginScreen.this);
SharedPreferences.Editor editor = prefs.edit();
if ((prefs.getString("showdialog_login", null).equalsIgnoreCase("dontshow")))
{
}
else if((prefs.getString("showdialog_login", null).equalsIgnoreCase("true")))
{
}
else if((prefs.getString("showdialog_login", null).equalsIgnoreCase("dummy")))
{
}
else
{
editor.putString("showdialog_login", "false");
editor.commit();
}
}
However i get error at this line:
if ((prefs.getString("showdialog_login", null).equalsIgnoreCase("dontshow"))).How can i execute this block of code.
Upvotes: 2
Views: 1794
Reputation: 22156
You should always use the constant as the first argument when comparing using equals
, i.e.
"dontshow".equalsIgnoreCase(prefs.getString("showdialog_login", null))
You are getting the NullPointerException
because the showdialog_login
property is not yet set, i.e.
prefs.getString("showdialog_login", null)
returns null
, because that's what you set the default value to.
Effectively, your condition is thus
null.equalsIgnoreCase("dontshow")
-which naturally ends up in a NullPointerException
.
Upvotes: 0
Reputation: 2049
In Activity A:
static SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState)
{
prefs = getSharedPreferences("showdialog_login",0);
String ss= prefs.getString("showdialog_login", "default");
if ((ss.equalsIgnoreCase("dontshow")))
{
}
else if((ss.equalsIgnoreCase("true")))
{
}
else if((ss.equalsIgnoreCase("dummy")))
{
}
else
{
editor.putString("showdialog_login", "false");
editor.commit();
}
}
Upvotes: 0
Reputation: 1262
Instead of :
prefs.getString("showdialog_login", null)
Use:
prefs.getString("showdialog_login", "")
Because, if value for "showdialog_login" preference is not set, it will return null value and you might get NPE (Null pointer exception).
Upvotes: 2