画像をダウンロードし、プログレスバーを表示して、そのビットマップを返すための次のコードがあります。しかし、ビットマップは常にnullを返します。whileループを削除すると、ビットマップには値がありますが、プログレスバーが表示されません。
@Override
protected Bitmap doInBackground(String... params) {
bitmap = null;
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
int lenghtOfFile = connection.getContentLength();
InputStream input = connection.getInputStream();
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/DCIM/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (IOException e) {
Log.e("could not load ", e.getMessage());
e.printStackTrace();
return null;
}
}
protected void onProgressUpdate(Integer... progress) {
pDialog.setProgress(progress[0]);
}
public void onPostExecute(Bitmap result) {
pDialog.dismiss();
listener.onTaskCompleted(result);
}
enter code here
InputStreamは1回しか読み取ることができません。コードを次のように変更する必要があります:
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
String pathName=Environment
.getExternalStorageDirectory().toString()
+ "/DCIM/downloadedfile.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加