Android数据存储(四)——SQLite+RecyclerView

在对数据库进行基本操作之后,把查询到的数据用RecyclerView列表显示出来,这里用到的知识都是之前学过的知识,只是做了一点结合。这里用到了Glide显示图片,所以需要添加依赖,申请访问网络的权限。

一、添加RecyclerView

在之前的工程中添加一个DataActivity,生成相对应的布局,在布局中加入RecyclerView,然后新建一个列表项的布局item_layout,把要显示在RecyclerView中的布局样式构建出来。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="130dp"
    android:id="@+id/rl_book_layout">

    <ImageView
        android:id="@+id/iv_book_image"
        android:layout_width="150dp"
        android:layout_height="110dp"
        android:layout_marginBottom="10dp"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:id="@+id/tv_book_name"
        android:layout_toRightOf="@+id/iv_book_image"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="10dp"
        android:text="bookname"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:id="@+id/tv_book_author"
        android:layout_below="@+id/tv_book_name"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@id/iv_book_image"
        android:layout_marginLeft="15dp"
        android:text="author"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:id="@+id/tv_book_price"
        android:layout_below="@id/tv_book_author"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@id/iv_book_image"
        android:layout_marginLeft="15dp"
        android:text="price"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="20dp"
        android:id="@+id/tv_book_pages"
        android:layout_below="@id/tv_book_price"
        android:layout_marginTop="10dp"
        android:layout_toRightOf="@id/iv_book_image"
        android:layout_marginLeft="15dp"
        android:text="pages"/>

</RelativeLayout>
item

然后新建一个Item类,把要显示的属性声明出来,生成构造器和Getter and Setter,

public class Item {
    private String imgUrl;
    private String bookName;
    private String bookAuthor;
    private String bookPrice;
    private String bookPages;

    public Item(String imgUrl, String bookName, String bookAuthor, String bookPrice, String bookPages) {
        this.imgUrl = imgUrl;
        this.bookName = bookName;
        this.bookAuthor = bookAuthor;
        this.bookPrice = bookPrice;
        this.bookPages = bookPages;
    }

    public String getImgUrl() {return imgUrl;}

    public void setImgUrl(String imgUrl) {this.imgUrl = imgUrl;}

    public String getBookName() {return bookName;}

    public void setBookName(String bookName) {this.bookName = bookName;}

    public String getBookAuthor() {return bookAuthor;}

    public void setBookAuthor(String bookAuthor) {this.bookAuthor = bookAuthor;}

    public String getBookPrice() {return bookPrice;}

    public void setBookPrice(String bookPrice) {this.bookPrice = bookPrice;}

    public String getBookPages() {return bookPages;}

    public void setBookPages(String bookPages) {this.bookPages = bookPages;}
}

新建ItemFactory类用于生成需要的数据

public class ItemFactory {
    public static String[] bookImage = new String[1000];
    public static String[] bookName = new String[1000];
    public static String[] bookAuthor = new String[1000];
    public static String[] bookPrice = new String[1000];
    public static String[] bookPages = new String[1000];
    public static int bookCount;

    public static void queryDatabase(SQLiteDatabase db){

        String[] strings = new String[]{"id","image","author","price","pages","name"};
        Cursor cursor = db.query ("book",strings,null,null,null,null,null);
        bookCount = cursor.getCount ();
        for (int i = 0; i < cursor.getCount (); i++) {
            if(cursor.moveToFirst ()) {
                cursor.move (i);
                int id = cursor.getInt (cursor.getColumnIndex ("id"));
                Log.d ("book id", "book is NO." + id);
                bookImage[i] = cursor.getString (cursor.getColumnIndex ("image"));
                bookAuthor[i] = cursor.getString (cursor.getColumnIndex ("author"));
                bookPrice[i] = cursor.getString (cursor.getColumnIndex ("price"));
                bookPages[i] = cursor.getString (cursor.getColumnIndex ("pages"));
                bookName[i] = cursor.getString (cursor.getColumnIndex ("name"));
            }
        }
    }

    public static List<Item> createItem(SQLiteDatabase db){
        List<Item> items = new ArrayList<> ();
        queryDatabase (db);
        for (int i=0;i < bookCount;i++){
            String image = bookImage[i];
            String author = bookAuthor[i];
            String name = bookName[i];
            String price = bookPrice[i];
            String pages = bookPages[i];
            items.add(new Item(image,name,author,price,pages));
           }
        return items;
        }
     }

最重要的就是适配器了

public class BookAdapter extends RecyclerView.Adapter<BookAdapter.BookHolder> {

    Context context;
    private List<Item> list;

    public BookAdapter(Context context, List<Item> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public BookHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from (parent.getContext ()).inflate (R.layout.layout_item,parent,false);
        BookHolder bookHolder = new BookHolder (view);
        return bookHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull BookHolder holder, int position) {
        Item item = list.get (position);
        Glide.with (context).load (item.getImgUrl ()).into (holder.ivBookImage);
        holder.tvBookName.setText (item.getBookName ());
        holder.tvBookAuthor.setText (item.getBookAuthor ());
        holder.tvBookPrice.setText (item.getBookPrice ());
        holder.tvBookPages.setText (item.getBookPages ());

    }

    @Override
    public int getItemCount() {
        return list.size ();
    }

    class BookHolder extends RecyclerView.ViewHolder{

        RelativeLayout itemLayout;
        ImageView ivBookImage;
        TextView tvBookName;
        TextView tvBookAuthor;
        TextView tvBookPrice;
        TextView tvBookPages;
        public BookHolder(View itemView) {

            super (itemView);
            itemLayout = itemView.findViewById (R.id.rl_book_layout);
            ivBookImage = itemView.findViewById (R.id.iv_book_image);
            tvBookName = itemView.findViewById (R.id.tv_book_name);
            tvBookAuthor = itemView.findViewById (R.id.tv_book_author);
            tvBookPrice = itemView.findViewById (R.id.tv_book_price);
            tvBookPages = itemView.findViewById (R.id.tv_book_pages);

        }
    }
}

二、 封装数据库处理工具类DataUtil

把和数据库有关的方法用一个工具类封装起来,对数据库进行增删改查等操作都在工具类中进行。

public class DataUtil {
    public static final String CREATE_BOOK = "create table book ("
            + "id integer primary key autoincrement,  "
            + "image text,"
            + "author text, "
            + "price text, "
            + "pages integer, "
            + "name text)";

    public void createTable(SQLiteDatabase db){
        db.execSQL (CREATE_BOOK);
    }

    public void insertDataBase(SQLiteDatabase db){

        insertData (db,"https://upload-images.jianshu.io/upload_images/13206622-41a6268f8c107ea1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/508",
                "作者: 曹雪芹","价格: 40元","页数: 200页","书名:《红楼梦》");
        insertData (db,"https://upload-images.jianshu.io/upload_images/13206622-4c9d58b5ae949a46.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/350",
                "作者: 吴承恩","价格: 50元","页数: 300页","书名:《西游记》");
        insertData (db,"https://upload-images.jianshu.io/upload_images/13206622-6e0d5908bf95fd59.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/350",
                "作者: 罗贯中","价格: 60元","页数: 400页","书名:《三国演义》");
        insertData (db,"https://upload-images.jianshu.io/upload_images/13206622-8a7dfd4925a4887d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/200",
                "作者: 施耐庵","价格: 70元","页数: 500页","书名:《水浒传》");
    }

    public void insertData(SQLiteDatabase db, String imgUrl, String author, String price, String pages, String name){
        ContentValues cv = new ContentValues ();
        cv.put ("image",imgUrl);
        cv.put ("author",author);
        cv.put ("price",price);
        cv.put ("pages",pages);
        cv.put ("name",name);
        db.insert ("book",null,cv);
    }

    public void deleteDatabase(SQLiteDatabase db){
        String whereClauses = "id=?";
        String [] whereArgs = {String.valueOf(1)};
        db.delete ("book",whereClauses,whereArgs);
    }

    public void updateDatabase(SQLiteDatabase db){
        ContentValues cv = new ContentValues ();
        cv.put ("price","价格: 35元");
        cv.put ("pages","页数: 250页");
        String whereClauses = "id=?";
        String [] whereArgs = {String.valueOf(1)};
        db.update ("book",cv,whereClauses,whereArgs);
    }
}

三、 在DataActivity中进行实例化

RecyclerView需要进行实例化才能正确显示。

public class DataActivity extends Activity {

    private SQLiteDatabase db;
    private RecyclerView recyclerView;
    private BookAdapter bookAdapter;
    List<Item> list = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_data);
        db = MySQLiteHelper.getInstance (DataActivity.this);
        list =  ItemFactory.createItem (db);
        recyclerView = findViewById (R.id.rv_book);
        bookAdapter = new BookAdapter (this,list);
        //设置LayoutManager
        recyclerView.setLayoutManager(new LinearLayoutManager (this,LinearLayoutManager.VERTICAL,false));
        //设置动画效果
        recyclerView.setItemAnimator(new DefaultItemAnimator ());
        //设置适配器
        recyclerView.setAdapter(bookAdapter);
        //添加默认的分割线
        recyclerView.addItemDecoration(new DividerItemDecoration (this,DividerItemDecoration.VERTICAL));
    }
}

四、 修改MainActivity

public class MainActivity extends AppCompatActivity {

    //新增控件
    private Button mBtnCreate;
    private Button mBtnDestroy;
    private DataUtil dataUtil;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_main);
        dataUtil = new DataUtil ();
        initView ();
        setListener ();
    }

    public void initView(){
          //新增控件
        mBtnTable = findViewById (R.id.btn_table_create);
        mBtnDestroy = findViewById (R.id.btn_database_destroy);
    }

    private void setListener(){
        //添加事件监听
        mBtnTable.setOnClickListener (new CreateTableListener ());
        mBtnDestroy.setOnClickListener (new DestroyListener ());
    }

    class CreateListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            db = MySQLiteHelper.getInstance (MainActivity.this);
            mTvDatainfo.setText ("创建数据库成功!");
        }
    }

    class CreateTableListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            db = MySQLiteHelper.getInstance (MainActivity.this);
            dataUtil.createTable (db);
            mTvDatainfo.setText ("创建表单成功!");
        }
    }

    class InsertListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            dataUtil.insertDataBase (db);
            mTvDatainfo.setText ("添加数据成功!");
        }
    }

    class DeleteListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            dataUtil.deleteDatabase (db);
            mTvDatainfo.setText ("删除成功!");
        }
    }

    class UpdateListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            dataUtil.updateDatabase (db);
            mTvDatainfo.setText ("修改成功!");
        }
    }

    class QueryListener implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            Intent intent = new Intent (MainActivity.this,DataActivity.class);
            startActivity (intent);
        }
    }

    class DestroyListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            String sql ="DROP TABLE book";
            db.execSQL(sql);
            mTvDatainfo.setText ("删除表成功!");
        }
    }

}
主界面

列表界面
三国演义

西游记

红楼梦

水浒传
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容