如何过滤SharedPreferences导入ArrayList中的空值?求正确代码
Hey there! I totally get how annoying it is when those unwanted empty or null values pop up in your ArrayList even after you tried adding checks. Let’s break down why your previous attempts might’ve failed and give you solid, working code to fix this.
Common Reasons Your Checks Didn’t Work
Chances are, you were only checking for null but not accounting for empty strings (or strings with just spaces). SharedPreferences can return empty strings if you set a default value like "" when using getString(), and those won’t trigger a null check.
Solution 1: Filter Values While Reading from SharedPreferences
This is the cleanest approach—we filter out bad values as we pull them from SharedPreferences instead of cleaning up later.
Case 1: Reading all key-value pairs
If you’re fetching all entries from SharedPreferences:
// Get your SharedPreferences instance SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE); Map<String, ?> allEntries = prefs.getAll(); ArrayList<String> filteredList = new ArrayList<>(); for (Map.Entry<String, ?> entry : allEntries.entrySet()) { Object value = entry.getValue(); // Skip null values, and strings that are empty or just whitespace if (value != null) { String strValue = value.toString(); if (!strValue.trim().isEmpty()) { filteredList.add(strValue); } } } // Now filteredList is ready to display—no empty/null items!
Case 2: Reading specific known keys
If you have a list of keys you need to fetch:
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE); // Replace with your actual keys String[] targetKeys = {"username", "email", "favoriteColor"}; ArrayList<String> filteredList = new ArrayList<>(); for (String key : targetKeys) { // Set default value to null instead of "" so we can detect missing keys String value = prefs.getString(key, null); // Check for both null AND empty/whitespace-only strings if (value != null && !value.trim().isEmpty()) { filteredList.add(value); } }
Solution 2: Clean Up an Existing ArrayList
If you already have an ArrayList that’s been populated (and has unwanted empty values), use an Iterator to safely remove bad entries (this avoids ConcurrentModificationException):
ArrayList<String> originalList = ...; // Your existing list with empty/null items Iterator<String> iterator = originalList.iterator(); while (iterator.hasNext()) { String item = iterator.next(); // Remove nulls, empty strings, and strings with only spaces if (item == null || item.trim().isEmpty()) { iterator.remove(); } } // originalList now has no unwanted entries
Key Takeaways
- Always set the default value to
nullwhen usinggetString()—this lets you tell the difference between a missing key and an intentionally empty value. - Don’t forget to check for whitespace-only strings with
trim().isEmpty()—they look empty but won’t be caught by a simple!value.isEmpty(). - Use an Iterator when removing items from a list during iteration to avoid errors.
内容的提问来源于stack exchange,提问作者Nouran Katana

