[Tutorial] Http android sample source code

  • Replies:0
  • OpenNot stickiedUnanswered

Apr 8, 2013 8:13:28 AM via Website

It is small quote from tutorial at http://www.9android.net/http-protocol/
This simple sample, we will show you how to download a image from URL using HttpURLConnection.
Thanks for 9android developer, who provide this turial
Create XML layout. main.xml


1<?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="schemas.android.com/apk/res/android"
3 android:layout_width="fill_parent"
4 android:layout_height="fill_parent"
5 android:background="#FFFFFF"
6 android:orientation="vertical" >
7
8 <!-- Image view to show image after downloading -->
9
10 <ImageView
11 android:id="@+id/my_image"
12 android:layout_width="fill_parent"
13 android:layout_height="wrap_content"
14 android:layout_weight="1" />
15 <!-- Download Button -->
16
17 <Button
18 android:id="@+id/btndownload"
19 android:layout_width="wrap_content"
20 android:layout_height="wrap_content"
21 android:layout_gravity="center_horizontal"
22 android:layout_margin="10dp"
23 android:text="Download Image" />
24
25 </LinearLayout>



Required Permission.

1<!-- Permission: Allow Connect to Internet -->
2 <uses-permission android:name="android.permission.INTERNET" />

Download Image from URL using HttpURLConnection.


1int count;
2 try {
3 URL url = new URL(f_url[0]);
4 URLConnection conection = url.openConnection();
5 conection.setConnectTimeout(TIME_OUT);
6 conection.connect();
7 // Getting file length
8 int lenghtOfFile = conection.getContentLength();
9 // Create a Input stream to read file - with 8k buffer
10 InputStream input = new BufferedInputStream(url.openStream(),
11 8192);
12 // Output stream to write file
13 OutputStream output = new FileOutputStream(
14 "/sdcard/9androidnet.jpg");
15
16 byte data[] = new byte[1024];
17 long total = 0;
18 while ((count = input.read(data)) != -1) {
19 total += count;
20 // publishing the progress....
21 // After this onProgressUpdate will be called
22 publishProgress("" + (int) ((total * 100) / lenghtOfFile));
23 // writing data to file
24 output.write(data, 0, count);
25 }
26 // flushing output
27 output.flush();
28 // closing streams
29 output.close();
30 input.close();
31 } catch (SocketTimeoutException e) {
32 connectionTimeout=true;
33 } catch (Exception e) {
34 Log.e("Error: ", e.getMessage());
35 }

Full Code in MainActivity.java

1public class MainActivity extends Activity {
2
3 Button btnDownload;
4 // Progress Dialog
5 private ProgressDialog dialog;
6 ImageView myimage;
7 // Progress dialog type (0 - for Horizontal progress bar,1- for Vertical)
8 public static final int progress_bar_type = 0;
9
10 // File url to download
11 private static String image_url = "9android.net/wp-content/uploads/2013/03/android-bikini.jpg";
12 private int TIME_OUT = 20000;// 20s
13 private boolean connectionTimeout=false;
14 @Override
15 public void onCreate(Bundle savedInstanceState) {
16 super.onCreate(savedInstanceState);
17 setContentView(R.layout.main);
18
19 // show progress bar button
20 btnDownload = (Button) findViewById(R.id.btndownload);
21 // Image view to show image after downloading
22 myimage = (ImageView) findViewById(R.id.my_image);
23 /**
24 * Show Progress bar click event
25 * */
26 btnDownload.setOnClickListener(new View.OnClickListener() {
27
28 @Override
29 public void onClick(View v) {
30 // Starting new Async Task
31 new DownloadImageFromURL().execute(image_url);
32 }
33 });
34 }
35
36 /**
37 * Showing Dialog
38 * */
39 @Override
40 protected Dialog onCreateDialog(int id) {
41 switch (id) {
42 case progress_bar_type:
43 dialog = new ProgressDialog(this);
44 dialog.setMessage("Downloading file. Please wait...");
45 dialog.setIndeterminate(false);
46 dialog.setMax(100);
47 dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
48 dialog.setCancelable(true);
49 dialog.show();
50 return dialog;
51 default:
52 return null;
53 }
54 }
55
56 /**
57 * @author: 9Android.net Background Async Task to download file from URL
58 * */
59 class DownloadImageFromURL extends AsyncTask<String, String, String> {
60
61 /**
62 * Before starting background thread Show Progress Bar Dialog
63 * */
64 @Override
65 protected void onPreExecute() {
66 super.onPreExecute();
67 showDialog(progress_bar_type);
68 }
69
70 /**
71 * Downloading file in background thread
72 * */
73 @Override
74 protected String doInBackground(String... f_url) {
75 int count;
76 try {
77 URL url = new URL(f_url[0]);
78 URLConnection conection = url.openConnection();
79 conection.setConnectTimeout(TIME_OUT);
80 conection.connect();
81 // Getting file length
82 int lenghtOfFile = conection.getContentLength();
83 // Create a Input stream to read file - with 8k buffer
84 InputStream input = new BufferedInputStream(url.openStream(),
85 8192);
86 // Output stream to write file
87 OutputStream output = new FileOutputStream(
88 "/sdcard/9androidnet.jpg");
89
90 byte data[] = new byte[1024];
91 long total = 0;
92 while ((count = input.read(data)) != -1) {
93 total += count;
94 // publishing the progress....
95 // After this onProgressUpdate will be called
96 publishProgress("" + (int) ((total * 100) / lenghtOfFile));
97 // writing data to file
98 output.write(data, 0, count);
99 }
100 // flushing output
101 output.flush();
102 // closing streams
103 output.close();
104 input.close();
105 } catch (SocketTimeoutException e) {
106 connectionTimeout=true;
107 } catch (Exception e) {
108 Log.e("Error: ", e.getMessage());
109 }
110
111 return null;
112 }
113
114 /**
115 * @author 9Android.net Updating progress bar
116 * */
117 protected void onProgressUpdate(String... progress) {
118 // setting progress percentage
119 dialog.setProgress(Integer.parseInt(progress[0]));
120 }
121
122 /**
123 * After completing background task Dismiss the progress dialog
124 * **/
125 @Override
126 protected void onPostExecute(String file_url) {
127 if(connectionTimeout==true)
128 {showToast("Connection Timeout");
129 connectionTimeout=false;
130 }
131 // dismiss the dialog after the file was downloaded
132 dismissDialog(progress_bar_type);
133
134 // Displaying downloaded image into image view
135 // Reading image path from sdcard
136 String imagePath = Environment.getExternalStorageDirectory()
137 .toString() + "/9androidnet.jpg";
138 // setting downloaded into image view
139 myimage.setImageDrawable(Drawable.createFromPath(imagePath));
140 }
141
142 }
143
144 /**
145 * @author 9Android.net
146 * @param text
147 */
148 private void showToast(String text) {
149 Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
150 }
151 }

— modified on Apr 15, 2013 7:02:26 AM