字符串到整数Android

时间:2015-11-08 21:15:52

标签: android

我将String转换为Integer存在问题。

   public SharedPreferences abc;
   abc = getApplicationContext().getSharedPreferences("Trening",0);



   Integer i = Integer.parseInt(abc.getString("T1",null).toString()); 

错误是:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.String android.content.SharedPreferences.getString(java.lang.String, java.lang.String)' on a null object reference

我学会了3天的课程,并希望你能帮助我并解释如何解决它,所以我可以学习。

抱歉我的英文。 :)

3 个答案:

答案 0 :(得分:1)

当您在null中使用abc.getString("T1", null)作为第二个参数时,您实际上是在说: 如果" T1"未设置值,默认返回null 所以你有parsInt(null)并导致NullPointerExceprion。
您可以将abc.getString("T1", null)替换为abc.getString("T1", "0")
它将返回字符串" 0"作为" T1"的默认值(如果" T1"为空)。所以你有parsInt("0")它真的很有效。

答案 1 :(得分:1)

如果abc.getString("T1", null)返回null(如果没有Key-Value-Pair与密钥" T1"在您的SharedPreferences中),那么你会尝试获取字符串null。这会导致NullPointerException。您应该定义另一个可以转换为String的defaultValue。

除此之外,您可以退出toString()因为getString()返回一个字符串:

Integer i = Integer.parseInt(abc.getString("T1", "-1")); 

答案 2 :(得分:1)

所以问题基本上是变量 abc 为空,因此 getSharedPreferences 调用无法检索有效的引用。