Android: Multi-thread graphics and text mixed row

Source: Internet
Author: User

Data preparation

The server-side data in this case is passed in JSON and used on the server side. NET develops a generic handler that serializes a product object that contains the name, price, and name of the picture, and the last data serialized in JSON format is returned to the client.

The data are as follows

1 [{"imagename": "Image1.png", "name": "Apple", "price":,
2 {"imagename": "Image2.png", "name": "Alarm Clock", "Price": 56},
3 {"imagename": "Image3.png", "name": "Cake", "Price":
4 {"imagename": "Image4.png", "name": "0 Wallet", "Price": 8 },
5 {"imagename": "Image5.png", "Name": "Book", "Price":
6 {"imagename": "Image6.png", "Name": "Candy", "price" :
7 {"imagename": "Image7.png", "name": "Watermelon", "Price": 2}]

The URL address for this case is managed using a Commonuri class:

1 package com.example.handlerimageortext;
2 
3 public class Commonuri {
4     //Access server Data Link
5 public     static final String Product_url = "HTTP://1 92.168.1.102:1231/json/returncommondityjson.ashx ";
6     //Picture Connection
7 public     static final String product_img= "http://192.168.1.102:1231/json/img/";
8}

  

Using Asynctask to get JSON data

In the UI thread, use Asynctask to access the network to get JSON data and parse it

 1 public class MyTask extends Asynctask<string, Void, list<map<string,object>>>{2 @Overr
 IDE 3 protected void OnPreExecute () {4 super.onpreexecute ();
 5//Display dialog Box 6 dialog.show (); 7} 8 9 @Override protected list<map<string, object>> Doinbackground (Str 
ing ... params) {One list<map<string,object>> list=new arraylist<map<string,object>> (); 
try {13//Get network JSON format data httpclient httpclient=new defaulthttpclient ();
HttpPost httppost=new HttpPost (params[0]);
HttpResponse Httpresponse=httpclient.execute (HttpPost); if (Httpresponse.getstatusline (). Getstatuscode () ==200) {a String Jsonstring=entityu
Tils.tostring (Httpresponse.getentity (), "utf-8");  19//Parse JSON format data and use a list<map> to store 20                   Jsonarray jsonarray=new Jsonarray (jsonstring); for (int i=0;i<jsonarray.length (); i++) {Jsonobject Jsonobject=jsonarra
Y.getjsonobject (i);
Map<string,object> map=new hashmap<string, object> ();
Map.put ("Name", Jsonobject.get ("name"));
Map.put ("Price", Jsonobject.get ("price"));
Map.put ("imagename", Jsonobject.get ("imagename"));
List.add (map); Exception e} catch (E.printstacktrace) (
);
return list;
@Override protected void OnPostExecute (list<map<string, object>> result) {
Panax Notoginseng Super.onpostexecute (result);
38//The query to the data passed to the adapter adapter.setdata (result); 40//Set adapter 41 for ListView            Listview.setadapter (adapter);
Adapter.notifydatasetchanged ();
43//Hidden dialog box Dialog.dismiss (); 45} 46}

Download picture information

In the above method, use Asynctask to access the network to obtain the product information, which has the name of the picture, can download the picture to the local by this address.

A new class is created to download a picture, but you need to access the picture's information in the main thread, and you can use an interface callback to handle the message Cheng sent over in handler. Comments are more complete, here is no longer tired.

 1 package com.example.handlerimageortext;
 2 3 Import java.io.IOException;
 4 Import java.net.MalformedURLException;
 5 Import Java.net.URL;
 6 Import android.graphics.drawable.Drawable;
 7 Import Android.os.Handler;
 8 Import Android.os.Message;
9 public class Downloadimage {One private string Image_path public downloadimage (string image_path) {
14//Save the download address of the picture This.image_path = Image_path;  LoadImage public void (final Imagecallback callback) {final Handler Handler = new Handler () {@Override public void Handlemessage (msg) {Super.handlemessage
(msg);
23//When the message is received, the method to invoke the interface callback is callback.getdrawable ((drawable) msg.obj);
25} 26}; 27//Open a new thread to access the picture data Runnable new Thread (new) {@Override public vo              ID run () {a try {33       Download picture for drawable object drawable drawable = Drawable.createfromstream (new URL (35
image_path). OpenStream (), "");
36//The Picture object is packaged into a message sent to Handler-Message.obtain ();
Message.what = 1;
Message.obj = drawable;
Handler.sendmessage (message); Malformedurlexception e) {e.printstacktrace ();} CA TCH (IOException e) {e.printstacktrace () ()}). Star
T (); 48} 49 50//define a public interface for performing callback operations the interface Imagecallback {getdrawable (D
Rawable draw); } 

Adapter for data

The above has obtained the data of the product in the JSON data, and the picture of the product, now declares a adapter class, inherits from Baseadapter, uses a layout XML resource file to populate the data.

 1 public class Myadapter extends baseadapter{2 private context;
 3 Private Layoutinflater Layoutinflater;
 4 private list<map<string,object>> List=null;
 5 public Myadapter {6 this.context=context;            
 7 Layoutinflater=layoutinflater.from (context); 8} 9 public void SetData (list<map<string,object>> List) {One this.lis
T=list;         @Override public int GetCount () {list.size () 17 
@Override public Object getitem (int position) {list.get (position);          @Override public long getitemid (int position) {Position 27             @Override public view GetView (int position, View Convertview, ViewGroup parent) {31 View View=null; if (convertview==null) {33//If view is empty, the view is populated with a layout XML resource file View=layoutinfla                
Ter.inflate (R.layout.item,null); }else{view=convertview TextView name= (TextView) view.fi
Ndviewbyid (R.ID.TEXTVIEW1);
TextView price= (TextView) View.findviewbyid (R.ID.TEXTVIEW2); 40//Because the ImageView control needs to be accessed in the callback interface, it needs to be declared final final ImageView imageview= (ImageView) View.findview
Byid (R.ID.IMAGEVIEW1);
Name.settext (List.get (position). Get ("name"). toString ());
Price.settext (List.get (position). Get ("price"). ToString ()); 44 45//Use Downloadimage, download address representative of the picture of Downloadimage downloadimage=new downloadimage (
Commonuri.product_img+list.get (position). Get ("imagename"). toString ());             47//using the callback interface, set ImageView picture Downloadimage.loadimage (New Imagecallback () {   
@Override public void getdrawable (drawable draw) {Wuyi image
View.setimagedrawable (Draw);
52} 53});
The return view; 55} 56}

Effect Display:

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.