Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/193.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android:GetSharedReferences用于会话_Android_Session - Fatal编程技术网

Android:GetSharedReferences用于会话

Android:GetSharedReferences用于会话,android,session,Android,Session,好的,检查以下源代码: public void checkSession() { SharedPreferences session = getSharedPreferences(PREFS_NAME, 1); String getSession = session.getString("SESSION", null); Toast.makeText(this, getSession, Toast.LENGTH_SHORT).show(); if(getSess

好的,检查以下源代码:

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 
    {   
    }
}
问题是“第一次用户”会被迷住

当我禁用该功能时,运行应用程序并登录代码创建会话。之后,当我注销,并重新启动应用程序-没有问题。有什么想法吗?

如果getSession为null,我认为Toast.makeText将失效。*您可能需要将默认返回值从null更改为“”。如果getSession也为null,则getSession.length()将不起作用

*显然这不是真的——请参阅TofferJ的评论。

如果getSession为null,我认为Toast.makeText将失效。*您可能需要将默认返回值从null更改为“”。如果getSession也为null,则getSession.length()将不起作用


*显然这不是真的——请参阅TofferJ的评论。

当应用程序第一次运行时,如果SharedReference“SESSION”中没有存储值,则返回null作为默认值。getSession().length随后将导致NullPointerException

您应该这样做:

String getSession = session.getString("SESSION", "");

首次运行应用程序时,如果SharedReference“SESSION”中没有存储值,则返回null作为默认值。getSession().length随后将导致NullPointerException

您应该这样做:

String getSession = session.getString("SESSION", "");
Toast.makeText(this,getSession,Toast.LENGTH_SHORT).show();实际上不会导致崩溃。可以将null作为消息发送给toast。但是,这对用户来说不是很有用。:)Toast.makeText(this,getSession,Toast.LENGTH_SHORT).show();实际上不会导致崩溃。可以将null作为消息发送给toast。但是,这对用户来说不是很有用。:)