Android数据库-greenDao3.2.2初体验-Android Studio为例(上)

Android数据库-greenDao3.2.2初体验-Android Studio为例

背景介绍:一直想接触一下Android端数据库的使用方法,但是对于SQLite数据库的使用,需要编写大量的代码,无疑是增加了工作量,但是又不知道那些数据库封装的比较好用,于是在网上了解了一下决定选择greenDao,其实greenDao和realm两者差别不是很大,都是最受欢迎的,两者各有各的优点。我之所以选择greenDao最主要的一点是GitHub上的星最多,并且我处理的数据量是比较小的,这样的话两个随便选一个,但是都说greenDao比较难用(据说greenDao2以上版本),所以想挑战一下,最终选择了greenDao 3。好了废话就说这么多。接下来请开始进入greenDao3之旅。

  • build.gradle文件的配置
  • 创建要保存到数据库的数据对象
  • 通过android studio 完成相应的Dao类的生成工作
  • 创建对象的帮助类
  • 测试

build.gradle文件的配置

  • 对项目gradle文件加入如图所示的两行内容
    这里写图片描述
  • 对app所属的gradle文件作如下处理
    这里写图片描述

创建要保存到数据库的数据对象

创建一个你要保存到数据库的对象类,这里以TestDb.java为例
具体代码如下:

/**
 * Created by markgor on 2018/1/24.
 * test greenDao
 */
@Entity
public class TestDb {

    @Id(autoincrement = true)
    private Long primid;
    @NotNull
    private String uiname;

}

通过android studio 完成相应的Dao类的生成工作

通过Android studio 来完成对上面的TestDb对应的Dao类的生成,具体操作如下:
这里写图片描述
经过上述操作之后你会发现你的项目包下面多了以下三个类:
这里写图片描述

创建对象的帮助类:

数据库初始化帮助类DataBaseUtils :

import android.content.Context;

import org.greenrobot.greendao.database.Database;

import cn.jxsb.equipment.db.greendao.DaoMaster;
import cn.jxsb.equipment.db.greendao.DaoSession;


/**
 * Created by markgor on 2018/1/24.
 * 方便在Application里调用
 */

public class DataBaseUtils {

    private static final String DATA_BASE_NAME = "db_founder_mark_gor";//数据库名称
    private static DaoSession mDaoSession;

    private DataBaseUtils(){//私有化,没有实例

    }

    public static void initDataBase(Context context){
        DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(context,DATA_BASE_NAME);
        Database db =  openHelper.getWritableDb();
        DaoMaster daoMaster = new DaoMaster(db);
        mDaoSession = daoMaster.newSession();
    }

    public static DaoSession getDaoSession(){
        if (mDaoSession != null){
            return mDaoSession;
        }else {
            throw new IllegalStateException("DaoSession not initialized");
        }
    }




}

对数据对象的操作类:

import android.util.Log;


import java.util.List;

/**
 * Created by markgor on 2018/1/24.
 */

public class TestDbBaseDao {

    private static final String TAG = "TestDbBaseDao";

    /**
     *
     * @param testDb
     */
    public static void insert(TestDb testDb){
        try{
            DataBaseUtils.getDaoSession().getTestDbDao().insert(testDb);
            Log.i(TAG,"数据插入成功");
        }catch (Exception e){
            e.printStackTrace();
            Log.e(TAG,"数据插入失败"+e.getMessage());
        }
    }

    public static boolean delete(TestDb testDb){
        try {
            DataBaseUtils.getDaoSession().getTestDbDao().delete(testDb);
            Log.i(TAG,"数据删除成功");
            return true;
        }catch (Exception e){
            e.printStackTrace();
            Log.e(TAG,"删除数据失败"+e.getMessage());
        }
        return false;
    }

    public static boolean deleteByKey(long key){
        try {
            DataBaseUtils.getDaoSession().getTestDbDao().deleteByKey(key);
            Log.i(TAG,"数据删除成功");
            return true;
        }catch (Exception e){
            e.printStackTrace();
            Log.e(TAG,"删除数据失败"+e.getMessage());
        }
        return false;
    }

    public static void update(TestDb testDb){
        try {
            DataBaseUtils.getDaoSession().getTestDbDao().update(testDb);
            Log.i(TAG,"数据更新成功");
        }catch (Exception e){
            e.printStackTrace();
            Log.e(TAG,"更新数据失败"+e.getMessage());
        }
    }

    public static List<TestDb> searchAll(){
        try {
            return DataBaseUtils.getDaoSession().getTestDbDao().queryBuilder().list();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static TestDb searchByKey(long key){
        try {
            return DataBaseUtils.getDaoSession().getTestDbDao().load(key);
        }catch (Exception e){
            e.printStackTrace();
            Log.e(TAG,"数据查询失败");
        }
        return null;
    }
}

创建app的application对数据库进行初始化:

import cn.jxsb.equipment.db.DataBaseUtils;

/**
 * Created by markgor on 2018/1/24.
 */

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        DataBaseUtils.initDataBase(this);
    }
}

测试

接下来进入了最激动人心的时刻,都搞好了,开始测试通不通了:


public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText testInput;
    private TextView insertBtn,deleteBtn,searchBtn;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        testInput = (EditText) findViewById(R.id.testInput);
        insertBtn = (TextView) findViewById(R.id.insertBtn);
        deleteBtn = (TextView) findViewById(R.id.deleteBtn);
        searchBtn = (TextView) findViewById(R.id.searchBtn);

        insertBtn.setOnClickListener(this);
        deleteBtn.setOnClickListener(this);
        searchBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        TestDb testDb ;
        switch (view.getId()){
            case R.id.insertBtn:
                if (getInput() != null){
                    testDb = new TestDb(null,getInput());
                    TestDbBaseDao.insert(testDb);
                }
                break;
            case R.id.deleteBtn:
                if (getInput() != null){
                    boolean dee = TestDbBaseDao.deleteByKey(Integer.parseInt(getInput()));
                    if (dee){
                        Log.i("markgor","删除成功");
                    }else {
                        Log.i("markgor","删除失败");
                    }
                }
                break;
            case R.id.searchBtn:
                if (getInput() != null){
                    List<TestDb> testDbList = TestDbBaseDao.searchAll();
                    for (TestDb testDb1 : testDbList){
                        Log.i("markgor","getPrimid="+testDb1.getPrimid()+",getUiname="+testDb1.getUiname());
                    }
                }
                break;
        }
    }

    private String getInput(){
        if (testInput.getText().toString().trim().length()>0){
            return testInput.getText().toString().trim();
        }
        return null;
    }
}
对应的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"
    android:gravity="center"
    tools:context="cn.jxsb.equipment.MainActivity">

    <EditText
        android:id="@+id/testInput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="请输入内容"
        />
    <TextView
        android:id="@+id/insertBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="插入一条数据"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="20dp"
        />
    <TextView
        android:id="@+id/deleteBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="删除一条数据"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="20dp"
        />
    <TextView
        android:id="@+id/searchBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查询数据"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="20dp"
        />

</LinearLayout>

有什么问题欢迎指正,谢谢。

发布了37 篇原创文章 · 获赞 15 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/u012764358/article/details/79154820