After the introduction of a blog post to the server to return JSON data to the Android client, this article on the basis of the addition of image download and listview display functions. The simple layout of adding a ListView first is as follows, and the content displayed in the ListView is the picture, name, and price.
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"Android:id= "@+id/vview"Android:layout_width= "Fill_parent"Android:layout_height= "Fill_parent"Android:background= "@drawable/listviewbackground"Android:paddingbottom= "5DP"Android:paddingleft= "5DP"Android:paddingright= "5DP"Android:paddingtop= "5DP" > <ImageView Android:id= "@+id/image"Android:layout_width= "80DP"Android:layout_height= "65DP"android:src= "@drawable/image_loading"/> <TextView Android:id= "@+id/title"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_marginleft= "5DP"Android:layout_torightof= "@id/image"Android:textcolor= "#000000"android:textsize= "13DP"Android:textstyle= "Italic"/> <TextView Android:id= "@+id/time"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignparentbottom= "true"Android:layout_below= "@id/title"Android:layout_marginleft= "5DP"Android:layout_margintop= "5DP"Android:layout_torightof= "@id/image"Android:textcolor= "#000000"android:textsize= "11DP"/></relativelayout>
Next, you need to customize an adapter for the ListView, which is inherited by the custom adapter Arrayadapter<picturebean> In the constructor method of the custom adapter, call the constructor of the parent class directly to deploy the Picturebean object to the adapter, and then override its GetView method to add the display to the control in the ListView. The code for this section is as follows:
Packagecom.example.restaurant;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;Importandroid.app.Activity;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.ArrayAdapter;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView;ImportCom.example.domain.PictureBean; Public classMyimageandtextlistadapterextendsArrayadapter<picturebean> { PublicMyimageandtextlistadapter (context context, list<picturebean>newslist) { Super(Context, 0, newslist); } PrivateMap<integer, view> viewmap =NewHashmap<integer, view>(); @Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {View Rowview= This. Viewmap.get (position); if(Rowview = =NULL) {Layoutinflater inflater= (Activity) This. GetContext ()). Getlayoutinflater (); Rowview= Inflater.inflate (R.layout.item,NULL); Picturebean Picture= This. GetItem (position); TextView TextView=(TextView) Rowview.findviewbyid (r.id.title); Textview.settext (Picture.getname ()); TextView TextView2=(TextView) Rowview.findviewbyid (r.id.time); Textview2.settext ("Price:" +Picture.getprice ()); ImageView ImageView=(ImageView) Rowview.findviewbyid (r.id.image); String Str= Picture.getname () + "$" + picture.getprice () + ". jpg"; Bitmap Bitmap= Bitmapfactory.decodefile ("/sdcard/restaurant/" +str); Imageview.setimagebitmap (bitmap); Viewmap.put (position, rowview); } returnRowview; }}
After the layouts and adapters have been added, the data is read and displayed in the next step. In Mainactivity's OnCreate () method, the data is first judged in the database, if the database is empty, the data is read from the server, and if not NULL, the data is read directly from the database. The code to get the data from the server is as follows:
/*** Get picture information from the server and save the picture on SDcard*/ Private voidUpdatefromserver () {showprogressdialog (); Getinfothread=NewThread (NewRunnable () {@Override Public voidrun () {Try { //get picture information and path JSON returned from the serverPictures =uptadepictureservice.getjsonpictures (); } Catch(Exception e) {//Toast.maketext (mainactivity.this, "Connection Server failed! ", //toast.length_short). Show ();}finally{Downok=true; } } }); Getinfothread.start (); /*** Download Picture thread*/Getpicturethread=NewThread (NewRunnable () {@Override Public voidrun () {Try { //wait for the picture information thread to finish executing while(Getinfothread.getstate ()! =Thread.State.TERMINATED) {} for(Picturebean picture:pictures) {/*** Process the path passed in * For example: E:\webTest\Restaurant\WebContent\Pictures * \ Sichuan \ Four-Hi Meatball $22.jpg * convert it to: restaurant/pictures/Sichuan/four-hi meatballs $22.jpg */String str= Picture.getname () + "$" + picture.getprice () + ". jpg"; Bitmap Bitmap=bitmapfactory. DecodeFile ("/sdcard/restaurant/" +str); if(Bitmap = =NULL) {String URL=Picture.getpath (); String[] Strlist= Url.split ("\\\\"); URL= Strlist[2] + "/" + strlist[4] + "/" + strlist[5] + "/" + strlist[6]; //Download the image and save it in the SD cardDown_file ("http://192.168.1.103:8080/" +URL,"/sdcard/restaurant/"); }} Message msg=NewMessage (); Msghandle.sendmessage (msg); } Catch(Exception e) {//Toast.maketext (mainactivity.this, "Connection Server failed! ", //toast.length_short). Show ();}finally { } } }); Getpicturethread.start (); } Public voidDown_file (string URL, string path)throwsException {String filename= Url.substring (Url.lastindexof ("/") + 1); /*** Processing Chinese path: Because Urlencoder.encode will transcode '/' and ': ', this error can be avoided by the following code*/string[] Strlist= Url.split ("\\/"); URL= ""; for(String mstr:strlist) {if(Mstr.contains (":") ) {URL= URL + mstr + "/"; } Else{URL= URL + urlencoder.encode (MSTR, "utf-8") + '/'; }} URL= url.substring (0, Url.length ()-1); LOG.D ("Mainactivity", URL); URL Myurl=Newurl (URL); HttpURLConnection Conn=(HttpURLConnection) myurl.openconnection (); Conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"); if(Conn.getresponsecode () = = 200) {InputStream InputStream=Conn.getinputstream (); File File=NewFile (path); if(!file.exists ()) {File.mkdir (); } FileOutputStream out=NewFileOutputStream (path +filename); //storing data in Path + file name byteBuf[] =New byte[1024]; Do { //Loop Read intNumread =Inputstream.read (BUF); if(Numread = =-1) { Break; } out.write (BUF,0, Numread); } while(true); Inputstream.close (); } }
Next, add an Update menu button that will get the latest menu information from the server. To deploy the application to the Android simulator, the basic effect is as follows:
Android Gets the image resource path returned by the server and downloads the picture