【问题标题】:Android app crashes because of Shared preferrence由于共享偏好,Android 应用程序崩溃
【发布时间】:2011-09-09 22:56:32
【问题描述】:

在我的应用程序的第一个活动中,一开始我正在检查 SharedPreferrence 是否包含一些值。如果为空,则打开第一个活动,如果不是,我想打开我的应用程序的第二个活动。

以下是我的代码的一部分。

SharedPreferences prefs = this.getSharedPreferences( "idValue", MODE_WORLD_READABLE );
public void onCreate(Bundle savedInstanceState)
{       
   super.onCreate(savedInstanceState);  
   setContentView(R.layout.login);
  if(prefs.getString("idValue", "")==null)
    {
        userinfo();
    }
    else
    {
        Intent myIntent = new Intent(getBaseContext(), Add.class);
    startActivityForResult(myIntent, 0);
    }
}

当我签入 logcat 时,它在以下行显示错误

但是当第一个活动打开时我的应用程序崩溃了

 SharedPreferences prefs = this.getSharedPreferences( "idValue", MODE_WORLD_READABLE );

以下是我的 logcat 详细信息....

AndroidRuntime(5747): Uncaught handler: thread main exiting due to uncaught exception
AndroidRuntime(5747): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.gs.cc.sp/com.gs.cc.sp.UserInfo}: java.lang.NullPointerException
AndroidRuntime(5747): Caused by: java.lang.NullPointerException
AndroidRuntime(5747):     at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
AndroidRuntime(5747):     at com.gs.cc.sp.UserInfo.<init>(UserInfo.java:62)
AndroidRuntime(5747):     at java.lang.Class.newInstanceImpl(Native Method)
AndroidRuntime(5747):     at java.lang.Class.newInstance(Class.java:1479)
AndroidRuntime(5747):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
AndroidRuntime(5747):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)

请朋友们告诉我哪里出错了

【问题讨论】:

  • 顺便说一句:if(prefs.getString("idValue", "")==null) 永远不会为真,因为如果没有“idValue”,则默认值(“”)已设置,不为空。

标签: android android-activity sharedpreferences switching


【解决方案1】:

您在启动之前正在访问您的类的当前实例this,这就是您收到空指针异常的原因。

SharedPreferences prefs = null;
public void onCreate(Bundle savedInstanceState)
{       
   super.onCreate(savedInstanceState);  
   setContentView(R.layout.login);
prefs = this.getSharedPreferences( "idValue", MODE_WORLD_READABLE );
  if(prefs.getString("idValue", "")==null)
    {
        userinfo();
    }
    else
    {
        Intent myIntent = new Intent(getBaseContext(), Add.class);
    startActivityForResult(myIntent, 0);
    }
}

【讨论】:

    【解决方案2】:

    你没有说,但我假设你在调用userinfo()时初始化了一些用户信息。

    关于prefs.getString,您需要知道的是它永远不会返回null。您提供的第二个参数定义了如果首选项不存在它将返回的值 - 因此在您的示例中您可能应该使用:

    if ( prefs.getString ( "idValue", "" ).equals ( "" ) )
    {
        userinfo();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 2021-04-20
      • 2016-04-06
      • 1970-01-01
      • 2023-03-15
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      相关资源
      最近更新 更多