在对数据库进行基本操作之后,把查询到的数据用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类,把要显示的属性声明出来,生成构造器和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 ("删除表成功!");
}
}
}