gpt4 book ai didi

android - 在内部存储android上下载文件时出错

转载 作者:行者123 更新时间:2023-11-29 21:53:30 26 4
gpt4 key购买 nike

因为我认为下载非常简单,所以当我尝试从 Internet 下载 xml 文件并将其保存在内部存储器时遇到错误。我使用内存是因为我正在三星 galaxy s3 上测试我的应用程序。

这是下载器的代码。它实际上是一个从 Activity 中调用的线程

public class DownloaderThread extends Thread
{
private static final int DOWNLOAD_BUFFER_SIZE = 4096;
Context context;
private String downloadUrl = "some address";

public void run()
{
URL url;
URLConnection conn;
String fileName;
BufferedInputStream inStream;
BufferedOutputStream outStream;
File outFile;
FileOutputStream fileStream;

try
{
url = new URL(downloadUrl);
conn = url.openConnection();
conn.setUseCaches(false);
fileName = "file.xml";

Log.v("XML", "Download Started");

// start download
inStream = new BufferedInputStream(conn.getInputStream());
outFile = new File(context.getFilesDir() + "/" + fileName);
fileStream = new FileOutputStream(outFile);
outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0;
while(!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
outStream.write(data, 0, bytesRead);
}

outStream.close();
fileStream.close();
inStream.close();

if(isInterrupted())
{
outFile.delete();
}
else
{
Log.v("XML","Download Finished");
Log.v("PATH","File is stored in direcotry:" + outFile.getAbsolutePath().toString());
}
}
catch(MalformedURLException e)
{
e.printStackTrace();
Log.v("Error",e.toString());

}
catch(FileNotFoundException e)
{
e.printStackTrace();
Log.v("Error",e.toString());
}
catch(Exception e)
{
e.printStackTrace();
Log.v("Error",e.toString());
}
}

这里是调用线程的代码:

public boolean onOptionsItemSelected(MenuItem item) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo datac = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ( item.getItemId() == DOWNLOAD_XML_MENU_ITEM ) {
if ((wifi != null & datac != null) && (wifi.isConnected() | datac.isConnected()))
{
downloaderThread = new DownloaderThread();
downloaderThread.start();
}
else
{
displayConnectionAlert();
}
}
return true;
}

我收到的错误是: 标记跟踪 - 没有这样的文件和目录在日志下载开始后,我在 outFile 的路径上得到 NullPointerException。任何想法为什么?

最佳答案

您正在使用从未分配过值的 Context 引用,因此是 NPE。

Context context; // never initialised anywhere, thus null

由于所有变量都用于解析 context.getFilesDir(),我建议您只需为您的线程类创建一个构造函数,将路径作为参数;即:

public DownloaderThread(String targetDir) { /* implement here */ }

或者,您实际上可以传入 Context 实例,但只需确保它是应用程序上下文(而不是 Activity)以避免潜在的内存泄漏。

关于android - 在内部存储android上下载文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13846918/

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