android 之适配器与json对象解析技术的联用的进一步优化(解决图片错位)
生活随笔
收集整理的這篇文章主要介紹了
android 之适配器与json对象解析技术的联用的进一步优化(解决图片错位)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ListView優化的模型示意圖
實例代碼:
業務邏輯代碼:
package com.hsj.example.asyncloadxmldatademo08;import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView;import com.hsj.example.asyncloadxmldatademo08.hsj.domain.Person; import com.hsj.example.asyncloadxmldatademo08.hsj.utils.NetUtils;import java.io.InputStream; import java.util.List;public class MainActivity extends AppCompatActivity {private ListView listView_persons;private MyAdapter adapter;private List<Person> personList;private ProgressDialog progressDialog;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);this.progressDialog=new ProgressDialog(this);this.progressDialog.setMessage("正在加載網絡數據,請稍等......");this.progressDialog.setCancelable(true);this.listView_persons= (ListView) this.findViewById(R.id.listView_persons);String path = "http://10.211.55.4:8080/persons.xml";new LoadNetDataAsyncTask().execute(path);}private final class LoadNetDataAsyncTask extends AsyncTask<String,Void,List<Person>> {@Overrideprotected void onPreExecute() {progressDialog.show();}@Overrideprotected List<Person> doInBackground(String... params) {try {InputStream inputStream= NetUtils.getInputStreamByPath(params[0]);if(inputStream!=null){String json= NetUtils.getStringByInputStream(inputStream);if(json!=null){return NetUtils.getPersonsByXmlString(json);}}} catch (Exception e) {e.printStackTrace();}return null;}@Overrideprotected void onPostExecute(List<Person> persons) {adapter=new MyAdapter(persons);listView_persons.setAdapter(adapter);progressDialog.dismiss();}}private final class MyAdapter extends BaseAdapter {private List<Person> personList;private ViewHolder viewHolder;public MyAdapter(List<Person> personList) {this.personList=personList;}@Overridepublic int getCount() {return personList.size();}@Overridepublic Object getItem(int position) {return personList.get(position);}@Overridepublic long getItemId(int position) {return position;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {//1.得到數據Person person=personList.get(position);if(convertView==null){viewHolder=new ViewHolder();convertView=View.inflate(MainActivity.this,R.layout.person_item,null);viewHolder.imageView_header= (ImageView) convertView.findViewById(R.id.imageView_header);viewHolder.textView_name= (TextView) convertView.findViewById(R.id.textView_name);viewHolder.textView_age= (TextView) convertView.findViewById(R.id.textView_age);convertView.setTag(viewHolder);}else{viewHolder= (ViewHolder) convertView.getTag();}//解決圖片錯位問題final String cover=person.getHeader();viewHolder.imageView_header.setTag(cover);//viewHolder.imageView_header.setImageBitmap(person.getHeader());class LoadImageAsyncTask extends AsyncTask<String,Void,Bitmap>{@Overrideprotected Bitmap doInBackground(String... params) {try {InputStream inputStream=NetUtils.getInputStreamByPath(params[0]);if(inputStream!=null){return BitmapFactory.decodeStream(inputStream);}} catch (Exception e) {e.printStackTrace();}return null;}@Overrideprotected void onPostExecute(Bitmap bitmap) {if(bitmap!=null && viewHolder.imageView_header.getTag()!=null && cover.equals(viewHolder.imageView_header.getTag())){viewHolder.imageView_header.setImageBitmap(bitmap);}}}new LoadImageAsyncTask().execute(person.getHeader());viewHolder.textView_name.setText(person.getName());viewHolder.textView_age.setText(String.valueOf(person.getAge()));return convertView;}}class ViewHolder{ImageView imageView_header;TextView textView_name;TextView textView_age;} }工具類代碼:
package com.hsj.example.asyncloadxmldatademo08.hsj.utils;import android.util.Xml;import com.hsj.example.asyncloadxmldatademo08.hsj.domain.Person;import org.xmlpull.v1.XmlPullParser;import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List;/*** Created by hsjwcf on 2018/6/1.*/ public class NetUtils {/*** 根據網址得到輸入流對象* @param path* @return*/public static InputStream getInputStreamByPath(String path) throws Exception {URL url=new URL(path);HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();httpURLConnection.setConnectTimeout(3000);int responseCode=httpURLConnection.getResponseCode();if(responseCode==HttpURLConnection.HTTP_OK){return httpURLConnection.getInputStream();}return null;}/*** 通過 InputStream 得到字節數組* @param inputStream* @return*/public static byte[] getByteArrayByInputStream(InputStream inputStream) throws IOException {ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();byte[] buffer=new byte[1024];int len=0;while ((len=inputStream.read(buffer))!=-1){byteArrayOutputStream.write(buffer,0,len);}return byteArrayOutputStream.toByteArray();}/*** 將輸入流轉換成字符串* @param inputStream* @return* @throws IOException*/public static String getStringByInputStream(InputStream inputStream) throws IOException {return new String(getByteArrayByInputStream(inputStream));}/*** 面試題:市面上常用的解析XML的技術有哪些?* DOM* SAX* JDOM* DOM4J* PULL(android 自帶的解析Xml的技術)** @param xml* @return* @throws Exception*/public static List<Person> getPersonsByXmlString(String xml) throws Exception {List<Person> persons=null;/*PULL 基于事件驅動的解析方式*///1.得到Pull解析器對象XmlPullParser xmlPullParser= Xml.newPullParser();//2.設置需要解析的Xml 數據xmlPullParser.setInput(new StringReader(xml));//3.得到事件對象int eventType= xmlPullParser.getEventType();System.out.println("eventType="+eventType);Person person=null;//XmlPullParser.END_DOCUMENT=1while (eventType!=XmlPullParser.END_DOCUMENT){switch (eventType){//XmlPullParser.START_DOCUMENT=0:開始解析Xml時執行,而且只執行一次case XmlPullParser.START_DOCUMENT:persons=new ArrayList<>();System.out.println("==START_DOCUMENT===");break;//XmlPullParser.START_TAG=2:遇到開始標簽時執行case XmlPullParser.START_TAG://xmlPullParser.getName():得到標簽名String startTag=xmlPullParser.getName();if("person".equals(startTag)){person=new Person();//根據索引值得到屬性值,索引值從0開始//String id=xmlPullParser.getAttributeValue(0);//根據屬性名得到屬性值String id=xmlPullParser.getAttributeValue(null,"id");System.out.println("id="+id);}else if("name".equals(startTag)){//得到當前標簽后面的文本內容,同時事件值向后推動了一下String name=xmlPullParser.nextText();person.setName(name);System.out.println("name="+name);}else if("age".equals(startTag)){String age=xmlPullParser.nextText();person.setAge(Integer.parseInt(age));System.out.println("age="+age);}else if("header".equals(startTag)){String header=xmlPullParser.nextText();person.setHeader(header);persons.add(person);System.out.println("header="+header);}System.out.println("===START_TAG="+startTag+"==");break;}//修改事件值eventType=xmlPullParser.next();}System.out.println("persons="+persons);return persons;} }總結
以上是生活随笔為你收集整理的android 之适配器与json对象解析技术的联用的进一步优化(解决图片错位)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 保定哪里有卖奖状纸的?
- 下一篇: android XML解析详解(封装好的