【问题标题】:EditText Method invocation may produce java.lang.NullpointerExceptionEditText 方法调用可能产生 java.lang.NullpointerException
【发布时间】:2016-10-25 17:48:17
【问题描述】:

首先,我在这里阅读了与我的标题相同的问题;

所以请把问题看一遍。我正在开发一个应用程序,它从共享首选项文件中获取值并将这些值放在EditText 字段中,为此我使用了setText() 方法。我在 android studio 中不断收到此警告。我意识到这只是一个警告,但我想知道

  1. 是什么原因造成的?
  2. 如何解决这个问题?

代码如下:

    EditText sil_key = (EditText)findViewById(R.id.silent_key);
    EditText gen_key = (EditText)findViewById(R.id.general_key);
    EditText vib_key = (EditText)findViewById(R.id.vibrate_key);
    SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.preference_file_key),MODE_PRIVATE);
    sil_key.setText(sharedPreferences.getString("silent","silent"));
    gen_key.setText(sharedPreferences.getString("general","general"));
    vib_key.setText(sharedPreferences.getString("vibrate","vibrate"));

最后我得到了与getText()EditText 一起使用的相同警告;为什么?以及如何纠正?

【问题讨论】:

  • 请注意。 Studio 有一个“合同”系统。如果函数可以返回 null,则该变量的一个可能值为 null。然后,如果您请求对可以为空的变量进行操作,则会出现警告,同样会发生,如果您使用返回布尔值的函数,对无法保存它的变量进行操作,或者对变量执行操作未初始化等...这些警告是一个单一的“合同->事件”系统,可帮助开发人员解决常见的小错误。
  • @Ironman 您标记的问题没有答案,我在发布此问题之前已经看到了它
  • @Bonatti 谢谢,但是有什么办法可以解决吗?
  • 是的。您可以确保合同有效(如if(sil_key!=null){...stuffs...})或删除带有@SuppressWarnings("The warning type")的警告标志

标签: android nullpointerexception android-edittext sharedpreferences


【解决方案1】:

您的问题是重复的,就像您阅读了一些答案一样,例如here (as linked by @Ironman)。警告状态

这不是错误,只是一个警告。静态分析器无法推断出您的 EditText 或 EditText.getText() 的结果不为空。这里的关键字是“可能”。

为两个实例添加(可能不必要的)空检查将使警告消失。

@nhaarman 在链接的问题中回答。

【讨论】:

  • 我已经看到了这个问题,并在我的问题中说明这是一个警告而不是错误,我想知道如何解决这个问题
  • 已经明白这不是错误或警告。我的回答中的引用专门告诉您如何避免该警告。 Adding a (possibly unnecessary) null-check for both instances will make the warning disappear.
  • 没关系,我接受的答案效果很好。顺便说一句,我应该如何添加空检查?使用 if(isNull) 之类的?
【解决方案2】:

在类级别声明 EditText,然后在 onCreate() 中进一步初始化。这将解决您的问题。

class Test extends AppCompactActivity{

private EditText sil_key;

onCreate(){

...

sil_key = (EditText)findViewById(R.id.silent_key);

SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.preference_file_key),MODE_PRIVATE);
    sil_key.setText(sharedPreferences.getString("silent","silent"));

...
    }
 }

您可以参考此链接作为@Rod_Algonquin 给出的答案。它给了你一个理由。

EditText.setText() Null Pointer Exception

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多