MainActivity主
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list);
getData();
}
//获取数据
//网络请求一般要在子线程跑
public String getData(){
new Thread(new Runnable() {
@Override
public void run() {
请求一个字符串
try {
String path =("https://suggest.taobao.com/sug?code=utf-8&q=%E6%89%8B%E6%9C%BA");
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//请求方式
conn.setRequestMethod("GET");
//设置连接超时间和读取超时时间
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
//设置请求码
final int code = conn.getResponseCode();
//如果请求成功
if(code==200){
InputStream inputStream = conn.getInputStream();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = inputStream.read(buf))!=-1){
baos.write(buf,0,len);
baos.flush();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
String string = baos.toString();
Gson gson = new Gson();
DataBean date = gson.fromJson(string, DataBean.class);
List<List<String>> result = date.getResult();
//适配
MAdapter mAdapter = new MAdapter(result, MainActivity.this);
listView.setAdapter(mAdapter);
}
});
}
} catch (Exception e)
{ e.printStackTrace(); }
}
}).start();
return null;
}
}
MAdapter适配
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
class MAdapter extends BaseAdapter {
private List<List<String>> list;
private Context mContext;
public MAdapter(List<List<String>> list, Context mContext) {
this.list = list;
this.mContext = mContext;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MHolder holder;
if (convertView == null){
convertView = View.inflate(mContext, R.layout.list, null);
holder = new MHolder();
holder.text = convertView.findViewById(R.id.text);
convertView.setTag(holder);
}else {
holder = (MHolder) convertView.getTag();
}
holder.text.setText(list.get(position).get(0));
return convertView;
}
class MHolder{
TextView text;
}
}