读取网络上的json文件
2017-10-13 16:13
211 查看
例:
String path = "http://mnews.gw.com.cn/wap/data/news/news/mobile/jbgg/page_1.json";
这个网络路径对应的是json文件,而不是json字符串
Fragment传过来的分类标识(category)
数据新闻 /xbsjxw
快讯 txs//json格式与其他7个不一样
头条 /toutiao
精编公告 /news/mobile/jbgg
美股 /news/mobile/mgxw
港股 /news/mobile/ggxw
基金 /news/mobile/jjxw
理财 /news/mobile/lcxw
代码如下(展示数据的Fragment):
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
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.Toast;
import com.google.gson.Gson;
import org.json.JSONArray;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import myapplication.monthexamdemo1.DataDataBean;
import myapplication.monthexamdemo1.R;
import myapplication.monthexamdemo1.XListViewAdapter;
import myapplication.monthexamdemo1.xlistview.XListView;
/**
* Created by Administrator on 2017/10/13.
*/
public class DataFragment extends Fragment implements XListView.IXListViewListener {
private XListView xListView;
private String pathBody = "http://mnews.gw.com.cn/wap/data/news";
private int page_num;
private List<DataDataBean.DataBean> list = new ArrayList<>();
private XListViewAdapter adapter;
private String category;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.datafragment_item, container, false);
xListView = view.findViewById(R.id.datafragment_x_list_view);
xListView.setPullRefreshEnable(true);
xListView.setPullLoadEnable(true);
xListView.setXListViewListener(this);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle bundle = getArguments();
category = bundle.getString("category");
page_num = 1;
getDateFromNet(getPath());
}
public String getPath(){
String path = pathBody + category + "/page_" + page_num + ".json";
return path;
}
public void getDateFromNet(final String path){
new AsyncTask<Void, Void, String>(){
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if(responseCode == 200){
InputStream inputStream = connection.getInputStream();
//根据分类标识为不同的数据在sd卡目录下创建文件夹,用来存储不同类别的json文件
File folder = new File(Environment.getExternalStorageDirectory().getPath()+category);
if(!folder.exists()){
folder.
a07a
mkdirs();
}
//根据当前展示的页数来创建一个json文件,因为这个接口对应的是一个json文件,所以我的思路是先把它读到内存中,然后再读成字符串解析
File file = new File(folder, "/" + page_num + ".json");
if(!file.exists()){
file.createNewFile();
BufferedInputStream input = new BufferedInputStream(inputStream);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
byte[] bytes = new byte[1024<<2];
int len = 0;
while((len = input.read(bytes)) != -1){
output.write(bytes, 0, len);
}
input.close();
output.flush();
output.close();
}
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
StringBuffer buffer = new StringBuffer();
String readline = null;
while((readline = bufferedReader.readLine()) != null){
buffer.append(readline);
}
bufferedReader.close();
return buffer.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONArray jsonArray = new JSONArray(s);
Gson gson = new Gson();
DataDataBean dataDataBean = gson.fromJson(jsonArray.getString(0), DataDataBean.class);
List<DataDataBean.DataBean> data = dataDataBean.getData();
list.clear();
list.addAll(data);
setAdapter();
} catch (Exception e) {
e.printStackTrace();
}
}
}.execute();
}
private void setAdapter() {
if(adapter == null){
adapter = new XListViewAdapter(getActivity(), list);
xListView.setAdapter(adapter);
}else{
adapter.notifyDataSetChanged();
}
}
//并不是只有10页,个人给它的一个限制
@Override
public void onRefresh() {
if(page_num < 10){
page_num++;
getDateFromNet(getPath());
}else{
Toast.makeText(getActivity(), "到顶了", Toast.LENGTH_SHORT).show();
}
xListView.stopRefresh();
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
xListView.setRefreshTime(simpleDateFormat.format(date));
}
@Override
public void onLoadMore() {
if(page_num > 1){
page_num--;
getDateFromNet(getPath());
}else{
Toast.makeText(getActivity(), "到底了", Toast.LENGTH_SHORT).show();
}
xListView.stopLoadMore();
}
}
String path = "http://mnews.gw.com.cn/wap/data/news/news/mobile/jbgg/page_1.json";
这个网络路径对应的是json文件,而不是json字符串
Fragment传过来的分类标识(category)
数据新闻 /xbsjxw
快讯 txs//json格式与其他7个不一样
头条 /toutiao
精编公告 /news/mobile/jbgg
美股 /news/mobile/mgxw
港股 /news/mobile/ggxw
基金 /news/mobile/jjxw
理财 /news/mobile/lcxw
代码如下(展示数据的Fragment):
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
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.Toast;
import com.google.gson.Gson;
import org.json.JSONArray;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import myapplication.monthexamdemo1.DataDataBean;
import myapplication.monthexamdemo1.R;
import myapplication.monthexamdemo1.XListViewAdapter;
import myapplication.monthexamdemo1.xlistview.XListView;
/**
* Created by Administrator on 2017/10/13.
*/
public class DataFragment extends Fragment implements XListView.IXListViewListener {
private XListView xListView;
private String pathBody = "http://mnews.gw.com.cn/wap/data/news";
private int page_num;
private List<DataDataBean.DataBean> list = new ArrayList<>();
private XListViewAdapter adapter;
private String category;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.datafragment_item, container, false);
xListView = view.findViewById(R.id.datafragment_x_list_view);
xListView.setPullRefreshEnable(true);
xListView.setPullLoadEnable(true);
xListView.setXListViewListener(this);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle bundle = getArguments();
category = bundle.getString("category");
page_num = 1;
getDateFromNet(getPath());
}
public String getPath(){
String path = pathBody + category + "/page_" + page_num + ".json";
return path;
}
public void getDateFromNet(final String path){
new AsyncTask<Void, Void, String>(){
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if(responseCode == 200){
InputStream inputStream = connection.getInputStream();
//根据分类标识为不同的数据在sd卡目录下创建文件夹,用来存储不同类别的json文件
File folder = new File(Environment.getExternalStorageDirectory().getPath()+category);
if(!folder.exists()){
folder.
a07a
mkdirs();
}
//根据当前展示的页数来创建一个json文件,因为这个接口对应的是一个json文件,所以我的思路是先把它读到内存中,然后再读成字符串解析
File file = new File(folder, "/" + page_num + ".json");
if(!file.exists()){
file.createNewFile();
BufferedInputStream input = new BufferedInputStream(inputStream);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
byte[] bytes = new byte[1024<<2];
int len = 0;
while((len = input.read(bytes)) != -1){
output.write(bytes, 0, len);
}
input.close();
output.flush();
output.close();
}
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
StringBuffer buffer = new StringBuffer();
String readline = null;
while((readline = bufferedReader.readLine()) != null){
buffer.append(readline);
}
bufferedReader.close();
return buffer.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONArray jsonArray = new JSONArray(s);
Gson gson = new Gson();
DataDataBean dataDataBean = gson.fromJson(jsonArray.getString(0), DataDataBean.class);
List<DataDataBean.DataBean> data = dataDataBean.getData();
list.clear();
list.addAll(data);
setAdapter();
} catch (Exception e) {
e.printStackTrace();
}
}
}.execute();
}
private void setAdapter() {
if(adapter == null){
adapter = new XListViewAdapter(getActivity(), list);
xListView.setAdapter(adapter);
}else{
adapter.notifyDataSetChanged();
}
}
//并不是只有10页,个人给它的一个限制
@Override
public void onRefresh() {
if(page_num < 10){
page_num++;
getDateFromNet(getPath());
}else{
Toast.makeText(getActivity(), "到顶了", Toast.LENGTH_SHORT).show();
}
xListView.stopRefresh();
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
xListView.setRefreshTime(simpleDateFormat.format(date));
}
@Override
public void onLoadMore() {
if(page_num > 1){
page_num--;
getDateFromNet(getPath());
}else{
Toast.makeText(getActivity(), "到底了", Toast.LENGTH_SHORT).show();
}
xListView.stopLoadMore();
}
}
相关文章推荐
- python学习笔记十六:读取JSON文件
- 使用nodejs读取简体语言json文件并生成繁体语言json文件
- MFC读取网络共享文件,从根目录开始
- 网络获取Json文件解析范例
- VS无法读取easyui中datagrid组件的json文件问题
- java读取json文件的数据
- iOS 读取本地JSON文件
- 【Java】读取Json配置文件
- 读取本地json文件,转出为指定格式json 使用Base64进行string的加密和解密
- Utils类(获取手机网络状态,读取Json,)
- Flex中读取(嵌入)本地JSON文件
- android 之 读取本地json文件返回string
- iOS Swift读取本地json文件报错的解决方法
- Cocos2d-3.x_读取json文件
- win7如何本地让IIS服务器可以读取json文件
- php读取网络文件curl,fsockopen,file_get_contents,file,fopen几种方法
- 读取Java项目中src/main/resources下的json文件
- Python——保存、读取json文件
- cocos2dx 3.X 中 json 文件生成与读取
- 【C++】JSON文件的读取和生成