MainActivity==============================================================
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();
}
}
}
操作数据库的 帮助类===============================================
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) {
}
}
操作数据库=========================================
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;
}
}
判断网络的Utile类========================================================
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();
}
}
ToString的提取类==========================================================
public class StreamToString {
public static String streamToStr(InputStream inputStream,String chartSet){
StringBuilder builder=new StringBuilder();
try {
BufferedReader br=new BufferedReader(new InputStreamReader(inputStream,chartSet));
String con;
while ((con=br.readLine())!=null){
builder.append(con);
}
br.close();
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}