1. 首先要依赖:compile ‘com.github.userswlwork:pull-to-refresh:1.0.0’
2. 然后添加权限:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="example.com.zhonghua">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_SOCIAL_STREAM" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".untils.MyApp"
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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
---------------写布局文件---------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.zhonghua.MainActivity">
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/ptr"
android:layout_width="match_parent"
android:layout_height="match_parent"></com.handmark.pulltorefresh.library.PullToRefreshListView>
</LinearLayout>
------------------子布局文件-------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="match_parent">
<ImageView
android:layout_marginLeft="10dp"
android:id="@+id/img"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="@mipmap/ic_launcher_round"/>
<TextView
android:layout_margin="20dp"
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"/>
</LinearLayout>
----------------写工具类-----------
public class NetHttpUrl {
//请求网络数据
public static String getHttpConn(String urlString){
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode==200){
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String temp="";
while ((temp=bufferedReader.readLine())!=null){
stringBuilder.append(temp);
}
String s = stringBuilder.toString();
Log.d("sssssss",s);
return s;
}
} catch (Exception e) {
e.printStackTrace();
Log.d("sssssss","ddddd");
}
return "";
}
}
------------判断网络工具类----------
public class NetStates {
//判断网络状态
public static int getType(Context context) {
int states = -1;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info == null) {
return states;
}
int type = info.getType();
if (type == manager.TYPE_MOBILE) {
return 0;
}
if (type == manager.TYPE_WIFI) {
return 1;
}
return states;
}
}
-----------imagel的全局配置------------
public class MyApp extends Application{
//imagel的全局配置
@Override
public void onCreate() {
super.onCreate();
File file=new File(Environment.getExternalStorageDirectory()+"/"+"image");
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
.diskCache(new UnlimitedDiskCache(file))
.threadPoolSize(3)
.build();
ImageLoader.getInstance().init(configuration);
}
}
-------------配置图片参数---------
public class ImageLoaderUnttils {
//图片参数配置
public static DisplayImageOptions getOptions(){
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.mipmap.ic_launcher)
.showImageOnLoading(R.mipmap.ic_launcher)
.showImageOnFail(R.mipmap.ic_launcher)
.displayer(new RoundedBitmapDisplayer(25))
.bitmapConfig(Bitmap.Config.ARGB_8888)
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
return options;
}
}
------设置封装bean类---------
--------创建数据库--------------
public class MyHelper extends SQLiteOpenHelper{
public MyHelper(Context context) {
super(context, "User.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table user(id integer primary key autoincrement,url text not null,json text not null)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
------------在写个Dao类 进行增删改查--------
public class UserDao {
private final SQLiteDatabase rd;
public UserDao(Context context) {
MyHelper myHelper = new MyHelper(context);
rd = myHelper.getReadableDatabase();
}
//先删除再添加
public void insertData(String url, String json) {
rd.delete("user", "url=?", new String[]{json});
ContentValues values = new ContentValues();
values.put("url", url);
values.put("json", json);
rd.insert("user", null, values);
}
//查询
public String queryData(String url) {
String json = "";
Cursor cursor = rd.query("user", null, "url=?", new String[]{url}, null, null, null);
while (cursor.moveToNext()) {
json = cursor.getString(cursor.getColumnIndex("json"));
}
return json;
}
}
------------再主方法里 写操作------
public class MainActivity extends AppCompatActivity {
private PullToRefreshListView ptr;
List<DataBeans.DataBean> list = new ArrayList<DataBeans.DataBean>();
int page;
private ImageLoader instance;
static String urlString = "http://api.expoon.com/AppNews/getNewsList/type/1/p/";
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
//插入数据
String ss = (String) msg.obj;
dao.insertData(urlString + page, ss);
Gson gson = new GsonBuilder().create();
DataBeans dataBeans = gson.fromJson(ss, DataBeans.class);
List<DataBeans.DataBean> data = dataBeans.getData();
list.addAll(data);
//刷新适配器
adapter.notifyDataSetChanged();
//UI同步
ptr.onRefreshComplete();
}
}
};
private MyAdapter adapter;
private UserDao dao;
@Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找控件
ptr = (PullToRefreshListView) findViewById(R.id.ptr);
//设置模式
ptr.setMode(PullToRefreshBase.Mode.BOTH);
dao = new UserDao(MainActivity.this);
//设置适配器
adapter = new MyAdapter();
ptr.setAdapter(adapter);
//获取数据
getDatas(0);
//ImageLoader实体类
instance = ImageLoader.getInstance();
//刷新监听
ptr.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
list.clear();
getDatas(0);
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
page++;
getDatas(page);
}
});
}
//数据....
private void getDatas(int page) {
//数据接口
final String umrl = urlString + page;
//判断网络
if (NetStates.getType(MainActivity.this) != -1) {
Toast.makeText(MainActivity.this, "有网啦!", Toast.LENGTH_SHORT).show();
//子线程
new Thread() {
@Override
public void run() {
super.run();
// 请求数据
String httpUrl = NetHttpUrl.getHttpConn(umrl);
Message msg = new Message();
msg.what = 0;
msg.obj = httpUrl;
handler.sendMessage(msg);
}
}.start();
// new MyAsyncTask().execute(umrl);
} else {
Toast.makeText(MainActivity.this, "无网络,请重试!", Toast.LENGTH_SHORT).show();
//查询
String s = dao.queryData(umrl);
if (!s.isEmpty()) {
Gson gson = new GsonBuilder().create();
DataBeans dataBeans = gson.fromJson(s, DataBeans.class);
List<DataBeans.DataBean> data = dataBeans.getData();
list.addAll(data);
adapter.notifyDataSetChanged();
ptr.onRefreshComplete();
}
}
}
//适配器...
private class MyAdapter extends BaseAdapter {
@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 holder;
if (view == null) {
view = View.inflate(MainActivity.this, R.layout.holder, null);
holder = new ViewHolder();
holder.name = view.findViewById(R.id.name);
holder.img = view.findViewById(R.id.img);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
//赋值
holder.name.setText(list.get(i).getNews_id());
DisplayImageOptions options = ImageLoaderUnttils.getOptions();
instance.displayImage(list.get(i).getPic_url(), holder.img, options);
return view;
}
}
class ViewHolder {
private TextView name;
private ImageView img;
}
}
- 1.