国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android開發(fā)實(shí)現(xiàn)ListView異步加載數(shù)據(jù)的方法詳解

2019-10-22 18:21:58
字體:
供稿:網(wǎng)友

本文實(shí)例講述了Android開發(fā)實(shí)現(xiàn)ListView異步加載數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:

1.主Activity

public class MainActivity extends Activity {  private ListView listView;  private ArrayList<Person> persons;  private ListAdapter adapter;  private Handler handler=null;  //xml文件的網(wǎng)絡(luò)地址  final String path="http://192.168.5.10:8080/FileServer/person.xml";  @SuppressLint("HandlerLeak")  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);    listView=(ListView) super.findViewById(R.id.listview);    //cache=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/cache");    //開一條子線程加載網(wǎng)絡(luò)數(shù)據(jù)    Runnable runnable=new Runnable()    {      public void run()       {        try         {          Thread.sleep(2000);          //xmlwebData解析網(wǎng)絡(luò)中xml中的數(shù)據(jù)          persons=XmlwebData.getData(path);          //發(fā)送消息,并把persons結(jié)合對(duì)象傳遞過去          handler.sendMessage(handler.obtainMessage(0, persons));        }         catch (InterruptedException e)         {          e.printStackTrace();        }      }    };    try     {      //開啟線程      new Thread(runnable).start();      //handler與線程之間的通信及數(shù)據(jù)處理      handler=new Handler()      {        public void handleMessage(Message msg)         {          if(msg.what==0)          {            //msg.obj是獲取handler發(fā)送信息傳來的數(shù)據(jù)            @SuppressWarnings("unchecked")            ArrayList<Person> person=(ArrayList<Person>) msg.obj;            //給ListView綁定數(shù)據(jù)            BinderListData(person);          }        }      };    }     catch (Exception e)     {      e.printStackTrace();    }  }  //綁定數(shù)據(jù)  public void BinderListData(ArrayList<Person> person)  {    //創(chuàng)建adapter對(duì)象    adapter=new ListViewAdapter(R.layout.item,this,person);    //將Adapter綁定到listview中    listView.setAdapter(adapter);  }}

2.從網(wǎng)絡(luò)中獲取xml文件并解析數(shù)據(jù)

public class XmlwebData {  private static ArrayList<Person> persons=null; 6   public static ArrayList<Person> getData(final String path)  {        try         {          URL url=new URL(path);          Person person=null;          HttpURLConnection conn=(HttpURLConnection) url.openConnection();          conn.setRequestMethod("GET");          conn.setConnectTimeout(5000);          if(conn.getResponseCode()==200)          {            InputStream inputstream=conn.getInputStream();             XmlPullParser xml=Xml.newPullParser();            xml.setInput(inputstream, "UTF-8");            int event=xml.getEventType();            while(event!=XmlPullParser.END_DOCUMENT)            {              switch (event)               {              //開始解析文檔              case XmlPullParser.START_DOCUMENT:                persons=new ArrayList<Person>();                break;              case XmlPullParser.START_TAG:                String value=xml.getName();                if(value.equals("person"))                {//person對(duì)象的初始化必須在這里初始化不然可能出現(xiàn)為null的現(xiàn)象                  person=new Person();                  //獲取屬性值                  person.setId(new Integer(xml.getAttributeValue(0)));                }                else if(value.equals("name"))                {                  person.setName(xml.nextText());                }                else if(value.equals("sex"))                {                  person.setSex(xml.nextText());                }                else if(value.equals("age"))                {                  person.setAge(new Integer(xml.nextText()));                }                else if(value.equals("path"))                {                  person.setPath(xml.nextText());                }                break;              case XmlPullParser.END_TAG:                if(xml.getName().equals("person"))                {                  persons.add(person);                  System.out.println(person.getName());;                  person=null;                }                break;              }              //解析下一個(gè)對(duì)象              event=xml.next();            }            return persons;          }        }         catch (Exception e)         {          e.printStackTrace();        }     return null;  }}

3.Person對(duì)象類

public class Person {  private int id;  private String name;  private String sex;  private String path;  public String getPath() {    return path;  }  public void setPath(String path) {    this.path = path;  }  private int age;  public int getId() {    return id;  }  public void setId(int id) {    this.id = id;  }  public String getName() {    return name;  }  public void setName(String name) {    this.name = name;  }  public String getSex() {    return sex;  }  public void setSex(String sex) {    this.sex = sex;  }  public int getAge() {    return age;  }  public void setAge(int age) {    this.age = age;  }  public Person(){  }}

4.Adapter數(shù)據(jù)適配器類

public class ListViewAdapter extends BaseAdapter implements ListAdapter {  private ArrayList<Person> data;  private int id;  private Context context;  private LayoutInflater inflater;  public ListViewAdapter(int item, MainActivity mainActivity,ArrayList<Person> data)   {    this.data=data;    this.context=mainActivity;    this.id=item;    inflater=LayoutInflater.from(context);  }  @Override  public int getCount()   {    return data.size();  }  @Override  public Object getItem(int position)   {    return data.get(position);  }  @Override  public long getItemId(int position)  {    return position;  }  @Override  public View getView(int position, View view, ViewGroup arg2)  {    TextView name=null;    TextView sex=null;    TextView age=null;    ImageView img=null;    if(view==null)    {      view=inflater.inflate(id, null);      name=(TextView) view.findViewById(R.id.PersonName);      sex=(TextView) view.findViewById(R.id.PersonSex);      age=(TextView) view.findViewById(R.id.PersonAge);      img=(ImageView) view.findViewById(R.id.Personimage);      //保存view對(duì)象到ObjectClass類中      view.setTag(new ObjectClass(name,sex,age,img));    }    else    {      //得到保存的對(duì)象      ObjectClass objectclass=(ObjectClass) view.getTag();      name=objectclass.name;      sex=objectclass.sex;      age=objectclass.age;      img=objectclass.img;    }    Person person=(Person) data.get(position);    //幫數(shù)據(jù)綁定到控件上    name.setText(person.getName().toString());    sex.setText("性別:"+person.getSex().toString());    age.setText("年齡:"+String.valueOf(person.getAge()));    //加載圖片資源    LoadImage(img,person.getPath());    return view;  }  private void LoadImage(ImageView img, String path)   {    //異步加載圖片資源    AsyncTaskImageLoad async=new AsyncTaskImageLoad(img);    //執(zhí)行異步加載,并把圖片的路徑傳送過去    async.execute(path);  }  private final class ObjectClass  {    TextView name=null;    TextView sex=null;    TextView age=null;    ImageView img=null;    public ObjectClass(TextView name, TextView sex, TextView age,ImageView img)     {      this.name=name;      this.sex=sex;      this.age=age;      this.img=img;    }  }}

5.異步加載圖片類

public class AsyncTaskImageLoad extends AsyncTask<String, Integer, Bitmap> {  private ImageView Image=null;  public AsyncTaskImageLoad(ImageView img)   {    Image=img;  }  //運(yùn)行在子線程中  protected Bitmap doInBackground(String... params) {    try     {      URL url=new URL(params[0]);      HttpURLConnection conn=(HttpURLConnection) url.openConnection();      conn.setRequestMethod("POST");      conn.setConnectTimeout(5000);      if(conn.getResponseCode()==200)      {        InputStream input=conn.getInputStream();        Bitmap map=BitmapFactory.decodeStream(input);        return map;      }    } catch (Exception e)     {      e.printStackTrace();    }    return null;  }  protected void onPostExecute(Bitmap result)  {    if(Image!=null && result!=null)    {      Image.setImageBitmap(result);    }    super.onPostExecute(result);  }}

6.網(wǎng)絡(luò)中的person.xml文件內(nèi)容為

<?xml version="1.0" encoding="UTF-8"?><Persons>  <person id="1">    <name>張三</name>    <sex>男</sex>    <age>25</age>    <path>http://192.168.5.10:8080/FileServer/chengjisihan.jpg</path>  </person>  <person id="2">    <name>李斯</name>    <sex>男</sex>    <age>78</age>    <path>http://192.168.5.10:8080/FileServer/laozi.jpg</path>  </person>  <person id="3">    <name>王五</name>    <sex>男</sex>    <age>22</age>    <path>http://192.168.5.10:8080/FileServer/lilongji.jpg</path>  </person>  <person id="4">    <name>龐聰</name>    <sex>男</sex>    <age>31</age>    <path>http://192.168.5.10:8080/FileServer/lishimin.jpg</path>  </person>  <person id="5">    <name>孫臏</name>    <sex>男</sex>    <age>48</age>    <path>http://192.168.5.10:8080/FileServer/lisi.jpg</path>  </person>  <person id="6">    <name>孫武</name>    <sex>男</sex>    <age>58</age>    <path>http://192.168.5.10:8080/FileServer/liyuan.jpg</path>  </person>  <person id="7">    <name>成吉思汗</name>    <sex>男</sex>    <age>40</age>    <path>http://192.168.5.10:8080/FileServer/sunbiin.jpg</path>  </person>  <person id="8">    <name>李淵</name>    <sex>男</sex>    <age>36</age>    <path>http://192.168.5.10:8080/FileServer/sunwu.jpg</path>  </person>  <person id="9">    <name>李隆基</name>    <sex>男</sex>    <age>32</age>    <path>http://192.168.5.10:8080/FileServer/wangwu.jpg</path>  </person>  <person id="10">    <name>武則天</name>    <sex>女</sex>    <age>55</age>    <path>http://192.168.5.10:8080/FileServer/wuzetian.jpg</path>  </person></Persons><?xml version="1.0" encoding="UTF-8"?><Persons>  <person id="1">    <name>張三</name>    <sex>男</sex>    <age>25</age>    <path>http://192.168.5.10:8080/FileServer/chengjisihan.jpg</path>  </person>  <person id="2">    <name>李斯</name>    <sex>男</sex>    <age>78</age>    <path>http://192.168.5.10:8080/FileServer/laozi.jpg</path>  </person>  <person id="3">    <name>王五</name>    <sex>男</sex>    <age>22</age>    <path>http://192.168.5.10:8080/FileServer/lilongji.jpg</path>  </person>  <person id="4">    <name>龐聰</name>    <sex>男</sex>    <age>31</age>    <path>http://192.168.5.10:8080/FileServer/lishimin.jpg</path>  </person>  <person id="5">    <name>孫臏</name>    <sex>男</sex>    <age>48</age>    <path>http://192.168.5.10:8080/FileServer/lisi.jpg</path>  </person>  <person id="6">    <name>孫武</name>    <sex>男</sex>    <age>58</age>    <path>http://192.168.5.10:8080/FileServer/liyuan.jpg</path>  </person>  <person id="7">    <name>成吉思汗</name>    <sex>男</sex>    <age>40</age>    <path>http://192.168.5.10:8080/FileServer/sunbiin.jpg</path>  </person>  <person id="8">    <name>李淵</name>    <sex>男</sex>    <age>36</age>    <path>http://192.168.5.10:8080/FileServer/sunwu.jpg</path>  </person>  <person id="9">    <name>李隆基</name>    <sex>男</sex>    <age>32</age>    <path>http://192.168.5.10:8080/FileServer/wangwu.jpg</path>  </person>  <person id="10">    <name>武則天</name>    <sex>女</sex>    <age>55</age>    <path>http://192.168.5.10:8080/FileServer/wuzetian.jpg</path>  </person></Persons>

運(yùn)行結(jié)果如下

Android,ListView,異步,加載數(shù)據(jù)

 

希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到Android開發(fā)頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 宝鸡市| 宜良县| 湟中县| 元江| 望都县| 游戏| 贵溪市| 丘北县| 古交市| 剑河县| 娄烦县| 绥滨县| 黄冈市| 丁青县| 安康市| 普安县| 册亨县| 芜湖县| 体育| 潜江市| 泰顺县| 胶南市| 容城县| 上杭县| 称多县| 即墨市| 肥西县| 武汉市| 彭阳县| 兴城市| 仁化县| 姚安县| 和田县| 昌都县| 巴中市| 温宿县| 石首市| 和政县| 大余县| 乌兰察布市| 萝北县|