public class XListViewActivity extends AppCompatActivity {
public static final String TAG = XListViewActivity.class.getSimpleName();
private XListView xListView;
private String api = "http://ttpc.dftoutiao.com/jsonpc/refresh?type=";
private int type = 5010;
private NetUtils_V2 netUtils;
private List<XListViewBean.DataBean> dataBeanList = new ArrayList<>();
private XListViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xlist_view);
xListView = findViewById(R.id.x_list_view);
// 开启刷新
xListView.setPullRefreshEnable(true);
xListView.setPullLoadEnable(true);
// 设置监听回调
xListView.setXListViewListener(new XListView.IXListViewListener() {
@Override
public void onRefresh() {
// 刷新
type = 5010;
netUtils.getDataFromServer(api + type);
}
@Override
public void onLoadMore() {
// loadmore
type++;
netUtils.getDataFromServer(api + type);
}
});
// 设置Adapter 展示数据
adapter = new XListViewAdapter(XListViewActivity.this, dataBeanList);
xListView.setAdapter(adapter);
netUtils = NetUtils_V2.getInstance();
netUtils.setNetCallback(new NetUtils_V2.NetCallback() {
@Override
public void onSuccess(String result) {
Log.i(TAG, "result:" + result);
Gson gson = new Gson();
XListViewBean bean = gson.fromJson(result.replace("null(", "").replace(")", ""), XListViewBean.class);
if (type == 5010) {
dataBeanList.clear();
}
dataBeanList.addAll(bean.getData());
adapter.notifyDataSetChanged();
// 停止刷新和加载
xListView.stopRefresh(true);
xListView.stopLoadMore();
}
});
netUtils.getDataFromServer(api + type);
}
}
//httpUtils
public class NetUtils_V2 {
private static final NetUtils_V2 ourInstance = new NetUtils_V2();
public static NetUtils_V2 getInstance() {
return ourInstance;
}
private NetUtils_V2() {
}
/**
* 从网络获取数据
* 有二中方案
* 1. Thread+HttpUrlConnection/HttpClient+Handler
* 2. AsyncTask+HttpUrlConnection/HttpClient
*/
public void getDataFromServer(String url) {
new LoadData().execute(url);
}
/**
* 接口回调实现过程
* 1. 定义一个接口
* 2. 声明一个引用
* 3. 给引用设值
*/
public interface NetCallback {
void onSuccess(String result);
}
private NetCallback netCallback;
public void setNetCallback(Net Callback netCallback) {
this.netCallback = netCallback;
}
/**
* 请求网络数据的类
*/
class LoadData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... strings) {
// 网络请求
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
return CharStreams.toString(new InputStreamReader(connection.getInputStream(), "UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
if (netCallback != null) {
netCallback.onSuccess(s);
}
}
}
}