Reputation: 471
First and foremost , I have read the questions with the same title as mine here;
So please go through the question once. I am developing an application that takes values from a shared preference file and puts those values in EditText
fields, for this I have used setText()
method. I keep getting this warning in android studio. I realize this is just a warning , but I would like to know
Code is as follows:
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"));
And lastly I get the same warning with getText()
used with EditText
;Why? and How to rectify?
Upvotes: 0
Views: 1323
Reputation: 97
Declare EditText in class level and then initialize further in onCreate(). this would solve your problem.
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"));
...
}
}
You can refer to this link as answer given by @Rod_Algonquin. it gives you a reason for this.
EditText.setText() Null Pointer Exception
Upvotes: 1
Reputation: 155
Your question is a duplicate as if you read some answers such as here (as linked by @Ironman). The warning states
This is no error, it is just a warning. The static analyzer cannot deduce that your EditText or the result from EditText.getText() isn't null. The keyword here is 'may'.
Adding a (possibly unnecessary) null-check for both instances will make the warning disappear.
As Answered by @nhaarman in the linked question.
Upvotes: 0