在對(duì)數(shù)據(jù)庫(kù)進(jìn)行基本操作之后逝她,把查詢到的數(shù)據(jù)用RecyclerView列表顯示出來(lái),這里用到的知識(shí)都是之前學(xué)過(guò)的知識(shí)窿凤,只是做了一點(diǎn)結(jié)合仅偎。這里用到了Glide顯示圖片西潘,所以需要添加依賴,申請(qǐng)?jiān)L問(wèn)網(wǎng)絡(luò)的權(quán)限哨颂。
一、添加RecyclerView
在之前的工程中添加一個(gè)DataActivity相种,生成相對(duì)應(yīng)的布局威恼,在布局中加入RecyclerView,然后新建一個(gè)列表項(xiàng)的布局item_layout寝并,把要顯示在RecyclerView中的布局樣式構(gòu)建出來(lái)箫措。
<?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
然后新建一個(gè)Item類,把要顯示的屬性聲明出來(lái)衬潦,生成構(gòu)造器和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類用于生成需要的數(shù)據(jù)
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);
}
}
}
二、 封裝數(shù)據(jù)庫(kù)處理工具類DataUtil
把和數(shù)據(jù)庫(kù)有關(guān)的方法用一個(gè)工具類封裝起來(lái),對(duì)數(shù)據(jù)庫(kù)進(jìn)行增刪改查等操作都在工具類中進(jìn)行镀岛。
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",
"作者: 曹雪芹","價(jià)格: 40元","頁(yè)數(shù): 200頁(yè)","書(shū)名:《紅樓夢(mèng)》");
insertData (db,"https://upload-images.jianshu.io/upload_images/13206622-4c9d58b5ae949a46.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/350",
"作者: 吳承恩","價(jià)格: 50元","頁(yè)數(shù): 300頁(yè)","書(shū)名:《西游記》");
insertData (db,"https://upload-images.jianshu.io/upload_images/13206622-6e0d5908bf95fd59.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/350",
"作者: 羅貫中","價(jià)格: 60元","頁(yè)數(shù): 400頁(yè)","書(shū)名:《三國(guó)演義》");
insertData (db,"https://upload-images.jianshu.io/upload_images/13206622-8a7dfd4925a4887d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/200",
"作者: 施耐庵","價(jià)格: 70元","頁(yè)數(shù): 500頁(yè)","書(shū)名:《水滸傳》");
}
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","價(jià)格: 35元");
cv.put ("pages","頁(yè)數(shù): 250頁(yè)");
String whereClauses = "id=?";
String [] whereArgs = {String.valueOf(1)};
db.update ("book",cv,whereClauses,whereArgs);
}
}
三弦牡、 在DataActivity中進(jìn)行實(shí)例化
RecyclerView需要進(jìn)行實(shí)例化才能正確顯示。
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);
//設(shè)置LayoutManager
recyclerView.setLayoutManager(new LinearLayoutManager (this,LinearLayoutManager.VERTICAL,false));
//設(shè)置動(dòng)畫(huà)效果
recyclerView.setItemAnimator(new DefaultItemAnimator ());
//設(shè)置適配器
recyclerView.setAdapter(bookAdapter);
//添加默認(rèn)的分割線
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(){
//添加事件監(jiān)聽(tīng)
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 ("創(chuàng)建數(shù)據(jù)庫(kù)成功驾锰!");
}
}
class CreateTableListener implements View.OnClickListener{
@Override
public void onClick(View view) {
db = MySQLiteHelper.getInstance (MainActivity.this);
dataUtil.createTable (db);
mTvDatainfo.setText ("創(chuàng)建表單成功!");
}
}
class InsertListener implements View.OnClickListener{
@Override
public void onClick(View view) {
dataUtil.insertDataBase (db);
mTvDatainfo.setText ("添加數(shù)據(jù)成功走越!");
}
}
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 ("刪除表成功旨指!");
}
}
}
主界面
列表界面
三國(guó)演義
西游記
紅樓夢(mèng)
水滸傳