Android HTTP Tutorial-Download Image from Internet

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Android HTTP Tutorial-Download Image from Internet

Postby nickmoi451 » Mon Apr 08, 2013 4:26 am

This simple sample, we will show you how to download a image from URL using HttpURLConnection.
Create XML layout. main.xml
Hide content
Code: Select all
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#FFFFFF"
        android:orientation="vertical" >
     
        <!-- Image view to show image after downloading -->
     
        <ImageView
            android:id="@+id/my_image"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
        <!-- Download Button -->
     
        <Button
            android:id="@+id/btndownload"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="10dp"
            android:text="Download Image" />
     
    </LinearLayout>




Required Permission

Code: Select all
<!-- Permission: Allow Connect to Internet -->
    <uses-permission android:name="android.permission.INTERNET" />


Download Image from URL using HttpURLConnection.
Code: Select all

    int count;
                try {
                    URL url = new URL(f_url[0]);
                    URLConnection conection = url.openConnection();
                    conection.setConnectTimeout(TIME_OUT);
                    conection.connect();
                    // Getting file length
                    int lenghtOfFile = conection.getContentLength();
                    // Create a Input stream to read file - with 8k buffer
                    InputStream input = new BufferedInputStream(url.openStream(),
                            8192);
                    // Output stream to write file
                    OutputStream output = new FileOutputStream(
                            "/sdcard/9androidnet.jpg");
     
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        // After this onProgressUpdate will be called
                        publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                        // writing data to file
                        output.write(data, 0, count);
                    }
                    // flushing output
                    output.flush();
                    // closing streams
                    output.close();
                    input.close();
                } catch (SocketTimeoutException e) {
                    connectionTimeout=true;
                } catch (Exception e) {
                    Log.e("Error: ", e.getMessage());
                }



Full Code in MainActivity.java

public class MainActivity extends Activity {

Button btnDownload;
// Progress Dialog
private ProgressDialog dialog;
ImageView myimage;
// Progress dialog type (0 - for Horizontal progress bar,1- for Vertical)
public static final int progress_bar_type = 0;

// File url to download
private static String image_url = "http://www.9android.net/wp-content/uploads/2013/03/android-bikini.jpg";
private int TIME_OUT = 20000;// 20s
private boolean connectionTimeout=false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// show progress bar button
btnDownload = (Button) findViewById(R.id.btndownload);
// Image view to show image after downloading
myimage = (ImageView) findViewById(R.id.my_image);
/**
* Show Progress bar click event
* */
btnDownload.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// Starting new Async Task
new DownloadImageFromURL().execute(image_url);
}
});
}

/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
dialog = new ProgressDialog(this);
dialog.setMessage("Downloading file. Please wait...");
dialog.setIndeterminate(false);
dialog.setMax(100);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setCancelable(true);
dialog.show();
return dialog;
default:
return null;
}
}

/**
* @author: 9Android.net Background Async Task to download file from URL
* */
class DownloadImageFromURL extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}

/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(TIME_OUT);
conection.connect();
// Getting file length
int lenghtOfFile = conection.getContentLength();
// Create a Input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
OutputStream output = new FileOutputStream(
"/sdcard/9androidnet.jpg");

byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (SocketTimeoutException e) {
connectionTimeout=true;
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

return null;
}

/**
* @author 9Android.net Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
dialog.setProgress(Integer.parseInt(progress[0]));
}

/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
if(connectionTimeout==true)
{showToast("Connection Timeout");
connectionTimeout=false;
}
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);

// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory()
.toString() + "/9androidnet.jpg";
// setting downloaded into image view
myimage.setImageDrawable(Drawable.createFromPath(imagePath));
}

}

/**
* @author 9Android.net
* @param text
*/
private void showToast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
}


Download code project: http://www.dl.9android.net/index.php?ac ... 1363308938
Source: http://www.9android.net/http-protocol/
nickmoi451
Freshman
Freshman
 
Posts: 6
Joined: Mon Apr 08, 2013 2:12 am

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 4 guests