在Android项目中如果使用字符串路径会提示 Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead,如图所示
原因是因为硬编码不是对任何设备都适合,在一些设备上可能会给出错误消息或无法正常工作。可以做如下替换。
String dirPath= "/data/data/com.weather.app/shared_prefs/";改为
String dirPath = this.getApplication().getFilesDir().getParentFile().getPath()+"/shared_prefs/";
这样的话就能解决问题了。
本文探讨了在Android开发中避免路径硬编码的技巧,并提供了将字符串路径替换为应用上下文获取文件目录路径的实用解决方案,以确保代码在不同设备上的兼容性和稳定性。
958





