Okay, check 开发者_运维技巧this source code:
public void checkSession() {
SharedPreferences session = getSharedPreferences(PREFS_NAME, 1);
String getSession = session.getString("SESSION", null);
Toast.makeText(this, getSession, Toast.LENGTH_SHORT).show();
if(getSession.length() > 30) {
Intent menu = new Intent(this, menu.class);
startActivity(menu);
finish();
}
else
{
}
}
The problem is that "first time users" get crush.
When I disable the function, run the app and login the code creates session. After that when I logout, and restart the app - there's no problem. Any ideas?
First time the app runs and you don't have a value stored in the SharedPreference "SESSION" you return null as your default value. The getSession().length will then result in a NullPointerException.
You should do like this instead:
String getSession = session.getString("SESSION", "");
If getSession is null, I think Toast.makeText will fall over.* You might want to change the default return to "" from null. getSession.length() won't work if getSession is null either.
*Apparently that isn't true -- see TofferJ's comment.
精彩评论