Download and display images of a specified URL in Android

Source: Internet
Author: User

It seems that there has been no writing technology for a long timeArticleNow, I just recently sorted out the android development that I did a while ago and recorded it here. This is a simple application-download and display images from a specified URL.

To be honest, there is nothing special about this application. The scale is very small and the technology used is also very common, but it is a good theme for hands-on. Since it is an android application, it involves some technical aspects of Android development as follows:

1. controls such as imageswitcher, imageview, gallery, dialog, processbar

2. Network Access-httpclient, httpentity, httpget, httpresponse, etc.

3. Image File Processing-bitmap, bitmapfactory, bytearrayoutputstream, etc.

4. Java-such as weakreference

5. Unit Test-activityinstrumentationtestcase2, largetest, keyevent, etc.

Because you are not prepared to save the image file to external storage, the Read and Write contents of the database and disk files are not involved in this example. Next we will first analyze the requirements based on the software engineering practices.

In fact, it is not complicated. Let's think about the basic requirements below:

1. Enter the URL

2. Download images

3. display images

To further optimize this application, we also need to do the following:

4. Good interaction interfaces-such as URL input, error handling, and Image Display

5. Performance Optimization-memory usage, network latency, etc.

Now, after the requirements are determined, we will enter the development stage. In fact, we need to further split the Demand Based on Agile development methods. However, this is not the case if you do it yourself. Based on TDD practice principles, I will first write some tests. This is because the android project created using eclipse (there are a lot of steps to build a development environment on the Internet ). You can build a test project while building the project. Assume that the project is named picshow.

After this step, we will get two picshow and picshowtest projects. AddCodeBefore that, I want to add some test code to the picshowtest project,

In the future, a class called picshow will be used to display the downloaded image. Therefore, in the setup method, write:

 
@ Overrideprotected void setup () throws exception {super. Setup (); Final picshow A = getactivity (); assertnotnull ();}

When you write this code, the compilation will fail, because the picshow class is not defined yet. So we can use the magic of Eclipse's quick correction function (CTRL + 1) to create a new class. Create a textbox to enter a URL and a button to process click events. In Android, you have two options to create controls. One is to generate an instance using code and the other is to use the layout file. The usual practice is to select the latter (you can write less code), and finally you need an imageview object to display the image. Now you need to add the real test code:

@ Largetest
Public VoidTestdownloadimage ()ThrowsException {
Sendkeys (keyevent. keycode_enter );
Systemclock. Sleep (5000 );
Simpleimageviewlistadapter adapter = (simpleimageviewlistadapter) Ga. getadapter ();
Imageview IV = (imageview) Adapter. getitem (0 );
Asserttrue (IV. getdrawable ()! =Null);
}

In Android testing, there are several annotation: @ smalltest, @ mediumtest, @ largetest. What are the differences between these annotation operations?

Feature Small Medium Large
Network Access No Localhost only Yes
Database No Yes Yes
File System Access No Yes Yes
Use external systems No Discouraged Yes
Multiple Threads No Yes Yes
Sleep statements No Yes Yes
System Properties No Yes Yes
Time limit (seconds) 60 300 900 +

It is mainly related to the test content. We need to use the @ largetest flag to access the network during the test. Next, we will write a code for downloading the image to call the Click Event of the button:

 Public Bitmap loadimagefromurl (string URL) Throws Exception {
Final Defaulthttpclient client =New Defaulthttpclient ();
Final Httpget getrequest = New Httpget (URL );

Httpresponse response = client.exe cute (getrequest );
Int Statuscode = response. getstatusline (). getstatuscode ();
If (Statuscode! = Httpstatus. SC _ OK ){
Log. E ("picshow", "request URL failed, error code =" + statuscode );
}

Httpentity entity = response. getentity ();
If (Entity = Null ){
Log. E ("picshow", "httpentity is null ");
}
Inputstream is = Null ;
Bytearrayoutputstream baos = New Bytearrayoutputstream ();
Try {
Is = entity. getcontent ();
Byte [] Buf = New Byte [1024];
Int Readbytes =-1;
While (Readbytes = is. Read (BUF ))! =-1 ){
Baos. Write (BUF, 0, readbytes );
}
} Finally {
If (Baos! = Null ){
Baos. Close ();
}
If (Is! = Null ){
Is. Close ();
}
}
Byte [] Imagearray = baos. tobytearray ();
Return Bitmapfactory. decodebytearray (
Imagearray, 0, imagearray. Length );
}

In this way, a simple image download application is ready. The complete code is here

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.