Android开发:筛选以MYNET开头的WiFi列表时应用崩溃求助
Hey there! Let's troubleshoot why your app crashes when filtering WiFi networks that start with "MYNET". Based on your description, the most likely issues are null pointer exceptions (from empty SSIDs) or unsafe UI/data operations. Here's how to fix it step by step:
Common Crash Causes & Fixes
1. Null SSID Values (Most Likely Culprit)
Some WiFi networks (like hidden ones) might return a null SSID. Calling startsWith() on a null string will immediately throw a NullPointerException.
Fixed Filtering Logic
Add a null check before checking the SSID prefix:
@SuppressLint("MissingPermission") private void filterAndDisplayNetworks() { WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); List<ScanResult> allNetworks = wifiManager.getScanResults(); List<ScanResult> filteredNetworks = new ArrayList<>(); // Guard against null scan results if (allNetworks != null) { for (ScanResult result : allNetworks) { // Check SSID is not null before checking prefix if (result.SSID != null && result.SSID.startsWith("MYNET")) { filteredNetworks.add(result); } } } // Update the ListActivity's adapter safely setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getSsidList(filteredNetworks))); } // Helper to extract SSIDs for display private List<String> getSsidList(List<ScanResult> networks) { List<String> ssids = new ArrayList<>(); for (ScanResult result : networks) { ssids.add(result.SSID); } return ssids; }
2. Unsafe UI Updates in BroadcastReceiver
If you're updating the list from a BroadcastReceiver, make sure you run the UI update on the main thread. Broadcast receivers often run on background threads, and modifying the UI there will cause crashes.
Fix for BroadcastReceiver
private BroadcastReceiver wifiScanReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false); if (success) { // Run UI updates on main thread runOnUiThread(() -> filterAndDisplayNetworks()); } } };
3. Missing Permissions (Hidden Cause)
Ensure you've requested the necessary permissions in your manifest and at runtime (for Android 6.0+):
<!-- In AndroidManifest.xml --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
For runtime permission request (in your Activity):
private static final int PERMISSIONS_REQUEST_CODE = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkPermissions(); } private void checkPermissions() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_CODE); } else { // Start WiFi scan if permissions are granted startWifiScan(); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == PERMISSIONS_REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startWifiScan(); } else { // Handle permission denial Toast.makeText(this, "Location permission required to scan WiFi", Toast.LENGTH_SHORT).show(); } } }
Final Checks
- Make sure you're not modifying the list adapter's data source from multiple threads (this causes
ConcurrentModificationException). - Test with networks that have empty/hidden SSIDs to verify the fix works.
内容的提问来源于stack exchange,提问作者SMACKDOWN

