【发布时间】:2011-07-22 14:03:49
【问题描述】:
我在这里没有找到任何类似的问题。
昨天我终于在我的 Nexus One 上安装了 Gingerbread 2.3.4。当我再次打开我的应用程序(基本上将 XML Feed 加载到 ListView 中)时,它在下载时卡住了。
似乎是 InputStream 流; -> 流。读取(缓冲区);完成后不再返回 -1。
代码与这里的代码几乎相同Download Progress
这是我的代码:
public InputStream getInputStreamFromURL(String urlString, DownloadProgressCallback callback)
throws IOException, IllegalArgumentException
{
InputStream in = null;
conn = (HttpURLConnection) new URL(urlString).openConnection();
fileSize = conn.getContentLength();
out = new ByteArrayOutputStream((int) fileSize);
conn.connect();
stream = conn.getInputStream();
// loop with step 1kb
while (status == DOWNLOADING) {
byte buffer[];
if (fileSize - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[(int) (fileSize - downloaded)];
}
int read = stream.read(buffer);
if (read == -1) {
break;
}
// writing to buffer
out.write(buffer, 0, read);
downloaded += read;
// update progress bar
callback.progressUpdate((int) ((downloaded / fileSize) * 100));
}// end of while
if (status == DOWNLOADING) {
status = COMPLETE;
}
in= (InputStream) new ByteArrayInputStream(out.toByteArray());
// end of class DownloadImageTask()
return in;
}
问题基本上是当下载完成时,stream.read(buffer) 返回 0 而不是 -1。当我改变
if (read == -1) {
break;
}
到 0 或
if (fileSize == downloaded) {
break;
}
我的 MainActivity 上出现 ParseExceptions (ExpatParser)。 在 2.2 上,它运行得非常完美。
我已经清除了应用缓存并尝试了其他一些方法,但我现在真的卡住了。
我希望有人可以帮助我。 :)
更新:
太棒了,你就是那个人,纪尧姆。 :) 非常感谢,这拯救了我的夜晚! :)
您的代码在这里满足我的需求:
public InputStream getStreamFromURL(String urlString, DownloadProgressCallback callback){
// initialize some timeouts
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,3000);
// create the connection
URL url;
try {
url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
// connection accepted
if(httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
int size = connection.getContentLength();
int index = 0;
int current = 0;
InputStream input = connection.getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
byte[] bBuffer = new byte[1024];
out = new ByteArrayOutputStream((int) size);
while((current = buffer.read(bBuffer)) != -1) {
out.write(bBuffer, 0, current);
index += current;
callback.progressUpdate((index/size)*100);
}
out.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (InputStream) new ByteArrayInputStream(out.toByteArray());
}
【问题讨论】:
标签: android download inputstream