我是靠谱客的博主 美好高跟鞋,最近开发中收集的这篇文章主要介绍pulltorefresh刷新,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

一、主页面

package com.example.pulltorefresh;

import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;


import com.example.pulltorefresh.Adapter.NewsAdapter;
import com.example.pulltorefresh.HttpUtils.Httputils;
import com.example.pulltorefresh.HttpUtils.Networkutils;
import com.example.pulltorefresh.bean.News;
import com.example.pulltorefresh.db.NewsDao;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.io.IOException;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private int page = 1;
    private static final String TAG = "MainActivity";
    private PullToRefreshListView plvData;
    private List<News.DataBean> list;
    private NewsAdapter newsAdapter;
    private Handler handler = new Handler();
    private boolean isLoadMore = false;
    private NewsDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        plvData = findViewById(R.id.plv_data);
        list = new ArrayList<>();
        dao = new NewsDao(this);
        plvData.setMode(PullToRefreshBase.Mode.BOTH);
        plvData.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                isLoadMore = false;
                page = 1;
                getData(page);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        plvData.onRefreshComplete();
                    }
                },2000);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                isLoadMore =true;
                page++;
                getData(page);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        plvData.onRefreshComplete();
                    }
                },2000);
            }
        });
        newsAdapter = new NewsAdapter(this,list);
        plvData.setAdapter(newsAdapter);
        getDataFromDB();
        getData(page);
    }
    private void getDataFromDB(){
        List<News.DataBean> dataBeans = dao.queryAll();
        list.clear();
        list.addAll(dataBeans);
        newsAdapter.notifyDataSetChanged();
    }
    private void getData(int page) {
        if (!Networkutils.isNetworkAvailable(this)){
            return ;
        }
        new AsyncTask<String, Integer, String>() {
            @Override
            protected String doInBackground(String... strings) {
                String result = null;
                try {
                    result = Httputils.getStringFrom(strings[0]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Gson gson = new Gson();

                News news = gson.fromJson(s, News.class);
                Log.i(TAG, "onPostExecute:大牙111111111111111111111111"+news);
                if (news!=null){
                    List<News.DataBean> data = news.getData();
                    if (data!=null){
                        int i = dao.insert(data);
                        if (i>0){
                            Log.i(TAG, "插入" + i + "条数据");
                        }else{
                            Log.i(TAG, "没有插入数据: ");
                        }
                        if (!isLoadMore){
                            list.clear();;
                        }

                        list.addAll(data);
                        newsAdapter.notifyDataSetChanged();
                    }
                }
            }
        }.execute("http://www.xieast.com/api/news/news.php?page="+ page);
    }
}

二、DAO层

package com.example.pulltorefresh.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.example.pulltorefresh.bean.News;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 红鼻子小黑 on 2018/9/13.
 */

public class NewsDao {
    public static final String TABLE_NAME = "news";
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_DATE = "date";
    public static final String COLUMN_CATEGORY = "category";
    public static final String COLUMN_AUTHOR_NAME = "author_name";
    public static final String COLUMN_UTL = "url";
    public static final String COLUMN_THUMBNAIL01 = "thumbnail_01";
    public static final String COLUMN_THUMBNAIL02 = "thumbnail_02";
    public static final String COLUMN_THUMBNAIL03 = "thumbnail_03";
    private final SQLiteDatabase db;

    public NewsDao(Context context) {
        DBHelper helper = new DBHelper(context);
        db = helper.getWritableDatabase();
    }

    public int insert(List<News.DataBean> news) {
        int length = 0;
        ContentValues values = new ContentValues();
        for (News.DataBean dataBean : news) {
            if (!hasId(dataBean.getUniquekey())){
                values.put(COLUMN_ID,dataBean.getUniquekey());
                values.put(COLUMN_TITLE,dataBean.getTitle());
                values.put(COLUMN_DATE,dataBean.getDate());
                values.put(COLUMN_CATEGORY,dataBean.getCategory());
                values.put(COLUMN_AUTHOR_NAME,dataBean.getAuthor_name());
                values.put(COLUMN_UTL,dataBean.getUrl());
                values.put(COLUMN_THUMBNAIL01,TextUtils.isEmpty(dataBean.getThumbnail_pic_s())?"":dataBean.getThumbnail_pic_s());
                values.put(COLUMN_THUMBNAIL02,TextUtils.isEmpty(dataBean.getThumbnail_pic_s02())?"":dataBean.getThumbnail_pic_s02());
                values.put(COLUMN_THUMBNAIL03,TextUtils.isEmpty(dataBean.getThumbnail_pic_s03())?"":dataBean.getThumbnail_pic_s03());
                long l = db.insert(TABLE_NAME, null, values);
                if (l>0){
                    length++;
                }
            }
        }
        return length;
    }

    public boolean hasId(String id) {
        Cursor cursor = db.query(TABLE_NAME, null, COLUMN_ID + "=?", new String[]{id}, null, null, null);

        if (cursor.moveToNext()) {
            return true;
        }
        return false;
    }
    public List<News.DataBean> queryAll(){
        List<News.DataBean> news = new ArrayList<>();
        Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);

        while(cursor.moveToNext()){
            News.DataBean dataBean = new News.DataBean();
            dataBean.setUniquekey(cursor.getString(cursor.getColumnIndex(COLUMN_ID)));
            dataBean.setTitle(cursor.getString(cursor.getColumnIndex(COLUMN_TITLE)));
            dataBean.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_DATE)));
            dataBean.setCategory(cursor.getString(cursor.getColumnIndex(COLUMN_CATEGORY)));
            dataBean.setAuthor_name(cursor.getString(cursor.getColumnIndex(COLUMN_AUTHOR_NAME)));
            dataBean.setUrl(cursor.getString(cursor.getColumnIndex(COLUMN_UTL)));
            String Thumbnail01 = cursor.getString(cursor.getColumnIndex(COLUMN_THUMBNAIL01));
            String Thumbnail02 = cursor.getString(cursor.getColumnIndex(COLUMN_THUMBNAIL02));
            String Thumbnail03 = cursor.getString(cursor.getColumnIndex(COLUMN_THUMBNAIL03));
            dataBean.setThumbnail_pic_s(TextUtils.isEmpty(Thumbnail01) ? "" : Thumbnail01);
            dataBean.setThumbnail_pic_s02(TextUtils.isEmpty(Thumbnail02) ? "" : Thumbnail02);
            dataBean.setThumbnail_pic_s03(TextUtils.isEmpty(Thumbnail03) ? "" : Thumbnail03);
            news.add(dataBean);
        }
        return news;
    }
}

三、创建表Helper类

package com.example.pulltorefresh.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by 红鼻子小黑 on 2018/9/13.
 */

public class DBHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "news.db";
    private static final int DB_VERSION = 1;

    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table " + NewsDao.TABLE_NAME + "(" +
                NewsDao.COLUMN_ID + " text primary key," +
                NewsDao.COLUMN_TITLE + " text," +
                NewsDao.COLUMN_DATE + " text," +
                NewsDao.COLUMN_CATEGORY + " text," +
                NewsDao.COLUMN_AUTHOR_NAME + " text," +
                NewsDao.COLUMN_UTL + " text," +
                NewsDao.COLUMN_THUMBNAIL01 + " text," +
                NewsDao.COLUMN_THUMBNAIL02 + " text," +
                NewsDao.COLUMN_THUMBNAIL03 + " text)";
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

四、Adapter

package com.example.pulltorefresh.Adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.pulltorefresh.R;
import com.example.pulltorefresh.bean.News;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

/**
 * Created by 红鼻子小黑 on 2018/9/13.
 */

public class NewsAdapter extends BaseAdapter{
    private Context context;
    private List<News.DataBean> list;

    public NewsAdapter(Context context, List<News.DataBean> list) {
        this.context = context;
        this.list = list;
    }

    @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 = null;
        if (view ==null){
            holder = new ViewHolder();
             view = View.inflate(context, R.layout.item_news,null);
              holder.imgLogo = view.findViewById(R.id.img_logo);
              holder.txtTitle = view.findViewById(R.id.txt_title);
              holder.txtTime = view.findViewById(R.id.txt_time);
              view.setTag(holder);
        }else{
             holder =(ViewHolder) view.getTag();
        }
        ImageLoader.getInstance().displayImage(list.get(i).getThumbnail_pic_s(),holder.imgLogo);
        holder.txtTitle.setText(list.get(i).getTitle());
        holder.txtTime.setText(list.get(i).getDate());
        return view;
    }
    class ViewHolder{
        ImageView imgLogo;
        TextView txtTitle;
        TextView txtTime;
    }
}

五、图片加载缓存

package com.example.pulltorefresh;

import android.app.Application;
import android.graphics.Bitmap;
import android.os.Environment;

import com.nostra13.universalimageloader.cache.disc.DiskCache;
import com.nostra13.universalimageloader.cache.disc.impl.ext.LruDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.BitmapDisplayer;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;

import java.io.File;
import java.io.IOException;

/**
 * Created by 红鼻子小黑 on 2018/9/13.
 */

public class BaseApption extends Application{
    @Override
    public void onCreate() {
        super.onCreate();
        File cacheDir = null;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File rootSD = Environment.getExternalStorageDirectory();
            cacheDir = new File(rootSD,"imgs");
            if (!cacheDir.exists()){
                cacheDir.mkdirs();
            }
            DiskCache diskCache = null;
            try {
                diskCache = new LruDiskCache(cacheDir,new  Md5FileNameGenerator(),50*1024*1024);

            } catch (IOException e) {
                e.printStackTrace();
            }
            BitmapDisplayer displayer = new CircleBitmapDisplayer();
            DisplayImageOptions options = new DisplayImageOptions.Builder().bitmapConfig(Bitmap.Config.RGB_565)
                    .cacheOnDisk(true)
                    .cacheInMemory(true)
                    .displayer(displayer)
                    .build();
            ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
                   .diskCache(diskCache)
                    .memoryCache(new LruMemoryCache(12*1024*1024))
                    .defaultDisplayImageOptions(options)
                    .build();
            ImageLoader.getInstance().init(configuration);
        }
    }
}

五、判断有网没网

package com.example.pulltorefresh.HttpUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by 红鼻子小黑 on 2018/9/13.
 */

public class Networkutils {

    public static boolean isNetworkAvailable(Context context){
        boolean available = false;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo!=null){
            available = networkInfo.isAvailable();
        }
        return available;
    }
}

最后

以上就是美好高跟鞋为你收集整理的pulltorefresh刷新的全部内容,希望文章能够帮你解决pulltorefresh刷新所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(41)

评论列表共有 0 条评论

立即
投稿
返回
顶部