greendao入門案例(crud)

greendao入門案例(crud)


一、gradle配置

二、初始化數據庫

三、編寫crud操作

四、效果圖


一、gradle配置

  • 項目級gradle中做如下配置
buildscript {
    ext{
        greendao_version = '3.2.2'
        schema_version=1
    }
   
    dependencies {
        classpath "org.greenrobot:greendao-gradle-plugin:$greendao_version"
    }
}
  • app的gralde中做如下配置
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao'
android {
   ....
}

greendao {
    //數據庫的版本號
    schemaVersion schema_version
    //設置DaoMaster、DaoSession、Dao包名,也就是要放置這些類的包的全路徑。
    daoPackage 'com.itplus.greendaodemo.entity.greendao'
    //設置DaoMaster、DaoSession、Dao目錄
    targetGenDir 'src/main/java'
}
dependencies {
    ...
    api "org.greenrobot:greendao:$greendao_version"
}
  • 點擊 “🔨”按鈕重新編譯gradle , 自動生成以下文件
    在這裏插入圖片描述

二、初始化數據庫

public class MyApp extends Application {
    public static final String DB_NAME = "itplus.db";
    private DaoSession mDaoSession;
    private static MyApp appInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        appInstance = this;
        initGreenDao();
    }

    private void initGreenDao() {
        // 初始化數據庫信息
        DaoMaster.DevOpenHelper devdOpenHelper = new DaoMaster.DevOpenHelper(this, DB_NAME);
        Database db = devdOpenHelper.getWritableDb();
        mDaoSession = new DaoMaster(db).newSession();
    }

    public static MyApp getAppInstance() {
        return appInstance;
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }
}
  • 創建數據庫的操作接口及實現
    在這裏插入圖片描述
public interface StudentDaoService {
    /**
     * 新增一條學生數據
     *
     * @param student
     * @return
     */
    boolean addStudentInfo(Student student);

    /**
     * 通過id查詢一條記錄
     *
     * @param id
     * @return
     */
    Student findStudentById(Long id);

    /**
     * 查詢所有記錄
     *
     * @return
     */
    List<Student> findAll();

    /**
     * 修改一條信息
     *
     * @param student
     * @return
     */
    boolean modifyStudentInfo(Student student);

    /**
     * 刪除一條信息
     *
     * @param id
     * @return
     */
    boolean deleteStudentInfo(Long id);
}
public class StudentDaoServiceImpl implements StudentDaoService {

    private final StudentDao mStudentDao;

    public StudentDaoServiceImpl() {
        mStudentDao = MyApp.getAppInstance().getDaoSession().getStudentDao();
    }

    @Override
    public boolean addStudentInfo(Student student) {
        long result = mStudentDao.insert(student);
        return result > 0;
    }

    @Override
    public Student findStudentById(Long id) {
        return mStudentDao.loadByRowId(id);
    }

    @Override
    public List<Student> findAll() {
        return mStudentDao.loadAll();
    }

    @Override
    public boolean modifyStudentInfo(Student student) {
        try {
            mStudentDao.update(student);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean deleteStudentInfo(Long id) {
        try {
            mStudentDao.deleteByKey(id);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}


三、編寫crud操作

  • 佈局
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="addStudentInfo"
            android:text="插入一條數據" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="findStudentById"
            android:text="查詢一條數據" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="findAll"
            android:text="查詢所有數據" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="modifyStudentInfo"
            android:text="修改一條數據" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="deleteStudentInfo"
            android:text="刪除一條數據" />
    </LinearLayout>
</ScrollView>
  • 測試界面
public class MainActivity extends AppCompatActivity {

    public static final String TAG = MainActivity.class.getSimpleName();
    private StudentDaoService mStudentDaoService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mStudentDaoService = new StudentDaoServiceImpl();
    }

    public void addStudentInfo(View view) {
        boolean isOk = mStudentDaoService.addStudentInfo(new Student("李小龍", 20));
        Toast.makeText(this, "新增數據" + (isOk ? "成功" : "失敗"), Toast.LENGTH_SHORT).show();
        Log.d(TAG, "新增數據" + (isOk ? "成功" : "失敗"));
    }

    public void findStudentById(View view) {
        Student student = mStudentDaoService.findStudentById(1L);
        if (student != null) {
            Log.d(TAG, "查詢結果: " + student.toString());
        } else {
            Toast.makeText(this, "沒有查詢到相關記錄", Toast.LENGTH_SHORT).show();
        }
    }

    public void findAll(View view) {
        List<Student> studentList = mStudentDaoService.findAll();
        if (studentList!=null&&studentList.size()>0){
            for (Student student : studentList) {
                Log.d(TAG, "查詢結果: " + student.toString());
            }
        }else {
            Toast.makeText(this, "沒有查詢到相關記錄", Toast.LENGTH_SHORT).show();
        }
    }

    public void modifyStudentInfo(View view) {
        Student student = new Student(1L,"魯班", 18);
        boolean updateResult = mStudentDaoService.modifyStudentInfo(student);
        Toast.makeText(this, "修改數據" + (updateResult ? "成功" : "失敗"), Toast.LENGTH_SHORT).show();
        Log.d(TAG, "修改數據" + (updateResult ? "成功" : "失敗"));
    }

    public void deleteStudentInfo(View view) {
        boolean deleteResult = mStudentDaoService.deleteStudentInfo(1L);
        Toast.makeText(this, "刪除數據" + (deleteResult ? "成功" : "失敗"), Toast.LENGTH_SHORT).show();
        Log.d(TAG, "刪除數據" + (deleteResult ? "成功" : "失敗"));
    }
}


四、效果圖

在這裏插入圖片描述

在這裏插入圖片描述


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章