简体   繁体   中英

SharedPreferences getString NULL parameter

Will I receive an error (Exception) on some devices if I set the second parameter of SharedPreferences.getString NULL?

SharedPreferences settings = ...

String data = settings.getString(_.PREFIX , null);

Will it cause an exception or an error on at least one device? Or I have to wrap this part of code in try-catch block?

If you are asking if you will get an exception if you set the second parameter to null, the answer is no (at least not unless you reference the result without first checking it is not null). The second parameter in the getString() method is the default value (ie the value that will be returned if there is nothing found for your prefix. So, it is perfectly acceptable to set null as your default value, as long as you realize (and account for) the fact that the value returned by your getString() could be null.

String data = settings.getString(_.PREFIX , null/ Null here is default value /); null - u can receive when your SraredPreferences have not this item(For example if u call/get this string before setting to this field any info or user clear cash of application from settings of device). I think it's can be normal situation, and u can remove "null" with some default value if you hope to got it(some emum field). If u don't suppose get null validate data before using. I thin'k your app must be ready get both variant, because user can change normal workflow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM