Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8216897
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T12:17:28+00:00 2026-06-07T12:17:28+00:00

I’m trying to get an image from a server and use that file as

  • 0

I’m trying to get an image from a server and use that file as the background fro my app.
Ive already leared that I should use AsyncTask to do so but my app still crashes or freezes when I run it.

Heres the code I use:

To call the AsyncTask:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent BG = new Intent((Intent) DownloadBGTask.THREAD_POOL_EXECUTOR);

The AsyncTask:

import java.net.URL;

import com.pxr.tutorial.json.Getbackground;

import android.os.AsyncTask;

public class DownloadBGTask extends AsyncTask<URL, Integer, Long> {
    protected Long doInBackground(URL... urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Getbackground.downloadFile(urls[i]);
            publishProgress((int) ((i / (float) count) * 100));
            // Escape early if cancel() is called
            if (isCancelled()) break;
        }
        return totalSize;
    }

    protected void onProgressUpdate(Integer... progress) {
        // Things to be done while execution of long running operation
    }

    protected void onPostExecute(Long result) {
        // xecution of result of Long time consuming operation
    }
}

And the Getbackground.java:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.Environment;

public class Getbackground {
    URL url;

    public static long downloadFile(URL url2) {
    try {

        URL url = new URL ("http://oranjelan.nl/oranjelan-bg.png");
        InputStream input = url.openStream();{
        try {

            File fileOnSD=Environment.getExternalStorageDirectory();    
            String storagePath = fileOnSD.getAbsolutePath();
            OutputStream output = new FileOutputStream (storagePath + "/oranjelangbg.png");
                try {

                    byte[] buffer = new byte[1000000];
                    int bytesRead = 0;
                    while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, bytesRead);
                    }
                    } finally {
            output.close();
            }
            } catch (IOException e) {
            throw new RuntimeException(e);
    } finally {
        try {
            input.close();
            } catch (IOException e) {
            throw new RuntimeException(e);
     }
   }    
 }    
        } catch (MalformedURLException ex) {
         throw new RuntimeException(ex);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

        return 0;
    }
}

PS, Sorry for the crappy code, I’m really new to this so dont be supprised if there are some really stupid misakes in there.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T12:17:31+00:00Added an answer on June 7, 2026 at 12:17 pm

    Since your comment says it’s hanging on this line:

    Intent BG = new Intent((Intent) DownloadBGTask.THREAD_POOL_EXECUTOR);
    

    let’s start with that.

    Since it sounds like you might be a newbie (no shame in that!), I’m guessing that you don’t necessarily need this task to execute in parallel.

    If you read the Android docs on AsyncTask, they kind of try to steer you away from that:

    Order of execution

    When first introduced, AsyncTasks were executed serially on a single
    background thread. Starting with DONUT, this was changed to a pool of
    threads allowing multiple tasks to operate in parallel. Starting with
    HONEYCOMB, tasks are executed on a single thread to avoid common
    application errors caused by parallel execution.

    If you truly want parallel execution, you can invoke
    executeOnExecutor(java.util.concurrent.Executor, Object[]) with
    THREAD_POOL_EXECUTOR.

    So, if you just want to pass a url, or a list of urls to the task to execute in order (series), then just start your task like this:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DownloadBGTask downloader = new DownloadBGTask();
        downloader.execute(new URL("http://www.google.com"), 
                           new URL("http://stackoverflow.com"));
    

    Where the strings are the URLs you want to retrieve (can be 1, or many). The parameters to execute() get passed to your task’s doInBackground() method.


    Edit: Now that you seem to have gotten past starting the task, here’s a couple other suggestions:

    1. 1000000 bytes seems like a large buffer to me. I’m not saying it won’t work, but I usually use something like byte[1024].

    2. Concerning the directory where you store your downloads. This is the code I like to use:

    private File mDownloadRootDir;
    private Context mParent;        // usually this is set to the Activity using this code
    
    private void callMeBeforeDownloading() {
        // http://developer.android.com/guide/topics/data/data-storage.html#filesExternal
        mDownloadRootDir = new File(Environment.getExternalStorageDirectory(),
            "/Android/data/" + mParent.getPackageName() + "/files/");
        if (!mDownloadRootDir.isDirectory()) {
            // this must be the first time we've attempted to download files, so create the proper external directories
            mDownloadRootDir.mkdirs();
        }
    }
    

    and later

    storagePath = mDownloadRootDir.getAbsolutePath();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I am trying to render a haml file in a javascript response like so:
I want use html5's new tag to play a wav file (currently only supported
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka
I'm trying to create an if statement in PHP that prevents a single post
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.