public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener {
private XListView xlv;
private MyxLvAdapter adapter;
private boolean bo = false;
private int index = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
xlv.setPullRefreshEnable(true);
xlv.setPullLoadEnable(true);
xlv.setXListViewListener(this);
initData(index);
}
private void initUI() {
xlv = (XListView) findViewById(R.id.xlv);
}
//下拉刷新
@Override
public void onRefresh() {
bo = true;
++index;
initData(index);
xlv.stopRefresh(true);
}
//上拉加载更多
@Override
public void onLoadMore() {
bo = false;
++index;
initData(index);
xlv.stopLoadMore();
}
private void initData(int index) {
new AsyncTask<String, Void, String>() {
private ProgressDialog dialog;
//在异步任务执行的时候 最先执行的方法
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("luluilu加载中");
dialog.show();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
dialog.dismiss();
if (s != null) {
Gson gson = new Gson();
Bean bean = gson.fromJson(s, Bean.class);
List<Bean.ResultBean.DataBean> dataBeanList = bean.getResult().getData();
if (adapter == null) {
adapter = new MyxLvAdapter(MainActivity.this, dataBeanList);
xlv.setAdapter(adapter);
} else {
adapter.addMore(dataBeanList, bo);
adapter.notifyDataSetChanged();
}
}
}
@Override
protected String doInBackground(String... params) {
try {
String path = params[0];
URL url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setConnectTimeout(5000);
if (httpURLConnection.getResponseCode() == 200) {
InputStream is = httpURLConnection.getInputStream();
String json = StreamTool.readNetWork(is);
FileWriter data = new FileWriter(new File(Environment.getExternalStorageDirectory(), "data.json"));
data.write(json);
data.flush();
data.close();
return json;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute("http://apis.juhe.cn/cook/query?key=faecc23d16cbd9bef7ce6043b7d612b3&menu=水煮肉&pn=" + index);
}
}
StreamTool:
/**
* Created by xyn on 2017/4/25.
*/
public class StreamTool {
public static String readNetWork(InputStream inputStream) throws IOException {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while ((len = inputStream.read(bytes)) !=-1){
boas.write(bytes,0,len);
}
return boas.toString();
}
}