Android room 学习

今天记录下对 使用 room 操作数据库的知识
1.添加依赖项(好像需要添加新的版本)

    implementation 'android.arch.persistence.room:runtime:1.1.0-beta2'
    annotationProcessor 'android.arch.persistence.room:compiler:1.1.0-beta2'
    implementation 'android.arch.persistence.room:rxjava2:1.1.0-beta2'

2.添加数据库对应的 表的属性

@Entity
public class User {
    @PrimaryKey
    public int uid;
    public String name;
    public String password;
}

3.添加操作数据的函数

@Dao
public interface UserDao {
    @Query("select * from User")
     List<User> getAll();
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertUser(User user);
    @Delete
    void deleteUser(User user);
}

4.添加数据库

@Database(entities = {User.class},version = 2)
public abstract class UserDatabase extends RoomDatabase {
    public abstract UserDao getUserDao();
}

5.得到 table 对象 和 对应的操作

public class MainActivity extends AppCompatActivity {

    private String TAG = "MainActivity";

    private UserDatabase userDatabase = null;

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

        databaseOperation();
    }


    private void databaseOperation() {
      //得到数据表对象
        userDatabase = Room.databaseBuilder(this, UserDatabase.class, "user.db")
                .allowMainThreadQueries()
                .fallbackToDestructiveMigration().build();
        UserDao mUserDao = userDatabase.getUserDao();


        writeDatabase(mUserDao, 1,"zhang", "123456");
        writeDatabase(mUserDao, 2,"li", "123");
        readDatabase(mUserDao);
    }

    private void readDatabase(UserDao dao) {
        List<User> users = dao.getAll();
        for (User u : users) {
            Log.e(TAG, "get user:" + String.valueOf(u.uid) + "name" + u.name );
        }
    }

    private void writeDatabase(UserDao dao, int uid,String name, String password) {
        User user = new User();
        user.uid = uid;
        user.name = name;
        user.password = password;
        dao.insertUser(user);
    }
}

6.遇到的坑
1.Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/arch/core/executor/AppTool
2.java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you’ve changed sc

文章地址:
1.https://blog.csdn.net/ygzrsno/article/details/80019755
2.http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2017/0728/8278.html(出现的错误及解决方法)
3.https://blog.csdn.net/zhangphil/article/details/78611632?locationNum=3&fps=1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值