package com.example.fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.example.adapter.adapter;
import com.example.adapter.myadapter;
import com.example.bean.news;
import com.example.mode1.R;
import com.example.mode1.Show;
import com.google.gson.Gson;
import org.apache.http.protocol.HTTP;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
/**
* Created by Dell on 2018/8/5.
*/
public class fragment extends Fragment{
@Nullable
private String spec=”http://www.xieast.com/api/news/news.php?page=1”;
private ListView list_view;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
list_view = view.findViewById(R.id.list_view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
jiexi(spec);
}
private void jiexi(String spec) {
MyAsync myAsync = new MyAsync();
myAsync.execute(spec);//执行
}
//使用异步解析
public class MyAsync extends AsyncTask<String,Integer,String>{
//耗时操作
@Override
protected String doInBackground(String... params) {
//创建一个输入的长度
String spec=params[0];
//创建一个路径
try {
URL url = new URL(spec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
if(connection.getResponseCode()==200){
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while((len=inputStream.read(bytes))!=-1){
bos.write(bytes,0,len);
}
inputStream.close();
bos.close();
//返回数据
String s = bos.toString();
return s;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//更新UI
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Gson gson = new Gson();
news news = gson.fromJson(s, news.class);
final List<com.example.bean.news.DataBean> data = news.getData();
myadapter myadapter = new myadapter(getActivity(),data);
list_view.setAdapter(myadapter);
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getActivity(), Show.class);
intent.putExtra("url",data.get(position).getUrl());
startActivity(intent);
}
});
}
}
}