package com.example.weixin;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.example.weixin.Weixin.Details;
import com.google.gson.Gson;
public class Fragment2 extends Fragment {
protected static final String TAG = “Fragment2”;
private View view;
private ListView listView;
private int positon = 0;
private String path;
private String result;
Handler handler = new Handler() {
@SuppressLint(“NewApi”)
public void handleMessage(android.os.Message msg) {
Log.i(TAG, "result...." + result.length());
Bitmap bitmap = (Bitmap) msg.obj;
// 拿到bitmap怎么使用
Bundle data = msg.getData();
// 获取tag imageView身上的标记
String tag = data.getString("tag", null);
// 在listView上根据tag查找控件
ImageView imageView = (ImageView) listView.findViewWithTag(tag);
if (bitmap != null && imageView != null) {
imageView.setImageBitmap(bitmap);
}
};
};
private ArrayList<Details> weixinList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.f2_item, container, false);
listView = (ListView) view.findViewById(R.id.f2_listView);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// 这里定义一个集合,用来放加载的数据
weixinList = new ArrayList<Details>();
path = "http://v.juhe.cn/weixin/query";
// 加载数据
loadData();
// 设置滑动监听
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// 判断一下当前的最后一个条目是不是集合的长度减一
int lastVisiblePosition = view.getLastVisiblePosition();
if (lastVisiblePosition == weixinList.size() - 1) {
// 加载数据,就是再执行一次异步任务
// 将页面++
positon++;
// 再次加载数据
loadData();
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
}
/**
* 加载数据,开启异步任务
*/
private void loadData() {
MyAsynTask asynTask = new MyAsynTask();
asynTask.execute();
}
private MyAdapter myAdapter;
class MyAsynTask extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
// 展示一个进度条
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle("人家正在努力加载");
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
try {
// 实例化客户端对象
HttpClient httpClient = new DefaultHttpClient();
// 定义一个post
HttpPost httpPost = new HttpPost(path);
// 如果你不知道如何测试post请求到底通没通
// 你需要自己拼串测试
// http://v.juhe.cn/weixin/query?key=0917c812f187b92e025c9b7c2d4e59b5&pno=2
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("key",
"0917c812f187b92e025c9b7c2d4e59b5"));
parameters
.add(new BasicNameValuePair("pno", (positon + 1) + ""));
HttpEntity entity = new UrlEncodedFormEntity(parameters);
httpPost.setEntity(entity);
// 执行post请求
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
InputStream inputStream = httpResponse.getEntity()
.getContent();
String streamToStr = streamToStr(inputStream);
return streamToStr;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Fragment2.this.result = result;
// 解析字符串
Gson gson = new Gson();
// json
Weixin fromJson = gson.fromJson(result, Weixin.class);
// 每次数据加载上来,都获取要展示的那个集合
ArrayList<Details> list = fromJson.result.list;
// 添加所有的数据
weixinList.addAll(list);
// 消失进度条
progressDialog.dismiss();
// 第一次的时候,adapter是null,创建,设置数据适配器
if (myAdapter == null) {
myAdapter = new MyAdapter();
listView.setAdapter(myAdapter);
} else {
// 之后每一次都刷新数据
myAdapter.notifyDataSetChanged();
}
}
}
/**
* 流转串
*
* @param inputStream
* @return
*/
public static String streamToStr(InputStream inputStream) {
try {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buffer)) != -1) {
arrayOutputStream.write(buffer, 0, len);
}
return arrayOutputStream.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return weixinList.size();
}
@Override
public Object getItem(int position) {
return weixinList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = View.inflate(getActivity(), R.layout.lv_item,
null);
viewHolder = new ViewHolder();
convertView.setTag(viewHolder);
viewHolder.lv_imageView = (ImageView) convertView
.findViewById(R.id.lv_imageView);
viewHolder.lv_textView = (TextView) convertView
.findViewById(R.id.lv_textView);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.lv_textView.setText(weixinList.get(position).title);
// bitmapUtils展示图片
// ----------------------------------------------------
// BitmapUtils bitmapUtils = new BitmapUtils(getActivity());
// String url = list.get(position).firstImg;
// if(TextUtils.isEmpty(url)){
// viewHolder.lv_imageView.setImageResource(R.drawable.ic_launcher);
// }else{
// url = url.substring(0, url.lastIndexOf("/"));
// // 正常的url
// url = Images.imageThumbUrls[position];
// bitmapUtils.display(viewHolder.lv_imageView, url);
// }
// ---------------------------------------------------------
// final String url = Images.imageThumbUrls[position];
final String firstImg = weixinList.get(position).firstImg;
if (TextUtils.isEmpty(firstImg)) {
viewHolder.lv_imageView
.setImageResource(R.drawable.ic_launcher);
} else {
// 给imageView设置tag 设置标记
viewHolder.lv_imageView.setTag(firstImg);
new Thread() {
public void run() {
getBitmap(firstImg);
};
}.start();
}
return convertView;
}
class ViewHolder {
ImageView lv_imageView;
TextView lv_textView;
}
}
/**
* 根据路径获取图片
*
* @param path
*/
public void getBitmap(String path) {
try {
URL url = new URL(path);
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
openConnection.setConnectTimeout(5000);
openConnection.setReadTimeout(5000);
int responseCode = openConnection.getResponseCode();
if (responseCode == 200) {
InputStream inputStream = openConnection.getInputStream();
Bitmap decodeStream = BitmapFactory.decodeStream(inputStream);
Message obtain = Message.obtain();
obtain.what = 1;
// 将imageView身上绑的tag传递给handler
Bundle data = new Bundle();
data.putString("tag", path);
obtain.setData(data);
obtain.obj = decodeStream;
handler.sendMessage(obtain);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}