赞
踩
这是MainActivity的:
package com.wzq.pulltorefreshdemo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wzq.pulltorefreshdemo.db.JsonDao;
import java.util.ArrayList;
import java.util.List;
/**
* 接入PullToRefresh
* 1.引入Library
* 2.依赖model
* 3. 布局文件中使用可刷新的控件
* 4. 设置可刷新监听--> mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>()
* 设置可以上拉 mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
*/
public class MainActivity extends AppCompatActivity {
String baseUrl = "http://www.93.gov.cn/93app/data.do?channelId=0&startNum=";
private ArrayList<String> list = new ArrayList();
private PullToRefreshListView plv;
private int page = 0;
private ArrayAdapter<String> mAdapter;
private JsonDao jsonDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find
plv = (PullToRefreshListView) findViewById(R.id.plv);
plv.setMode(PullToRefreshBase.Mode.BOTH);//上下拉都支持;
// 设置adapter
mAdapter = new ArrayAdapter<>(MainActivity.this,
android.R.layout.simple_list_item_1, list);
plv.setAdapter(mAdapter);
//构造数据流dao层
jsonDao = new JsonDao(this);
//请求网络
getNetData(0);
//处理上拉和下拉的操作;
plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
// 下拉刷新
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
list.clear();
getNetData(0);
}
//上拉加载
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
page++;
getNetData(page);
}
});
}
private void getNetData(int page) {
String mUrl = baseUrl+page;
if(NetStateUtil.isConn(this)){ //这个是网络获取的逻辑
new MAsyncTask().execute(mUrl);
}else { //这个是数据库获取的逻辑
Toast.makeText(this,"当前没有网络,请稍后重试!",Toast.LENGTH_SHORT).show();
//从数据库中查询
String s = jsonDao.queryData(mUrl);
if(!s.isEmpty()){
Log.d("wzq","--------从数据库中取得数据------------");
//解析,显示
Gson gson = new Gson();
Product product = gson.fromJson(s, Product.class);
List<Product.DataBean> dataTemp = product.getData();
ArrayList<String> stringList = new ArrayList<>();//初始化一个空的字符串集合
for (int i = 0; i <dataTemp.size() ; i++) {
stringList.add(dataTemp.get(i).getTITLE());
}
list.addAll(stringList);
mAdapter.notifyDataSetChanged();
plv.onRefreshComplete(); // 让刷新头和刷新底部返回
}
}
}
class MAsyncTask extends AsyncTask<String,Void,String> {
String mUrl = "";
@Override
protected String doInBackground(String... strings) {
mUrl = strings[0];
return NetWordUtils.getNetjson(strings[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//调用插入方法
jsonDao.insertData(mUrl,s);
Gson gson = new Gson();
Product product = gson.fromJson(s, Product.class);
List<Product.DataBean> dataTemp = product.getData();
ArrayList<String> stringList = new ArrayList<>();//初始化一个空的字符串集合
for (int i = 0; i <dataTemp.size() ; i++) {
stringList.add(dataTemp.get(i).getTITLE());
}
list.addAll(stringList);
mAdapter.notifyDataSetChanged();
plv.onRefreshComplete(); // 让刷新头和刷新底部返回
}
}
}
这是NetWordUtils的:
package com.wzq.pulltorefreshdemo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* author:Created by WangZhiQiang on 2017-09-27.
*/
public class NetWordUtils {
private static String tag = "NetWordUtils";
/**
* 获取网络json
*
* @param urlString
* @return
*/
public static String getNetjson(String urlString) {
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");//若果是get请求可以不用配置; 其他请求必须配置
urlConnection.setConnectTimeout(8000);//设置链接超时间
InputStream inputStream = urlConnection.getInputStream();//获取网络返回的输入流;
//可拼接的字符串
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp = "";
while ((temp = bufferedReader.readLine()) != null) {
stringBuilder.append(temp);
temp = "";
}
//这个是网络获取的数据
String data = stringBuilder.toString();
Log.e(tag, "getData: " + data);
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取网络图片的工具类
*
* @param urlString
* @return
*/
public static Bitmap getNetBitmap(String urlString) {
try {
//用URL封装链接地址;
URL url = new URL(urlString);
//用url打开链接
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//联网的状态码
int responseCode = urlConnection.getResponseCode();
if(responseCode ==200){
//链接上获取输入流
InputStream inputStream = urlConnection.getInputStream();
//把流直接转换成bitmap(系统提供的BitmapFactory)
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);//BitmapFactory是个工具类,系统提供的
return bitmap;
}else {
Log.e(tag, "网络状态码:: "+responseCode );
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
这是NetStateUtil的:
package com.wzq.pulltorefreshdemo;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetStateUtil {
/*
* 判断网络连接是否已开
* true 已打开 false 未打开
* */
public static boolean isConn(Context context){
boolean bisConnFlag=false;
ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = conManager.getActiveNetworkInfo();
if(network!=null){
bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();
}
return bisConnFlag;
}
/**
* 当判断当前手机没有网络时选择是否打开网络设置
* @param context
*/
public static void showNoNetWorkDlg(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.mipmap.ic_launcher) //
.setTitle(R.string.app_name) //
.setMessage("当前无网络").setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到系统的网络设置界面
Intent intent = null;
// 先判断当前系统版本
if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
}
context.startActivity(intent);
}
}).setNegativeButton("知道了", null).show();
}
}
这是JsonDao的:
package com.wzq.pulltorefreshdemo.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class JsonDao {
private MyHelper helper;
public JsonDao(Context context) {
helper=new MyHelper(context);
}
//插入数据
public void insertData(String url,String jsonstr){
SQLiteDatabase db=helper.getWritableDatabase();
//先删除,再插入
db.delete("jsontable","url=?",new String[]{jsonstr});
ContentValues values=new ContentValues();
values.put("url",url);
values.put("json",jsonstr);
long rowid = db.insert("jsontable", null, values);
Log.d("zzz","insert-----rowid:"+rowid);
}
/**
* 查询数据
* @param url
* @return
*/
public String queryData(String url){
String json="";
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.query("jsontable", null, "url=?", new String[]{url}, null, null, null);
while (cursor.moveToNext()){
json = cursor.getString(cursor.getColumnIndex("json"));
}
return json;
}
}
这是MyHelper的
package com.wzq.pulltorefreshdemo.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class MyHelper extends SQLiteOpenHelper {
public MyHelper(Context context) {
super(context, "dbcache", null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//创建数据表
sqLiteDatabase.execSQL("create table jsontable (id integer primary key autoincrement,url text not null,json text not null)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。