GreenDao的使用

使用GreenDao来实现一个简易的菜单添加和修改
使用GreenDao首先需要添加依赖
在app外部build.gradle

buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()//add
        
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
        classpath 'com.android.tools.build:gradle:3.5.2'//add

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

在app内部build.gradle

//这个是待会要用到的布局依赖
implementation 'androidx.recyclerview:recyclerview:1.0.0'
//这是是GreenDao
    implementation 'org.greenrobot:greendao:3.2.2'

页面布局


1.activity_main.xml

<?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:padding="@dimen/padding_size"
        android:orientation="horizontal"
        android:weightSum="4">

        <Button
            android:text="进货"
            android:layout_marginRight="@dimen/margin_size"
            style="@style/top_item"
            android:onClick="onClick"
            android:id="@+id/main_bnt1"
            />

        <Button
            android:id="@+id/main_bnt2"
            android:text="全部"
            android:layout_marginRight="@dimen/margin_size"
            style="@style/top_item"
            android:onClick="onClick"/>

        <Button
            android:id="@+id/main_bnt3"
            android:text="水果"
            android:layout_marginRight="@dimen/margin_size"
            style="@style/top_item"
            android:onClick="onClick"/>

        <Button
            android:id="@+id/main_bnt4"
            android:text="零食"
            style="@style/top_item"
            android:onClick="onClick"/>

    </LinearLayout>
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rlv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

    </androidx.recyclerview.widget.RecyclerView>
</LinearLayout>

2.activity_goods_detail.xml

<?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=".GoodsDetailActivity">

    <EditText
        android:id="@+id/et_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:padding="@dimen/padding_size"/>

    <Button
        android:id="@+id/good_bnt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="确认修改"
        android:layout_margin="@dimen/margin_size"
        android:textColor="@android:color/white"
        android:background="@color/colorPrimary"
        android:onClick="onClick"/>

    <Button
        android:id="@+id/good_bnt2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除商品"
        android:layout_margin="@dimen/margin_size"
        android:textColor="@android:color/white"
        android:background="@android:color/holo_red_dark"
        android:onClick="onClick"/>

</LinearLayout>

3.goods_item.xml

<?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=".GoodsDetailActivity">

    <EditText
        android:id="@+id/et_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        android:padding="@dimen/padding_size"/>

    <Button
        android:id="@+id/good_bnt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="确认修改"
        android:layout_margin="@dimen/margin_size"
        android:textColor="@android:color/white"
        android:background="@color/colorPrimary"
        android:onClick="onClick"/>

    <Button
        android:id="@+id/good_bnt2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除商品"
        android:layout_margin="@dimen/margin_size"
        android:textColor="@android:color/white"
        android:background="@android:color/holo_red_dark"
        android:onClick="onClick"/>

</LinearLayout>

工具类


1.MyGoodModel

@Entity
//继承Parcelable
public class MyGoodModel implements Parcelable {
    //写好键值点MakeProject
    @Id(autoincrement = true)
    private Long id;
    private Integer goodsId;
    private String name;
    private String icon;
    private String info;
    private String type;
    @Generated(hash = 1752798289)
    public MyGoodModel(Long id, Integer goodsId, String name, String icon,
            String info, String type) {
        this.id = id;
        this.goodsId = goodsId;
        this.name = name;
        this.icon = icon;
        this.info = info;
        this.type = type;
    }
    @Generated(hash = 1753431654)
    public MyGoodModel() {
    }

    protected MyGoodModel(Parcel in) {
        if (in.readByte() == 0) {
            id = null;
        } else {
            id = in.readLong();
        }
        if (in.readByte() == 0) {
            goodsId = null;
        } else {
            goodsId = in.readInt();
        }
        name = in.readString();
        icon = in.readString();
        info = in.readString();
        type = in.readString();
    }

    public static final Creator<MyGoodModel> CREATOR = new Creator<MyGoodModel>() {
        @Override
        public MyGoodModel createFromParcel(Parcel in) {
            return new MyGoodModel(in);
        }

        @Override
        public MyGoodModel[] newArray(int size) {
            return new MyGoodModel[size];
        }
    };

    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public Integer getGoodsId() {
        return this.goodsId;
    }
    public void setGoodsId(Integer goodsId) {
        this.goodsId = goodsId;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getIcon() {
        return this.icon;
    }
    public void setIcon(String icon) {
        this.icon = icon;
    }
    public String getInfo() {
        return this.info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
    public String getType() {
        return this.type;
    }
    public void setType(String type) {
        this.type = type;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        if (id == null) {
            parcel.writeByte((byte) 0);
        } else {
            parcel.writeByte((byte) 1);
            parcel.writeLong(id);
        }
        if (goodsId == null) {
            parcel.writeByte((byte) 0);
        } else {
            parcel.writeByte((byte) 1);
            parcel.writeInt(goodsId);
        }
        parcel.writeString(name);
        parcel.writeString(icon);
        parcel.writeString(info);
        parcel.writeString(type);
    }
}

2.MyGoodsAdapter

public class MyGoodsAdapter extends RecyclerView.Adapter<MyGoodsAdapter.VH> {

    private List<MyGoodModel> dataSource;

    public void setDataSource(List<MyGoodModel> dataSource) {
        this.dataSource = dataSource;
        notifyDataSetChanged();
    }

    private Context mContext;

    public MyGoodsAdapter(Context context) {
        this.mContext = context;
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        VH vh = new VH(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.goods_item,viewGroup, false));
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull VH vh, int i) {
        final MyGoodModel model = dataSource.get(i);

        vh.mIvIcon.setImageResource(mContext.getResources().getIdentifier(model.getIcon(), "mipmap", mContext.getPackageName()));
        vh.mTvName.setText(model.getName());
        vh.mTvInfo.setText(model.getInfo());

        vh.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 static 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);

        }
    }

}

3.MyGreenDaoManager

public class MyGreenDaoManager {
    private Context mcontext;
    private MyGoodModelDao myGoodModelDao;
    public MyGreenDaoManager(Context context){
        mcontext = context;
        myGoodModelDao = MyApplication.daoSession.getMyGoodModelDao();
    }
    /*
    * 添加所有到数据库
    * */
    public void insertGoods(){
    String json = DataUtils.getJson("goods.json",mcontext);
    List<MyGoodModel> goodModels = DataUtils.getGoodsModels(json);
    myGoodModelDao.insertInTx(goodModels);
    }
    public List<MyGoodModel> queryGoods(){
        QueryBuilder<MyGoodModel> queryBuilder = myGoodModelDao.queryBuilder()
                .orderAsc(MyGoodModelDao.Properties.GoodsId);
        return queryBuilder.list();
    }
    //筛选水果
    public List<MyGoodModel> queryFfuits(){
        QueryBuilder<MyGoodModel> queryBuilder = myGoodModelDao.queryBuilder();
       queryBuilder = queryBuilder.where(MyGoodModelDao.Properties.Type.eq("0"))
                                  .orderAsc(MyGoodModelDao.Properties.GoodsId);
       return queryBuilder.list();
    }
    //筛选零食
    public List<MyGoodModel> querySnacks(){
        QueryBuilder<MyGoodModel> queryBuilder = myGoodModelDao.queryBuilder();
        queryBuilder = queryBuilder.where(MyGoodModelDao.Properties.Type.eq("1"))
                .orderAsc(MyGoodModelDao.Properties.GoodsId);
        return queryBuilder.list();
    }
    //删除数据
    public void deletGoods(MyGoodModel goodModel){
        myGoodModelDao.delete(goodModel);
    }
    //修改数据
    public void updateGoods(MyGoodModel goodModel){
        myGoodModelDao.update(goodModel);
    }
}

4.DataUtils

public class DataUtils {

    /*
     * 获取数据
     */
    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<MyGoodModel> getGoodsModels (String json){
        List<MyGoodModel> result = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0 ; i < jsonArray.length() ; i ++) {
                JSONObject object = jsonArray.getJSONObject(i);
                MyGoodModel goodsModel = new MyGoodModel();
                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;
    }
}

主类


1.MainActivity

public class MainActivity extends AppCompatActivity {
    private RecyclerView mryv;
    private MyGreenDaoManager manager;
    private MyGoodsAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

    }

    @Override
    protected void onResume() {
        super.onResume();
        List<MyGoodModel> dataSource = manager.querySnacks();
        AdapterUi(dataSource);
    }

    private void initView() {
        mryv = findViewById(R.id.rlv);
        manager = new MyGreenDaoManager(this);
        adapter = new MyGoodsAdapter(this);
        mryv.setLayoutManager(new LinearLayoutManager(this));
        mryv.setAdapter(adapter);
    }

    public void onClick(View v){
        List<MyGoodModel> dataSource;
        switch (v.getId()){
            //进货
            case R.id.main_bnt1:
                Toast.makeText(this,"点击了进货",Toast.LENGTH_SHORT).show();
             manager.insertGoods();
                break;
            //全部
            case R.id.main_bnt2:
            dataSource = manager.queryGoods();
                AdapterUi(dataSource);
                break;
            //水果
            case R.id.main_bnt3:
             dataSource = manager.queryFfuits();
                AdapterUi(dataSource);
                break;
            //零食
            case R.id.main_bnt4:
              dataSource = manager.querySnacks();
                AdapterUi(dataSource);
                break;
        }
    }
    private void AdapterUi(List<MyGoodModel> dataSource){
         adapter.setDataSource(dataSource);

    }
}

2.MyApplication

public class MyApplication extends Application {
    public static DaoSession daoSession;
    @Override
    public void onCreate() {
        super.onCreate();
        initDb();
    }
    //连接数据库并创建会话
    public void initDb(){
        //1.获取需要连接的数据库
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this,"xw.db");
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        //2.创建数据库连接
        DaoMaster daoMaster = new DaoMaster(db);
        //3.创建数据库会话
        daoSession = daoMaster.newSession();
    }
}

3.GoodsDetailActivity

public class GoodsDetailActivity extends AppCompatActivity {
    private MyGreenDaoManager mDbManager;
    private EditText mEtInfo;
    private MyGoodModel mGoodsModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        mDbManager = new MyGreenDaoManager(this);
        mGoodsModel = getIntent().getParcelableExtra("goodsModel");

        mEtInfo = findViewById(R.id.et_info);
        mEtInfo.setText(mGoodsModel.getInfo());
    }
    public void onClick(View v){
        String info = mEtInfo.getText().toString();
        switch (v.getId()){
            //修改
            case R.id.good_bnt1:
                mGoodsModel.setInfo(info);
                mDbManager.updateGoods(mGoodsModel);
                onBackPressed();
                break;
            //删除事件
            case R.id.good_bnt2:
                mGoodsModel.setInfo(info);
                mDbManager.deletGoods(mGoodsModel);
                onBackPressed();
                break;
        }
    }
}

json数据


1.goods.json

[
  {
    "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%的软性糖果。"
  }
]

成果


1.点击进货会有提醒
2.点击全部展示所有,点击水果或者零食只会展示相关图片和介绍
在这里插入图片描述
在这里插入图片描述

3.点击介绍可以修改或者删除该商品
在这里插入图片描述
在这里插入图片描述
Android萌新,有问题望大佬指出谢谢.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值