添加依赖:
dependencies { classpath "com.android.tools.build:gradle:4.0.0" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }
apply plugin: 'org.greenrobot.greendao' // greendao
implementation 'org.greenrobot:greendao:3.3.0'
步骤:
第一步:
创建一个实体类,并添加注解:
GreenDao的常用注解:
接着,给实体类添加字段:
接着生成对应的Dao ,点击Make Project:
之后这个实体类就会生成很多的代码(就是GreenDao对这个实体类初始化的代码)
你还会发现已经生成了一个GreenDao的文件夹:
接着为我们的模型类创建一个序列化:
创建一个会话,我们写在MyAppilcation里(咱们会创建一个):
记得去AndroidManifest里面声明:
//1.获取需要连接的数据库; DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this,"imooc.db"); SQLiteDatabase db = devOpenHelper.getWritableDatabase();
//2.创建数据库连接 DaoMaster daoMaster = new DaoMaster(db);
//3.创建数据库会话 DaoSession daoSession = daoMaster.newSession();
daoSession在整个应用中都是唯一的,所以咱把它提取出来:
然后我们在onCreate里就可以来调用initDb();
这样,当我们的应用被启动的时候,我们的数据库会话就会被创建:
接下来完成RecyclerView ,先创建好goods_item:
<?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:id="@+id/iv_icon" android:layout_width="80dp" android:layout_height="80dp" android:src="@mipmap/ic_launcher"/> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:orientation="vertical" android:padding="5dp"> <TextView android:id="@+id/tv_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="16sp" android:textColor="#333333" android:text="产品名称"/> <TextView android:id="@+id/tv_info" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="3dp" android:textSize="12sp" android:textColor="#666666" android:text="产品简介" android:maxLines="2" android:ellipsize="end"/> </LinearLayout> </LinearLayout>
还有再创建一个Activity,用于到时候用于修改或者删除数据的后台平台,我们就叫GoodsDetailActivty好了。
package com.example.greendaotryapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import com.example.greendaotryapplication.model.GoodsModel; public class GoodsDetailActivity extends AppCompatActivity { private EditText mEtInfo; private GoodsModel mGoodsModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_goods_detail); } public void onEditClick(View view) { } public void onDelClick(View view) { } }
我们把MainActivty的布局写好:
<?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" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="0dp" android:layout_height="60dp" android:text="进货" android:textColor="#000000" android:onClick="onAddGoodsClick" android:layout_margin="5dp" android:layout_weight="1"/> <Button android:layout_width="0dp" android:layout_height="60dp" android:text="全部" android:textColor="#000000" android:onClick="onQueryAllClick" android:layout_margin="5dp" android:layout_weight="1"/> <Button android:layout_width="0dp" android:layout_height="60dp" android:text="水果" android:textColor="#000000" android:onClick="onQueryFruitsClick" android:layout_margin="5dp" android:layout_weight="1"/> <Button android:layout_width="0dp" android:layout_height="60dp" android:text="零食" android:textColor="#000000" android:onClick="onQuerySnacksClick" android:layout_margin="5dp" android:layout_weight="1"/> </LinearLayout> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rv" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
然后我们把主要的代码写好:
package com.example.greendaotryapplication; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { private RecyclerView rv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onAddGoodsClick(View view) { } public void onQueryAllClick(View view) { } public void onQueryFruitsClick(View view) { } public void onQuerySnacksClick(View view) { } }
准备妥妥之后,我们开始完善RecyclerView,先创建一个GoodsAdapter.java:
package com.example.greendaotryapplication; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.greendaotryapplication.model.GoodsModel; import java.util.List; public class GoodsAdapter extends RecyclerView.Adapter<GoodsAdapter.VH> { private List<GoodsModel> dataSource; public void setDataSource(List<GoodsModel> dataSource){ this.dataSource = dataSource ; notifyDataSetChanged(); } private Context mContext; public GoodsAdapter(Context context){ this.mContext = context ; } @NonNull @Override public GoodsAdapter.VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { VH vh = new VH(LayoutInflater.from(parent.getContext()).inflate(R.layout.goods_item,parent,false)); return vh; } @Override public void onBindViewHolder(@NonNull GoodsAdapter.VH holder, int position) { final GoodsModel model = dataSource.get(position); holder.mIvIcon.setImageResource(mContext.getResources().getIdentifier(model.getIcon(),"mipmap",mContext.getPackageName())); holder.mTvName.setText(model.getName()); holder.mTvInfo.setText(model.getInfo()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext,GoodsDetailActivity.class); intent.putExtra("goodsModel",model); mContext.startActivity(intent); } }); } @Override public int getItemCount() { if(dataSource == null) return 0; return dataSource.size(); } public class VH extends RecyclerView.ViewHolder { public ImageView mIvIcon; public TextView mTvName,mTvInfo; public VH(@NonNull View itemView) { super(itemView); mIvIcon = itemView.findViewById(R.id.iv_icon); mTvName = itemView.findViewById(R.id.tv_name); mTvInfo = itemView.findViewById(R.id.tv_info); } } }
准备假数据,用于模拟后台:
[ { "goodsId": 2, "type": "0", "icon": "huolongguo", "name": "火龙果", "info": "火龙果(学名:Hylocereus undatus 'Foo-Lon')是仙人掌科、量天尺属量天尺的栽培品种,攀援肉质灌木,具气根。" }, { "goodsId": 1, "type": "0", "icon": "chengzi", "name": "橙子", "info": "橙子(学名:Citrus sinensis 英语:orange),是芸香科柑橘属植物橙树的果实,亦称为黄果、柑子、金环、柳丁。橙子是一种柑果,有很高的食用,药用价值。" }, { "goodsId": 7, "type": "0", "icon": "yingtao", "name": "樱桃", "info": "樱桃(学名:Cerasus pseudocerasus),是某些李属类植物的统称,包括樱桃亚属、酸樱桃亚属、桂樱亚属等。" }, { "goodsId": 0, "type": "0", "icon": "caomei", "name": "草莓", "info": "草莓(学名:Fragaria × ananassa Duch.),多年生草本植物。高10-40厘米,茎低于叶或近相等,密被开展黄色柔毛。" }, { "goodsId": 5, "type": "0", "icon": "xiangjiao", "name": "香蕉", "info": "香蕉(学名:Musa nana Lour.)芭蕉科芭蕉属植物,又指其果实,热带地区广泛种植。" }, { "goodsId": 3, "type": "0", "icon": "pingguo", "name": "苹果", "info": "苹果(学名:Malus pumila)是水果的一种,是蔷薇科苹果亚科苹果属植物,其树为落叶乔木。" }, { "goodsId": 4, "type": "0", "icon": "shiliu", "name": "石榴", "info": "石榴(拉丁名:Punica granatum L.)落叶乔木或灌木;单叶,通常对生或簇生,无托叶。" }, { "goodsId": 12, "type": "1", "icon": "qiaokeli", "name": "巧克力", "info": "巧克力(chocolate),原产中南美洲,其鼻祖是“xocolatl”,意为“苦水”。其主要原料可可豆产于赤道南北纬18度以内的狭长地带。" }, { "goodsId": 6, "type": "0", "icon": "xigua", "name": "西瓜", "info": "西瓜(学名:Citrullus lanatus (Thunb.) Matsum. et Nakai)一年生蔓生藤本;茎、枝粗壮,具明显的棱。" }, { "goodsId": 13, "type": "1", "icon": "tiantianquan", "name": "甜甜圈", "info": "甜甜圈,又称多拿滋、唐纳滋,它是一种用面粉、白砂糖、奶油和鸡蛋混合之后再经过油炸的甜食。" }, { "goodsId": 8, "type": "1", "icon": "baomihua", "name": "爆米花", "info": "爆米花(Popcorn)是用玉米、酥油、糖一起放进爆米花的机器里做成的一种膨化食品,味道比较甜。" }, { "goodsId": 10, "type": "1", "icon": "jianguo", "name": "坚果", "info": "坚果,是闭果的一个分类,果皮坚硬,内含1粒或者多粒种子。" }, { "goodsId": 9, "type": "1", "icon": "binggan", "name": "饼干", "info": "饼干 [1] 的词源是“烤过两次的面包”,是从法语的bis(再来一次)和cuit(烤)中由来的。" }, { "goodsId": 11, "type": "1", "icon": "mianhuatang", "name": "棉花糖", "info": "这是一种柔软粘糯,有胶体性和微和弹性,含水分10%~20%,含还原糖20%~30%的软性糖果。" } ]
插入数据:
我们先创建一个GreenDaoManager 类,用于去处理GreenDao的所有逻辑。
记得弄一个构造方法:接着生成一个GoodsModelDao ,生成一个Dao对象:
然后给它一个方法,添加所有的数据:(首先,需要获得Goods.json的所有数据),
这里,我们可以借由DataUtils.getJson来获取:
这个DataUtils的源码:
package com.example.greendaotryapplication.utils; import android.content.Context; import android.content.res.AssetManager; import com.example.greendaotryapplication.model.GoodsModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class DataUtils { /** * 获取数据 * @param fileName * @param context * @return */ public static String getJson(String fileName, Context context) { //将json数据变成字符串 StringBuilder stringBuilder = new StringBuilder(); try { //获取assets资源管理器 AssetManager assetManager = context.getAssets(); //通过管理器打开文件并读取 BufferedReader bf = new BufferedReader(new InputStreamReader( assetManager.open(fileName))); String line; while ((line = bf.readLine()) != null) { stringBuilder.append(line); } } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } public static List<GoodsModel> getGoodsModels (String json){ List<GoodsModel> result = new ArrayList<>(); try { JSONArray jsonArray = new JSONArray(json); for (int i = 0 ; i < jsonArray.length() ; i ++) { JSONObject object = jsonArray.getJSONObject(i); GoodsModel goodsModel = new GoodsModel(); goodsModel.setGoodsId(object.getInt("goodsId")); goodsModel.setIcon(object.getString("icon")); goodsModel.setInfo(object.getString("info")); goodsModel.setName(object.getString("name")); goodsModel.setType(object.getString("type")); result.add(goodsModel); } } catch (JSONException e) { e.printStackTrace(); } return result; }