gpt4 book ai didi

尝试从网络服务器获取 txt 文件时,android 应用程序崩溃

转载 作者:行者123 更新时间:2023-11-30 04:00:54 25 4
gpt4 key购买 nike

我的应用程序在尝试获取远程 txt 文件时崩溃。即使只是尝试解析它崩溃的 url。已设置互联网权限并且设备/虚拟机已连接到互联网。

登录目录: enter image description here

代码 fragment :

try {
// the following line is enough to crash the app
URL url = new URL("http://www.i.am/not/going/to/show/you/this.txt");


BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = null;
while ((line = in.readLine()) != null) {
//get lines
}
in.close();


} catch (MalformedURLException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}

我不明白我做错了什么。提前感谢您的帮助。

//编辑:添加日志猫 fragment

最佳答案

应用程序由于主 UI 线程上的大量网络 Activity 而崩溃,这本身并不是一个很好的做法,因为应用程序可能会停止响应并可能被操作系统终止。您应该始终尝试在一些单独的线程中进行后台处理,而不是在主 UI 线程中。

将用于获取文件的代码放在 AsyncTaskdoInBackground() 中.

private class DownloadFile extends AsyncTask<String, Integer, Void> {
protected void doInBackground() {
try {

URL url = new URL("http://www.i.am/not/going/to/show/you/this.txt");

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = null;
while ((line = in.readLine()) != null) {
//get lines
}
in.close();


} catch (MalformedURLException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}

protected void onProgressUpdate() {
//called when the background task makes any progress
}

protected void onPreExecute() {
//called before doInBackground() is started
}
protected void onPostExecute() {
//called after doInBackground() has finished
}
}

您可以通过 new DownloadFile().execute(""); 调用此任务以获取文件文件。

关于尝试从网络服务器获取 txt 文件时,android 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12521456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com