package cn.zhaoliang5156.consultation1604k.activity;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import cn.zhaoliang5156.consultation1604k.R;
import cn.zhaoliang5156.consultation1604k.adapter.ImageListAdapter;
import cn.zhaoliang5156.consultation1604k.bean.ListBean;
/**
* 图片列表Activity
* 需求:
* 1. 请求https://www.apiopen.top/meituApi?page=1 获取内容
* 2. 使用Gson 解析数据
* 3. 使用ListView展示数据
* 4. 有化ListView
*/
public class ImageListActivity extends AppCompatActivity {
public static final String TAG = ImageListActivity.class.getSimpleName();
private ListView imageList;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 把数据放在列表中展示
List<ListBean.DataBean> data = (List<ListBean.DataBean>) msg.obj;
Log.i(TAG, "data:" + data.size());
imageList.setAdapter(new ImageListAdapter(ImageListActivity.this, data));
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_list);
imageList = findViewById(R.id.image_list);
getDataFromServer();
}
/**
* 从服务器获取数据
*/
private void getDataFromServer() {
// 1. 开启一个子线程
new Thread() {
@Override
public void run() {
// 2. 创建一个Url
try {
URL url = new URL("https://www.apiopen.top/meituApi?page=1");
// 3. 获取一个HTTPURLConnection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 4. 设置连接和读取超时
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 5. 判断响应吗如果是200响应成功
if (connection.getResponseCode() == 200) {
// 6. 响应成功后解析数据, 把流转换成字符串
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len = -1;
byte[] b = new byte[1024];
while ((len = inputStream.read(b)) != -1) {
outputStream.write(b, 0, len);
}
String result = new String(outputStream.toByteArray());
// result 是一个json 我们需要使用Gson解析json
Gson gson = new Gson();
ListBean listBean = gson.fromJson(result, ListBean.class);
List<ListBean.DataBean> data = listBean.getData();
// 创建消息发送数据
Message message = Message.obtain();
message.what = 1;
message.obj = data;
mHandler.sendMessage(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}