我正在尝试下载图像,然后将其显示到我的imageView组件。
要下载,我必须使用Asyntask并显示进度条以通知用户。问题是在经过循环后得到计算的进度值,我从inputStream得到0。
Log.d("is", "" + inputStream.available()); // ---> will have a value
byte[] buffer = new byte[contentLenght];
while ((read = inputStream.read(buffer)) != -1) {
counter += read;
publishProgress(counter);
outputStream.write(buffer,0,read);
}
Log.d("is", "" + inputStream.available()); // -----> will return 0
bmp = BitmapFactory.decodeStream(inputStream); // bmp will be empty
有没有办法获得进度条的计算值,而不是在输入流的末尾得到0值?
我在这里使用Asyntask。
imageView.setImageBitmap(bmp);
它会起作用仅在时我移除了循环,只需拨打bmp = BitmapFactory.decodeStream(inputStream);
然而如果我在执行此操作之前放置一个循环
bmp = BitmapFactory.decodeStream(inputStream);
imageView将不显示任何内容
这是我的完整Asynctask代码,包括网络连接
int progressCounter;
int contentLenght;
int counter;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
protected Boolean doInBackground(String... params) {
return ConnectToInternet(params[0]);
}
@Override
protected void onPostExecute(Boolean aVoid) {
//Log.d("buff",bmp.toString());
progressBar.setVisibility(View.GONE);
imageView.setImageBitmap(bmp);
}
@Override
protected void onProgressUpdate(Integer... values) {
progressCounter =(int) (((double) values[0] / contentLenght) * 100);
progressBar.setProgress(progressCounter);
}
boolean ConnectToInternet(String url){
boolean sucessfull = false;
URL downloadURL = null;
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
downloadURL = new URL(url);
connection = (HttpURLConnection) downloadURL.openConnection();
inputStream = connection.getInputStream();
contentLenght = connection.getContentLength();
Log.d("is", "" + inputStream.available());
int read = -1;
byte[] buffer = new byte[contentLenght];
while ((read = inputStream.read(buffer)) != -1) {
counter += read;
publishProgress(counter);
}
Log.d("is", "" + inputStream.available());
bmp = BitmapFactory.decodeStream(inputStream);
sucessfull = true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
connection.disconnect();
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sucessfull;
}
感谢
答案 0 :(得分:2)
while
语句完全占用了inputStream
,因此BitmapFactory.decodeStream(inputStream)
中没有任何内容可供解码。
试试这个:
boolean ConnectToInternet(String url){
// ...
int read;
// contentLength may be too big,
// so read stream in smaller chunks.
//
// there's a typo in contentLenght :)
byte[] buffer = new byte[4096];
// Object for storing partially downloaded image.
ByteArrayOutputStream imageBaos = new ByteArrayOutputStream();
// Initialize counter.
counter = 0;
while ((read = inputStream.read(buffer)) != -1) {
counter += read;
publishProgress(counter);
// Store downloaded chunk.
imageBaos.write(buffer, 0, read);
}
// Obtain bitmap from downloaded chunks.
bmp = BitmapFactory.decodeByteArray(imageBaos.toByteArray(), 0, imageBaos.size());
// ...
}