一,首先确定布局和基本权限
二,当开始在主Activity中开始写代码的时候,首先找所需的控件,然后思考本Activity需不需要开启子线程.
三,书写子线程代码
示例工程
activity_main.xml
xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mi.MainActivity">
android:id="@+id/plv"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
items.xml
xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/img"
android:layout_width="100dp"
android:layout_height="100dp" />
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
MainActivity.java
package com.example.mi;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import com.example.mi.bean.DateBean;
import com.example.mi.utils.JsonDao;
import com.example.mi.utils.NetStateUtil;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.LoadingLayoutProxy;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private PullToRefreshListView plv;
private int oderType = 1;
private int pageIndex = 1;
private List dataAll=new ArrayList <>();
private MyAdapter adapter;
private String url="https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page="+pageIndex;
private JsonDao jsonDao = new JsonDao(this);
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
List list = (List )msg.obj;
showData(list);
}
};
private void showData(List list) {
if (oderType==1)
{
dataAll.clear();
}
dataAll.addAll(list);
setPlvAdapter();
plv.onRefreshComplete();
}
private void setPlvAdapter() {
if (adapter==null)
{
adapter=new MyAdapter(MainActivity.this,dataAll);
plv.setAdapter(adapter);
}else {
adapter.notifyDataSetChanged();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
plv = findViewById(R.id.plv);
initPlv();
requestNetData();
}
private void requestNetData() {
//判断网络是否连接
if (NetStateUtil.isConn(this)){
openThread();
}else {
NetStateUtil.showNoNetWorkDlg(this);
//吐司提示
Toast.makeText(this,"现在没有网络,请稍后重试!",Toast.LENGTH_SHORT).show();
//展示本地数据
String s = jsonDao.select(url);
Gson gson = new Gson();
showData(gson.fromJson(s,DateBean.class).getNewslist());
}
}
public void openThread(){
new Thread(){
@Override
public void run() {
try {
URL url1=new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection)url1.openConnection();
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestMethod("GET");
if (urlConnection.getResponseCode()==200)
{
InputStream inputStream = urlConnection.getInputStream();
String s = streamToString(inputStream);
jsonDao.insertData(url,s);
Gson gson = new Gson();
DateBean dateBean = gson.fromJson(s, DateBean.class);
List newslist = dateBean.getNewslist();
Message mes = Message.obtain();
mes.obj=newslist;
handler.sendMessage(mes);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
private String streamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
String str;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
try {
while ((str=bufferedReader.readLine())!=null)
{
stringBuilder.append(str);
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private void initPlv() {
plv.setMode(PullToRefreshBase.Mode.BOTH);
//设置下拉提示文字
LoadingLayoutProxy layoutProxy = (LoadingLayoutProxy) plv.getLoadingLayoutProxy(true, false);
//下拉的时候显示的文本
layoutProxy.setPullLabel("继续拉,对,继续,拉,拉,拉");
//放开刷新的时候显示的文本
layoutProxy.setReleaseLabel("松开你就会发现一件神奇的事情");
//执行刷新的时候显示的文本
layoutProxy.setRefreshingLabel("哈哈哈哈哈,神奇不?");
//设置上拉提示文字
LoadingLayoutProxy layoutProxy1 = (LoadingLayoutProxy) plv.getLoadingLayoutProxy(false, true);
//上拉的时候显示的文本
layoutProxy1.setPullLabel("继续上拉,加载更多~");
//放开刷新的时候显示的文本
layoutProxy1.setReleaseLabel("松开加载");
//执行刷新的时候显示的文本
layoutProxy1.setRefreshingLabel("正在加载...");
plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2 () {
@Override
public void onPullDownToRefresh(PullToRefreshBase pullToRefreshBase) {
oderType=1;
pageIndex=1;
url="https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page="+pageIndex;
requestNetData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase pullToRefreshBase) {
oderType=2;
pageIndex++;
url="https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page="+pageIndex;
requestNetData();
}
});
}
}
package com.example.mi;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Adapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.mi.bean.DateBean;
import com.example.mi.utils.JsonDao;
import com.example.mi.utils.NetStateUtil;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private PullToRefreshListView plv;
private int oderType = 1;
private int pageIndex = 1;
private List dataAll=new ArrayList <>();
private MyAdapter adapter;
private String url="https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page="+pageIndex;
private JsonDao jsonDao = new JsonDao(this);
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
List list = (List )msg.obj;
showData(list);
}
};
private void showData(List list) {
if (oderType==1)
{
dataAll.clear();
}
dataAll.addAll(list);
setPlvAdapter();
plv.onRefreshComplete();
}
private void setPlvAdapter() {
if (adapter==null)
{
adapter=new MyAdapter(MainActivity.this,dataAll);
plv.setAdapter(adapter);
}else {
adapter.notifyDataSetChanged();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
plv = findViewById(R.id.plv);
initPlv();
requestNetData();
}
private void requestNetData() {
//判断网络是否连接
if (NetStateUtil.isConn(this)){
openThread();
}else {
NetStateUtil.showNoNetWorkDlg(this);
//吐司提示
Toast.makeText(this,"现在没有网络,请稍后重试!",Toast.LENGTH_SHORT).show();
//展示本地数据
String s = jsonDao.select(url);
Gson gson = new Gson();
showData(gson.fromJson(s,DateBean.class).getNewslist());
}
}
public void openThread(){
new Thread(){
@Override
public void run() {
try {
URL url1=new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection)url1.openConnection();
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestMethod("GET");
if (urlConnection.getResponseCode()==200)
{
InputStream inputStream = urlConnection.getInputStream();
String s = streamToString(inputStream);
jsonDao.insertData(url,s);
Gson gson = new Gson();
DateBean dateBean = gson.fromJson(s, DateBean.class);
List newslist = dateBean.getNewslist();
Message mes = Message.obtain();
mes.obj=newslist;
handler.sendMessage(mes);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
private String streamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
String str;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
try {
while ((str=bufferedReader.readLine())!=null)
{
stringBuilder.append(str);
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
private void initPlv() {
plv.setMode(PullToRefreshBase.Mode.BOTH);
plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2 () {
@Override
public void onPullDownToRefresh(PullToRefreshBase pullToRefreshBase) {
oderType=1;
pageIndex=1;
url="https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page="+pageIndex;
requestNetData();
}
@Override
public void onPullUpToRefresh(PullToRefreshBase pullToRefreshBase) {
oderType=2;
pageIndex++;
url="https://api.tianapi.com/wxnew/?key=48a7d7193e11bd2dd4a683b6e2f90a4f&num=10&page="+pageIndex;
requestNetData();
}
});
}
}
MyAdapter.java
package com.example.mi;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mi.bean.DateBean;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import java.util.List;
/**
* Created by Administrator on 2018/3/31.
*/
public class MyAdapter extends BaseAdapter {
private Context context;
private List list;
private DisplayImageOptions options;
public MyAdapter(Context context, List list) {
this.context = context;
this.list = list;
options=new DisplayImageOptions.Builder()
.cacheInMemory(true)//使用内存缓存
.cacheOnDisk(true)//使用磁盘缓存
.showImageOnLoading(R.mipmap.ic_launcher_round)//设置正在下载的图片
.showImageForEmptyUri(R.mipmap.ic_launcher_round)//url为空或请求的资源不存在时
.showImageOnFail(R.mipmap.ic_launcher_round)//下载失败时显示的图片
.bitmapConfig(Bitmap.Config.RGB_565)//设置图片色彩模式
.imageScaleType(ImageScaleType.EXACTLY)//设置图片的缩放模式
.build();
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view==null)
{
view=View.inflate(context,R.layout.items,null);
viewHolder=new ViewHolder();
viewHolder.img = view.findViewById(R.id.img);
viewHolder.txt = view.findViewById(R.id.txt);
view.setTag(viewHolder);
}else {
viewHolder=(ViewHolder)view.getTag();
}
ImageLoader.getInstance().displayImage(list.get(i).getPicUrl(),viewHolder.img,options);
viewHolder.txt.setText(list.get(i).getTitle());
return view;
}
class ViewHolder{
ImageView img;
TextView txt;
}
}
package com.example.mi;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mi.bean.DateBean;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import java.util.List;
/**
* Created by Administrator on 2018/3/31.
*/
public class MyAdapter extends BaseAdapter {
private Context context;
private List list;
private DisplayImageOptions options;
public MyAdapter(Context context, List list) {
this.context = context;
this.list = list;
options=new DisplayImageOptions.Builder()
.cacheInMemory(true)//使用内存缓存
.cacheOnDisk(true)//使用磁盘缓存
.showImageOnLoading(R.mipmap.ic_launcher_round)//设置正在下载的图片
.showImageForEmptyUri(R.mipmap.ic_launcher_round)//url为空或请求的资源不存在时
.showImageOnFail(R.mipmap.ic_launcher_round)//下载失败时显示的图片
.bitmapConfig(Bitmap.Config.RGB_565)//设置图片色彩模式
.imageScaleType(ImageScaleType.EXACTLY)//设置图片的缩放模式
.build();
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if (view==null)
{
view=View.inflate(context,R.layout.items,null);
viewHolder=new ViewHolder();
viewHolder.img = view.findViewById(R.id.img);
viewHolder.txt = view.findViewById(R.id.txt);
view.setTag(viewHolder);
}else {
viewHolder=(ViewHolder)view.getTag();
}
ImageLoader.getInstance().displayImage(list.get(i).getPicUrl(),viewHolder.img,options);
viewHolder.txt.setText(list.get(i).getTitle());
return view;
}
class ViewHolder{
ImageView img;
TextView txt;
}
}
MyApplication.java
package com.example.mi;
import android.app.Application;
import android.os.Environment;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.io.File;
/**
* Created by Administrator on 2018/3/31.
*/
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//程序的入口 函数
//自定义缓存路径 sd卡下的piccache文件夹下
File cachefile=new File(Environment.getExternalStorageDirectory().getPath()+"/piccache");
//File cachefile1=getExternalCacheDir();//获取系统默认的sd卡缓存路径
ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this)
.memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽
.threadPoolSize(2)//线程池的数量
.threadPriority(4)
.memoryCacheSize(2*1024*1024)//设置内存缓存区大小
.diskCacheSize(20*1024*1024)//设置sd卡缓存区大小
.diskCache(new UnlimitedDiscCache(cachefile))//自定义缓存目录
.writeDebugLogs()//打印日志内容
.diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理
.build();
ImageLoader.getInstance().init(configuration);
}
}
package com.example.mi; import android.app.Application; import android.os.Environment; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import java.io.File; /** * Created by Administrator on 2018/3/31. */ public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); //程序的入口 函数 //自定义缓存路径 sd卡下的piccache文件夹下 File cachefile=new File(Environment.getExternalStorageDirectory().getPath()+"/piccache"); //File cachefile1=getExternalCacheDir();//获取系统默认的sd卡缓存路径 ImageLoaderConfiguration configuration=new ImageLoaderConfiguration.Builder(this) .memoryCacheExtraOptions(480, 800)//缓存图片最大的长和宽 .threadPoolSize(2)//线程池的数量 .threadPriority(4) .memoryCacheSize(2*1024*1024)//设置内存缓存区大小 .diskCacheSize(20*1024*1024)//设置sd卡缓存区大小 .diskCache(new UnlimitedDiscCache(cachefile))//自定义缓存目录 .writeDebugLogs()//打印日志内容 .diskCacheFileNameGenerator(new Md5FileNameGenerator())//给缓存的文件名进行md5加密处理 .build(); ImageLoader.getInstance().init(configuration); } }
DataBean.java
package com.example.mi.bean;
import java.util.List;
/**
* Created by Administrator on 2018/3/31.
*/
public class DateBean {
/**
* code : 200
* msg : success
* newslist : [{"ctime":"2018-03-30","title":"关于红楼梦的N个念头","description":"三联生活周刊","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900671.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MTc5MTU3NTYyMQ==&idx=2&mid=2650651785&sn=75526e17b4b480ea510f65ec3793bf54"},{"ctime":"2018-03-30","title":"广州有座\u201c猪宾馆\u201d,里面的猪会\u201c尬舞\u201d?这是世界首例!","description":"广州日报","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-45262906.static/640","url":"https://mp.weixin.qq.com/s?__biz=MjM5MjA0MDk2MA==&idx=2&mid=2652421905&sn=0ae22141145b30c848ecf0a0ac612153"},{"ctime":"2018-03-30","title":"\u201c你不就是个服务员吗?凭什么不让我换头等舱?\u201d","description":"暴走大事件","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900613.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MzI4ODA1MDA2MQ==&idx=1&mid=2652647217&sn=efaa395be06b18c55b3e48a03c4a8677"},{"ctime":"2018-03-30","title":"左眼跳财,右眼跳灾?女子左眼皮连跳8年,终于出事了...","description":"FM93交通之声","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900601.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MTIzNDg3NzY2MA==&idx=3&mid=2653040765&sn=cafb01cf0ebcbd673ee4c4637764f0f2"},{"ctime":"2018-03-30","title":"千万别着急!又一大波重磅新车将上市,买早了吃亏!","description":"有车以后","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900573.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MzAxMTA0ODE3Mw==&idx=1&mid=2656904565&sn=5a75df7049ca08181ecaf18476e1f370"},{"ctime":"2018-03-30","title":"2.0T+9AT的大7座SUV,卖多少钱能让你放弃汉兰达/奥迪Q5?","description":"车买买","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62898269.static/640","url":"https://mp.weixin.qq.com/s?__biz=MzA5NTU1MjEwNA==&idx=4&mid=2668673664&sn=197feccde9aad5f1c47772235c541e3e"},{"ctime":"2018-03-30","title":"黑人的头发养活了中国的一座城,这里藏着一段屈辱的民族史","description":"微在Wezeit","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900480.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MzA5MjMzNTQyNw==&idx=1&mid=2656030884&sn=9a79b276f2c66c9b2694427d19ee5c72"},{"ctime":"2018-03-30","title":"朋友养了一只猛犬,网友本来是不相信的,直到靠近狗窝后.....","description":"大爱萌狗控","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900520.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MjM5NjQ0MDE1OQ==&idx=2&mid=2650063440&sn=42593507b8b2f992795fb8ed6c675a5a"},{"ctime":"2018-03-30","title":"中国最美的20个旅行目的地,走过10个以上,就算超级旅行达人。","description":"带着相机去旅行","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900363.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MzAxNjI1MzUwOA==&idx=3&mid=2247521649&sn=9c9c6d637348d975baa2c4352039f286"},{"ctime":"2018-03-30","title":"【入流】网红食物打造指南","description":"腾讯时尚","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-61887411.static/640","url":"https://mp.weixin.qq.com/s?__biz=MjM5MTIxOTEyMA==&idx=2&mid=2650591720&sn=e7e246e4bdf3c2659fd26f36b88697fa"}]
*/
private int code;
private String msg;
private List newslist;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List getNewslist() {
return newslist;
}
public void setNewslist(List newslist) {
this.newslist = newslist;
}
public static class NewslistBean {
/**
* ctime : 2018-03-30
* title : 关于红楼梦的N个念头
* description : 三联生活周刊
* picUrl : https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900671.jpg/640
* url : https://mp.weixin.qq.com/s?__biz=MTc5MTU3NTYyMQ==&idx=2&mid=2650651785&sn=75526e17b4b480ea510f65ec3793bf54
*/
private String ctime;
private String title;
private String description;
private String picUrl;
private String url;
public String getCtime() {
return ctime;
}
public void setCtime(String ctime) {
this.ctime = ctime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
package com.example.mi.bean; import java.util.List; /** * Created by Administrator on 2018/3/31. */ public class DateBean { /** * code : 200 * msg : success * newslist : [{"ctime":"2018-03-30","title":"关于红楼梦的N个念头","description":"三联生活周刊","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900671.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MTc5MTU3NTYyMQ==&idx=2&mid=2650651785&sn=75526e17b4b480ea510f65ec3793bf54"},{"ctime":"2018-03-30","title":"广州有座\u201c猪宾馆\u201d,里面的猪会\u201c尬舞\u201d?这是世界首例!","description":"广州日报","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-45262906.static/640","url":"https://mp.weixin.qq.com/s?__biz=MjM5MjA0MDk2MA==&idx=2&mid=2652421905&sn=0ae22141145b30c848ecf0a0ac612153"},{"ctime":"2018-03-30","title":"\u201c你不就是个服务员吗?凭什么不让我换头等舱?\u201d","description":"暴走大事件","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900613.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MzI4ODA1MDA2MQ==&idx=1&mid=2652647217&sn=efaa395be06b18c55b3e48a03c4a8677"},{"ctime":"2018-03-30","title":"左眼跳财,右眼跳灾?女子左眼皮连跳8年,终于出事了...","description":"FM93交通之声","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900601.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MTIzNDg3NzY2MA==&idx=3&mid=2653040765&sn=cafb01cf0ebcbd673ee4c4637764f0f2"},{"ctime":"2018-03-30","title":"千万别着急!又一大波重磅新车将上市,买早了吃亏!","description":"有车以后","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900573.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MzAxMTA0ODE3Mw==&idx=1&mid=2656904565&sn=5a75df7049ca08181ecaf18476e1f370"},{"ctime":"2018-03-30","title":"2.0T+9AT的大7座SUV,卖多少钱能让你放弃汉兰达/奥迪Q5?","description":"车买买","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62898269.static/640","url":"https://mp.weixin.qq.com/s?__biz=MzA5NTU1MjEwNA==&idx=4&mid=2668673664&sn=197feccde9aad5f1c47772235c541e3e"},{"ctime":"2018-03-30","title":"黑人的头发养活了中国的一座城,这里藏着一段屈辱的民族史","description":"微在Wezeit","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900480.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MzA5MjMzNTQyNw==&idx=1&mid=2656030884&sn=9a79b276f2c66c9b2694427d19ee5c72"},{"ctime":"2018-03-30","title":"朋友养了一只猛犬,网友本来是不相信的,直到靠近狗窝后.....","description":"大爱萌狗控","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900520.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MjM5NjQ0MDE1OQ==&idx=2&mid=2650063440&sn=42593507b8b2f992795fb8ed6c675a5a"},{"ctime":"2018-03-30","title":"中国最美的20个旅行目的地,走过10个以上,就算超级旅行达人。","description":"带着相机去旅行","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900363.jpg/640","url":"https://mp.weixin.qq.com/s?__biz=MzAxNjI1MzUwOA==&idx=3&mid=2247521649&sn=9c9c6d637348d975baa2c4352039f286"},{"ctime":"2018-03-30","title":"【入流】网红食物打造指南","description":"腾讯时尚","picUrl":"https://zxpic.gtimg.com/infonew/0/wechat_pics_-61887411.static/640","url":"https://mp.weixin.qq.com/s?__biz=MjM5MTIxOTEyMA==&idx=2&mid=2650591720&sn=e7e246e4bdf3c2659fd26f36b88697fa"}] */ private int code; private String msg; private Listnewslist; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public List getNewslist() { return newslist; } public void setNewslist(List newslist) { this.newslist = newslist; } public static class NewslistBean { /** * ctime : 2018-03-30 * title : 关于红楼梦的N个念头 * description : 三联生活周刊 * picUrl : https://zxpic.gtimg.com/infonew/0/wechat_pics_-62900671.jpg/640 * url : https://mp.weixin.qq.com/s?__biz=MTc5MTU3NTYyMQ==&idx=2&mid=2650651785&sn=75526e17b4b480ea510f65ec3793bf54 */ private String ctime; private String title; private String description; private String picUrl; private String url; public String getCtime() { return ctime; } public void setCtime(String ctime) { this.ctime = ctime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } }
MyDatabaseHelper.java
package com.example.mi.dateBase;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Administrator on 2018/4/1.
*/
public class MyDatebaseHelper extends SQLiteOpenHelper {
//构造方法,用于确定数据库的名称,版本号等
public MyDatebaseHelper(Context context) {
super(context, "mydb",null,1);
}
//创建数据库时调用一次,初始化表中数据
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table users(id integer primary key autoincrement,urlPath text,jsonData text)");
}
//数据库版本更新时回调
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
package com.example.mi.dateBase; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Administrator on 2018/4/1. */ public class MyDatebaseHelper extends SQLiteOpenHelper { //构造方法,用于确定数据库的名称,版本号等 public MyDatebaseHelper(Context context) { super(context, "mydb",null,1); } //创建数据库时调用一次,初始化表中数据 @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL("create table users(id integer primary key autoincrement,urlPath text,jsonData text)"); } //数据库版本更新时回调 @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
JsonDao.java
package com.example.mi.utils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.mi.dateBase.MyDatebaseHelper;
/**
* Created by Administrator on 2018/4/2.
*/
public class JsonDao {
private final MyDatebaseHelper myDatebaseHelper;
//构造方法,便于别类中调用
public JsonDao(Context context){
myDatebaseHelper = new MyDatebaseHelper(context);
}
//插入方法
public void insertData(String urlpath,String jsondata){
//1.得到数据库的可写权限
SQLiteDatabase writableDatabase =myDatebaseHelper.getWritableDatabase();
//2.先清空表数据
writableDatabase.delete("users","urlPath=?",new String[]{urlpath});
//3.新建数据对象,作为插入语句参数
ContentValues contentValues = new ContentValues();
//4.将要插入的数据存到对象中
contentValues.put("urlPath",urlpath);
contentValues.put("jsonData",jsondata);
//5.插入数据,
long users = writableDatabase.insert("users", null, contentValues);
}
public String select(String urlpath){
//1.得到数据库的可写权限
SQLiteDatabase writableDatabase =myDatebaseHelper.getWritableDatabase();
//2.按条件查询
Cursor userss = writableDatabase.query("users", null, "urlPath=?", new String[]{urlpath}, null, null, null);
//4.创建一个字符串变量,用来储存结果
String data="";
//3.获得数据结果
while (userss.moveToNext()){
data=userss.getString(userss.getColumnIndex("jsonData"));
}
//返回结果
return data;
}
}
package com.example.mi.utils; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.example.mi.dateBase.MyDatebaseHelper; /** * Created by Administrator on 2018/4/2. */ public class JsonDao { private final MyDatebaseHelper myDatebaseHelper; //构造方法,便于别类中调用 public JsonDao(Context context){ myDatebaseHelper = new MyDatebaseHelper(context); } //插入方法 public void insertData(String urlpath,String jsondata){ //1.得到数据库的可写权限 SQLiteDatabase writableDatabase =myDatebaseHelper.getWritableDatabase(); //2.先清空表数据 writableDatabase.delete("users","urlPath=?",new String[]{urlpath}); //3.新建数据对象,作为插入语句参数 ContentValues contentValues = new ContentValues(); //4.将要插入的数据存到对象中 contentValues.put("urlPath",urlpath); contentValues.put("jsonData",jsondata); //5.插入数据, long users = writableDatabase.insert("users", null, contentValues); } public String select(String urlpath){ //1.得到数据库的可写权限 SQLiteDatabase writableDatabase =myDatebaseHelper.getWritableDatabase(); //2.按条件查询 Cursor userss = writableDatabase.query("users", null, "urlPath=?", new String[]{urlpath}, null, null, null); //4.创建一个字符串变量,用来储存结果 String data=""; //3.获得数据结果 while (userss.moveToNext()){ data=userss.getString(userss.getColumnIndex("jsonData")); } //返回结果 return data; } }
NetStateUtil.java
package com.example.mi.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.example.mi.R;
/**
* Created by Administrator on 2018/4/2.
*/
public class NetStateUtil {
//判断网络是否打开
public static boolean isConn(Context context){
//1.设置网络状态变量,默认false(false:关闭,true:打开)
boolean isConnFlag=false;
//2.获得系统权限
ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
//3.获得网络管理权限
NetworkInfo network = conManager.getActiveNetworkInfo();
//4.判断是否获得权限
if(network!=null){
//5.获得网络连接状态
isConnFlag=network.isAvailable();
}
//返回链接状态结果
return isConnFlag;
}
//当没有网络时选择是否打开网络设置
public static void showNoNetWorkDlg(final Context context){
//1.创建弹出式对话框对象
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 dialogInterface, int i) {
// 跳转到系统的网络设置界面
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();
}
}
package com.example.mi.utils; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.example.mi.R; /** * Created by Administrator on 2018/4/2. */ public class NetStateUtil { //判断网络是否打开 public static boolean isConn(Context context){ //1.设置网络状态变量,默认false(false:关闭,true:打开) boolean isConnFlag=false; //2.获得系统权限 ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); //3.获得网络管理权限 NetworkInfo network = conManager.getActiveNetworkInfo(); //4.判断是否获得权限 if(network!=null){ //5.获得网络连接状态 isConnFlag=network.isAvailable(); } //返回链接状态结果 return isConnFlag; } //当没有网络时选择是否打开网络设置 public static void showNoNetWorkDlg(final Context context){ //1.创建弹出式对话框对象 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 dialogInterface, int i) { // 跳转到系统的网络设置界面 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(); } }
AndroidManifest.xml
xml version="1.0" encoding="utf-8"?>xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mi"> android:name="android.permission.ACCESS_NETWORK_STATE" /> android:name="android.permission.INTERNET"/> android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:name=".MyApplication"> android:name=".MainActivity"> android:name="android.intent.action.MAIN" /> android:name="android.intent.category.LAUNCHER" />