public class MainActivity extends AppCompatActivity {
private ListView lv;
private List<JsonBean.DataBean> data;
String urlString = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 100) {
String str = (String) msg.obj;
Gson gson = new Gson();
JsonBean jsonBean = gson.fromJson(str, JsonBean.class);
data = jsonBean.getData();
lv.setAdapter(new MyAdapter(MainActivity.this,data));
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = findViewById(R.id.lv);
getIntentDia();
}
private void getIntentDia() {
//切记开启子线程
new Thread() {
@Override
public void run() {
super.run();
String json = Intt.getJson(urlString);
Message message = handler.obtainMessage();
message.obj = json;
message.what = 100;
handler.sendMessage(message);
}
}.start();
}
}
//handler 的上下拉刷新 原代码的基础上改动
public class Fr1 extends Fragment {
private PullToRefreshListView plv;
String urlString = "http://api.tianapi.com/meinv/?key=3304a8bc9414f97e30928b80163cf098&num=";
int page;
private List<JsonBean.NewslistBean> beans;
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==200){
String str = (String) msg.obj;
Gson gson=new Gson();
JsonBean jsonBean = gson.fromJson(str, JsonBean.class);
beans = jsonBean.getNewslist();
MyAdapter ada=new MyAdapter(beans,getActivity());
plv.setAdapter(ada);
plv.onRefreshComplete();
}
}
};
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fr1, null);
plv = view.findViewById(R.id.plv);
plv.setMode(PullToRefreshListView.Mode.BOTH);
getData(page);
plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
beans.clear();
page=0;
getData(page);
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
page++;
getData(page);
}
});
return view;
}
private void getData(int page) {
final String url = urlString+page;
new Thread(){
@Override
public void run() {
super.run();
String json = NetWordUtils.getNetjson(url);
Message message = handler.obtainMessage();
message.obj=json;
message.what=200;
handler.sendMessage(message);
}
}.start();
}
}