1.创建数据库
package animtest.com.example.e531.database_sample.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by jane on 2018/4/25.
*/
public class MyHelper extends SQLiteOpenHelper {
//确定数据库的名子及版本号
public MyHelper(Context context) {
super(context, "mydatadb", null, 1);
}
//当数据库创建的时候回调
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//创建数据表
sqLiteDatabase.execSQL("create table users (id integer primary key autoincrement,path text,jsondata text)");
}
//版本升级
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
*****************************************************************************
2.数据库的增删改查
package animtest.com.example.e531.database_sample.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* Created by jane on 2018/4/25.
*/
public class UsersDao {
//数据库的帮助类
private MyHelper helper;
public UsersDao(Context context) {
helper=new MyHelper(context);
}
/**
* 插入数据
* @param url url地址
* @param data json数据
*/
public void addData(String url,String data){
//得到一个可读可写的数据库
SQLiteDatabase db = helper.getWritableDatabase();
//先进行删除
db.delete("users"," path=?",new String[]{url});
ContentValues contentValues=new ContentValues();
contentValues.put("path",url);
contentValues.put("jsondata",data);
//进行插入
long rows = db.insert("users", null, contentValues);
Log.d("zzz","addData-rows:"+rows);
}
/**
* 根据指定的url 来查询数据
* @param url
* @return
*/
public String queryData(String url){
String json="";
//得到一个可读可写的数据库
SQLiteDatabase db = helper.getWritableDatabase();
Cursor cursor = db.query("users", null, " path=?", new String[]{url}, null, null, null);
while (cursor.moveToNext()){
json=cursor.getString(cursor.getColumnIndex("jsondata"));
}
Log.d("zzz","---从数据库中获取---"+json);
return json;
}
}
************************************************************
MainActivity
package animtest.com.example.e531.database_sample;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.GridView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import animtest.com.example.e531.database_sample.adapter.GridViewAdapter;
import animtest.com.example.e531.database_sample.bean.DataDataBean;
import animtest.com.example.e531.database_sample.db.UsersDao;
import animtest.com.example.e531.database_sample.utils.NetStateUtil;
import animtest.com.example.e531.database_sample.utils.StreamToString;
/**
* 数据库缓存的思路
*准备工作:创建出sqlite数据库
*
* 第一步:请求数据,判断网络是否连接 ,
* 成功:请求数据显示,将新请求下来的数据存放到数据库中
* 失败:提示用户,根据url从数据库中查询获取数据,显示
*
*/
public class MainActivity extends AppCompatActivity {
//页数
private int pageIndex=1;
//操作类型
private int operType=1;
//请求的url地址
private String url="http://gank.io/api/data/Android/10/"+pageIndex;
//集合数据
private List<DataDataBean.ResultsBean> list=new ArrayList<>();
//适配器
private GridViewAdapter gridViewAdapter;
private PullToRefreshGridView pullToRefreshGridView;
private UsersDao usersDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pullToRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pgv);
//创建数据库的逻辑操作类
usersDao = new UsersDao(MainActivity.this);
//初使化
initPgv();
//请求数据
requestNetData();
}
private void requestNetData() {
//判断有没有网络
if(NetStateUtil.isConn(this)){
//请求网络数据
new MyTask().execute(url);
}else{
Toast.makeText(this,"当前没有网络,请稍后再试!",Toast.LENGTH_SHORT).show();
//从数据库中获取数据
String s = usersDao.queryData(url);
//展示数据
showData(s);
}
}
private void initPgv() {
//1.设置模式
pullToRefreshGridView.setMode(PullToRefreshBase.Mode.BOTH);
//2.设置监听事件
pullToRefreshGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<GridView> pullToRefreshBase) {
//刷新 回调
operType=1;
pageIndex=1;
url="http://gank.io/api/data/Android/10/"+pageIndex;
requestNetData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<GridView> pullToRefreshBase) {
//加载回调
operType=2;
pageIndex++;
url="http://gank.io/api/data/Android/10/"+pageIndex;
requestNetData();
}
});
}
class MyTask extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... strings) {
String str="";
try {
URL url=new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestMethod("GET");
if(urlConnection.getResponseCode()==200){
InputStream inputStream = urlConnection.getInputStream();
str= StreamToString.streamToStr(inputStream,"utf-8");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//将json数据缓存到数据库中
usersDao.addData(url,s);
//展示数据
showData(s);
}
}
private void showData(String s) {
if(!s.equals("")) {
//解析,显示
Gson gson = new Gson();
DataDataBean result = gson.fromJson(s, DataDataBean.class);
//取得列表要显示的数据
List<DataDataBean.ResultsBean> datalists = result.getResults();
if (operType == 1) {
list.clear();//刷新时,清空集合中所有的数据
}
list.addAll(datalists);
setLvAdapter();
}
//关闭头尾视图
pullToRefreshGridView.onRefreshComplete();
}
public void setLvAdapter(){
if(gridViewAdapter==null){
gridViewAdapter=new GridViewAdapter(this,list);
//给包裹的ListView列表设置适配器
pullToRefreshGridView.setAdapter(gridViewAdapter);
}else {
gridViewAdapter.notifyDataSetChanged();
}
}
}