waiting for the image to be downloaded before incrementing - android

I have a for loop that will download image on a server and here is what it looks
for (int i = 0; i < sync_data.length(); i++) {
String main_link = "LINK" + folder + "/" + file_name;
FilePathname = sdCardDirectory + "/" + file_name;
DownloadFilesname(FilePathname, main_link);
index++;
p = (float) index / (float) sync_data.length();
p = p * (float) 100;
runOnUiThread(new Runnable() {
#Override
public void run() {
publishProgress((int) p);
}
});
}
/* Function Image Download */
public void DownloadFilesname(String filanme, String Urlname) {
try {
URL u = new URL(Urlname);
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(new File(filanme));
while ((length = dis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
}
}
my problem is the publishProgress already updated even the image is not yet downloaded. This will cause the asynctask to be done but the image is still downloading..
How can I make that the image must be downloaded before increment?

You only have to call "publishProgress()" in your "doInBackground()" and then implement/override
protected void onProgressUpdate(Integer... progress) {
...
}
When you call "publishProgress()" the "onProgressUpdate()" event is called in the Ui/MainThread (it means you can use all the UI components inside it)

Related

OutOfMemory while downloading a PDF file

In an app I am making people can download a PDF file. On my Nexus 5 there is on problem when downloading the PDF but on an HTC One X I get an Out of Memory error. How can I avoid this? The code I am using is:
#Override
protected Boolean doInBackground(String... params) {
String fileUrl = params[0];
mFileName = params[1];
mFolder = new File(mContext.getFilesDir(), "pdfs");
mFolder.mkdir();
Random r = new Random();
int i1 = r.nextInt(99 - 10) + 99;
mFile = new File(mFolder, mFileName + "." + i1);
try {
mFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
System.gc();
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(mFile);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
long total = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
total += bufferLength;
int progress = (int)((total * 100) / totalSize);
publishProgress(progress, (int)total, totalSize);
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
return true;
} catch (FileNotFoundException e) {
mFile.delete();
e.printStackTrace();
} catch (MalformedURLException e) {
mFile.delete();
e.printStackTrace();
} catch (IOException e) {
mFile.delete();
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean success) {
if(mOnDownloadListener != null) {
File to = new File(mFolder, mFileName);
mFile.renameTo(to);
mOnDownloadListener.onDownloaded(success);
}
super.onPostExecute(success);
}

file download using asynctask stops in middle

I am creating an app for my client, one of his requirements is to download and install an external apk (size approx. 62mb) on the device. The devices will be rooted, so that's not a problem. But, while downloading the apk using AsyncTask, the progress bar resets to 0% after reaching 34% (exact 34% every time, even on different devices) and throws java.io.IOException: unexpected end of stream.
Here is the code I'm using :
public class InstallAPK extends AsyncTask<Void,Integer,Void> {
ProgressDialog progressDialog;
int status = 0;
private Context context;
public InstallAPK(Context context, ProgressDialog progress){
this.context = context;
this.progressDialog = progress;
}
public void onPreExecute() {
if(progressDialog!=null)
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
URL url = new URL(context.getString(R.string.kodi_apk_link));
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
// getting file length
int lenghtOfFile = c.getContentLength();
Log.e("File length", ""+lenghtOfFile);
File outputFile = new File(context.getFilesDir(), context.getString(R.string.kodi_apk_name));
if(outputFile.exists()){
if(outputFile.length() != lenghtOfFile)
outputFile.delete();
else {
publishProgress(-1);
final String libs = "LD_LIBRARY_PATH=/vendor/lib:/system/lib ";
final String commands = libs + "pm install -r " + context.getFilesDir().getAbsolutePath() + "/"
+ context.getString(R.string.kodi_apk_name);
installApk(commands);
return null;
}
}
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
//i tried both, with and without buffered reader
BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len1 = 0, total=0;
if (lenghtOfFile != -1)
{
buffer = new byte[lenghtOfFile];
do {
len1 += bufferedInputStream.read(buffer, len1, lenghtOfFile-len1);
publishProgress((int)((len1*100)/lenghtOfFile));
} while (len1 < lenghtOfFile);
}
//I was using this code before, but it's not working too
/*while ((len1 = is.read(buffer)) != -1) {
total += len1;
publishProgress((int)((total*100)/lenghtOfFile));
fos.write(buffer, 0, len1);
}*/
fos.flush();
fos.close();
bufferedInputStream.close();
is.close();
//Log.e("Directory path", myDir.getAbsolutePath());
publishProgress(-1);
final String libs = "LD_LIBRARY_PATH=/vendor/lib:/system/lib ";
final String commands = libs + "pm install -r " + context.getFilesDir().getAbsolutePath() + "/"
+ context.getString(R.string.kodi_apk_name);
installApk(commands);
} catch (FileNotFoundException fnfe) {
status = 1;
Log.e("File", "FileNotFoundException! " + fnfe);
}
catch(Exception e)
{
Log.e("UpdateAPP", "Exception " + e);
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
if(progress[0]!=-1) {
// setting progress percentage
progressDialog.setProgress(progress[0]);
} else {
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Installing Kodi...");
}
}
public void onPostExecute(Void unused) {
if(progressDialog!=null) {
progressDialog.dismiss();
}
if(status == 1)
Toast.makeText(context,"App Not Available",Toast.LENGTH_LONG).show();
else
Toast.makeText(context,"Successfully installed the app",Toast.LENGTH_LONG).show();
Intent LaunchIntent = context.getPackageManager().getLaunchIntentForPackage(context.getString(R.string.kodi_apk_package));
if(LaunchIntent!=null)
context.startActivity(LaunchIntent);
else
Toast.makeText(context, "Error in installig Kodi, Try again.", Toast.LENGTH_LONG).show();
}
private void installApk(String commands) {
try {
Process p = Runtime.getRuntime().exec("su");
InputStream es = p.getErrorStream();
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes(commands + "\n");
os.writeBytes("exit\n");
os.flush();
int read;
byte[] buffer = new byte[4096];
String output = new String();
while ((read = es.read(buffer)) > 0) {
output += new String(buffer, 0, read);
}
Log.v("AutoUpdaterActivity", output.toString());
p.waitFor();
} catch (IOException e) {
Log.v("AutoUpdaterActivity", e.toString());
} catch (InterruptedException e) {
Log.v("AutoUpdaterActivity", e.toString());
}
}
}
I tried everything to make this code work. But, it didn't. Then I found an alternative to this. I tried IntentService to download the apk, and surprisingly it worked. I think AsyncTask might have some kind of limit for downloading. To download using IntentService I used this code. The answer is very informative. It also has some other alternatives for downloading.
You should add connection timeout for HttpURLConnection.
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
//set timeout to 5 seconds , set your time here
c.setConnectTimeout(5000);
c.connect();
Its work for me.I hope its work for you.

Cannot download video file with android emulator

Here's the code to download a 3pg video file. Maybe one can give me an idea about what's wrong with it. I really need help. Can't get it to download the file:
Blockquote
protected String doInBackground(String... sUrl) {
byte[] data = new byte[1024];
int count = 0;
FileOutputStream fos = null;
BufferedOutputStream output = null;
try {
URL url= new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
Log.v("URL"," " + connection.getURL());
Log.v("File ", "length = " + connection.getContentLength());
// download the file
BufferedInputStream input = new BufferedInputStream(connection.getInputStream());
File f = new File(Environment.getExternalStorageDirectory().getPath() + "/twokids.3gp");
f.setWritable(true,true);
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException fnfe) {
fnfe.getStackTrace();
} catch (SecurityException se) {
se.getStackTrace();
}
output = new BufferedOutputStream(fos);
while ((count = input.read(data)) != -1) {
Log.v("Count="," " + count);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Log.v("Download","Finished");
} catch (IndexOutOfBoundsException iobe) {
iobe.getStackTrace();
} catch (IOException ioe) {
ioe.getStackTrace();
} catch (NullPointerException npe) {
npe.getStackTrace();
}
catch (Exception e) {
e.getStackTrace();
}
return null;
}
And strangely enough, sometimes the method connection.getContentLength() returns -1 instead of the file length.

for loop not incrementing in Doinbackground in async task

Im reading image url from a Array list in doInBackground using for loop , but loop is not incrementing only 1st url is loading and saving image . here is code :
class DownloadImageTask extends AsyncTask<Void, Void, Bitmap> {
// This class definition states that DownloadImageTask will take String
// parameters, publish Integer progress updates, and return a Bitmap
#SuppressWarnings("unused")
protected Bitmap doInBackground(Void... paths) {
//URL url;
try {
for(int j=0; j<List.size();j++)
{
reviewImageLink =List.get(j).get(TAG_Image);
URL url = new URL(reviewImageLink);
// URL reviewImageURL;
String name = reviewImageLink.substring(reviewImageLink .lastIndexOf("/") + 1,reviewImageLink.length());
//try {
if (!hasExternalStoragePublicPicture(name)) {
isImage = false;
//new DownloadImageTask().execute();
Log.v("log_tag", "if");
isImage = true;
File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources().getString(R.string.directory));
//if(!sdImageMainDirectory.exists()){
sdImageMainDirectory.mkdirs();
File file = new File(sdImageMainDirectory, name);
Log.v("log_tag", "Directory created");}
//}
// catch (MalformedURLException e) {
// Log.v(TAG, e.toString()); }
// }
// }//try
// catch (Exception e) {
// e.printStackTrace();}
//url = new URL(List.get(j).get(TAG_Image));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);
} else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length- downloaded);
} else {
read = is.read(imageData, downloaded, buffersize);
}
downloaded += read;
setProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;
}
}catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return null;
}
protected void onPostExecute(Bitmap result) {
String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1,reviewImageLink.length());
if (result != null) {
hasExternalStoragePublicPicture(name);
saveToSDCard(result, name);
isImage = true;
} else {
isImage = false;
}
}
}
List is an interface, you can't use like List.size().Define one List subtype like ArrayList or something.There is no wrong with for loop.For ex:
List<Integer> li = new ArrayList<Integer>();
li.add(10);
li.add(20)';
for(int i = 0; i <= li.size(); ++i) {
//your stuff
}

Managing multiple asynctask to download multiple images from html code, leaking ram, any ideas?

I'm developing an android app. Now I'm parsing bbcode to html and display it inside a textview, the textview is inside a custom listview. I use Html.ImageGetter() to display the images downloaded from AsyncTask.
It works great for a low number of pictures. But if the app is asked to download 40-50 pictures, 40-50 tasks are created and it becomes a mess. Each task opens a stream to download the images. After that it decodes the bytes into bitmaps, resize them, save them to the sdcard and recycles the bitmaps.
Now if the app is loading all this images at the same time it uses a huge amount of ram. I managed to make it pass 48 mb. There is a big gap between 16 and 48 :(. I searched on how to solve this. I downloaded AsyncTask code from google:
http://google.com/codesearch/p?hl=en&sa=N&cd=2&ct=rc#uX1GffpyOZk/core/java/android/os/AsyncTask.java&q=lang:java%20AsyncTask
And set the pool size to 3. But this didn't helped. I really can't figure out where I'm loosing ram. As soon as I put a big task queue my ram goes crazy. After a few images are received it gets worst. I don't think it is the images since I can get to 30 mb before any image is displayed. The app itself including the view, information and its service uses 13 mb, all the rest is leaked here.
Does the queue itself make big ram allocations? Or is the Html.ImageGetter() leaking a huge amount of memory somehow? Is there a better way to do this?
Here I load the images:
public void LoadImages(String source) {
myurl = null;
try {
myurl = new URL(source);
} catch (MalformedURLException e) {
e.printStackTrace();
}
new DownloadImageFromPost().execute(myurl);
}
private class DownloadImageFromPost extends AsyncTask<URL, Integer, Bitmap> {
#Override
protected Bitmap doInBackground(URL... params) {
URL url;
Log.d(TAG, "Starting new image download");
try {
url = params[0];
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);
} else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length
- downloaded);
} else {
read = is.read(imageData, downloaded, buffersize);
}
downloaded += read;
publishProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;
} catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(Bitmap result) {
String name = Environment.getExternalStorageDirectory() + "/tempthumbs/" + myurl.toString().hashCode() +".jpg";
String rname = Environment.getExternalStorageDirectory() + "/tempthumbs/" + myurl.toString().hashCode() +"-t.jpg";
try {
if (result != null) {
hasExternalStoragePublicPicture(name);
ImageManager manager = new ImageManager(context);
Bitmap rezised = manager.resizeBitmap(result, 300, 300);
saveToSDCard(result, name, myurl.toString().hashCode() +".jpg");
saveToSDCard(rezised, rname, myurl.toString().hashCode() +"-t.jpg");
result.recycle();
rezised.recycle();
} else {
}
} catch(NullPointerException e) {
}
Log.d(TAG, "Sending images loaded announcement");
Intent i = new Intent(IMAGE_LOADED);
i.putExtra("image", name);
i.putExtra("source", myurl.toString());
i.putExtra("class", true);
context.sendBroadcast(i);
}
}
private boolean hasExternalStoragePublicPicture(String name) {
File file = new File(name);
if (file != null) {
file.delete();
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return file.exists();
}
public void saveToSDCard(Bitmap bitmap, String name, String nam) {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
Log.v(TAG, "SD Card is available for read and write "
+ mExternalStorageAvailable + mExternalStorageWriteable);
saveFile(bitmap, name, nam);
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
Log.v(TAG, "SD Card is available for read "
+ mExternalStorageAvailable);
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
Log.v(TAG, "Please insert a SD Card to save your Video "
+ mExternalStorageAvailable + mExternalStorageWriteable);
}
}
private void saveFile(Bitmap bitmap, String fullname, String nam) {
ContentValues values = new ContentValues();
File outputFile = new File(fullname);
values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
values.put(MediaStore.MediaColumns.TITLE, nam);
values.put(MediaStore.MediaColumns.DATE_ADDED, System
.currentTimeMillis());
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
Uri uri = context.getContentResolver().insert(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);;
try {
OutputStream outStream = context.getContentResolver()
.openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
bitmap.recycle();
}
And here i call Html.ImageGetter(), this is inside a list getView:
holder.content.setText(Html.fromHtml(
processor.preparePostText(posts.get(position).post_content),
new Html.ImageGetter() {
#Override public Drawable getDrawable(String source) {
Log.d("Forum Service", "image source: " + source);
if (imageSources.contains(source)) {
for (int x = 0; x < imageSources.size(); x++) {
if (source.equals(imageSources.get(x))) {
String tmp = oImages.get(x);
tmp = tmp.substring(0, tmp.length() - 4);
tmp = tmp + "-t.jpg";
Drawable d = Drawable.createFromPath(tmp);
try {
d.setBounds(0, 0, d.getIntrinsicWidth(),
d.getIntrinsicHeight());
} catch (NullPointerException e) {
}
Log.d("Forum Service", "Loaded image froms sdcard");
return d;
}
}
} else if (notLoadedImages.contains(source)) {
Log.d("Forum Service", "Waiting for image");
return null;
} else {
notLoadedImages.add(source);
LoadAllIcons loader = new LoadAllIcons(context);
loader.LoadImages(source);
Log.d("Forum Service", "Asked for image");
return null;
}
return null;
}
}, null));
Thanks!
Finally the problem was that all Tasks loaded at the same time. Therefor 40 images where allocated in ram while downloading. I managed to limit the amount of running tasks by doing this modifications on AsyncTask:
private static final int CORE_POOL_SIZE = 2;
private static final int MAXIMUM_POOL_SIZE = 2;
private static final int KEEP_ALIVE = 1;
private static final BlockingQueue<Runnable> sWorkQueue =
new LinkedBlockingQueue<Runnable>(100);
Mateo there goes your answer http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
And you're done!

Categories

Resources