I am trying to upload an image and then display it in my imageView component.
To download, I have to use Asyntask and display a progress bar to inform the user. The problem is that after going through the loop, in order to get the computed execution value, I get 0 from inputStream.
Log.d("is", "" + inputStream.available());
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());
bmp = BitmapFactory.decodeStream(inputStream);
Is there a way to get the calculated value for the progress bar and not get the value 0 at the end of the input stream?
I am using Asyntask here.
Explanation
bmp will matter, and when I do this
imageView.setImageBitmap(bmp);it will work ONLY IF I delete the loop and just callbmp = BitmapFactory.decodeStream(inputStream);
However , if I set the loop before doing this
bmp = BitmapFactory.decodeStream(inputStream);
imageView will not show anything
,
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) {
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;
}