Android GPX解析报错:No content provider 问题求助
解决GPX解析时的FileNotFoundException问题
错误原因
getContentResolver().openInputStream()仅适用于Android系统的Content Provider Uri(格式通常为content://开头,指向本地内容),而你传入的是服务器的http/https协议URL,不属于Content Provider的处理范围,因此抛出找不到内容提供者的异常。
解决方案
方案1:直接通过网络获取InputStream解析
将网络请求放在子线程中执行(避免主线程网络操作异常),直接获取服务器文件的输入流进行解析:
new Thread(() -> { Gpx parsedGpx = null; GPXParser parser = new GPXParser(); try { URL url = new URL(stringUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 获取网络输入流 InputStream inputStream = connection.getInputStream(); parsedGpx = parser.parse(inputStream); // 解析完成后回到主线程处理结果(如更新UI) runOnUiThread(() -> { // 这里处理解析后的GPX数据 }); inputStream.close(); connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } }).start();
方案2:先下载文件到本地再解析
如果需要保留文件副本,可先将GPX文件下载到应用私有存储,再读取本地文件的输入流解析:
new Thread(() -> { Gpx parsedGpx = null; GPXParser parser = new GPXParser(); try { URL url = new URL(stringUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 创建应用私有目录下的临时文件 File gpxFile = new File(getExternalFilesDir(null), "temp.gpx"); FileOutputStream outputStream = new FileOutputStream(gpxFile); InputStream inputStream = connection.getInputStream(); // 下载文件到本地 byte[] buffer = new byte[1024]; int readLen; while ((readLen = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, readLen); } // 读取本地文件输入流进行解析 parsedGpx = parser.parse(new FileInputStream(gpxFile)); runOnUiThread(() -> { // 处理解析后的GPX数据 }); inputStream.close(); outputStream.close(); connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } }).start();
注意事项
- 所有网络操作必须放在子线程中,Android 4.0及以上版本禁止主线程执行网络请求。
- 使用
getExternalFilesDir()存储文件无需动态权限,若需写入公共外部存储,需申请WRITE_EXTERNAL_STORAGE动态权限(Android 6.0+)。 - 可使用OkHttp、Retrofit等第三方网络库简化网络请求逻辑,提升代码可读性。
内容的提问来源于stack exchange,提问作者maciek_123_123
相关产品推荐
相关产品推荐

