Android - 有没有超级舒适的方式来存储持久数据?
我希望我的数据模型以及 Getters 和 Setters 像一个简单的 Java 类一样设置,让 Eclipse 创建所有的 getters 和 setters,如果我调用它们,我希望数据能够持久存储。有一种使用 SQLiteDatabase 类的方法,但它仍然不如使用简单的 Java 类那么舒服。是否有它的框架。(而且,不仅适用于 android。(我从 Web 框架 Grails 中得到了这个想法)
//Define DataModel
class StackOverflowUser {
private String name;
private int points;
}
//getters, setters...
//store Data persistently in a Database:
dan.setPoints(dan.getPoints()+5);
我不明白为什么这个 OO 语言有这种非常舒适的对象、getter 和 setter 方式来轻松定义数据模型,但是当谈到持久性时,我需要几十个辅助类,这不是一个具体的问题,但我希望你有一个想法。
I want my Data Model and my Getters and Setters set like a simple Java Class, let Eclipse create all the getters and setters and if I call them, I want the Data to be stored persistently. There is a sort of way with SQLiteDatabase Class, but it´s still not as comfortable as if you work with simple Java Classes. Is there are framework for it.(also, not only for android. (I got the Idea from the web framework Grails)
//Define DataModel
class StackOverflowUser {
private String name;
private int points;
}
//getters, setters...
//store Data persistently in a Database:
dan.setPoints(dan.getPoints()+5);
I dont understand why this OO Language has this very comfortable way of objects and getters and setters to easily define a data model, but when it comes to persistence, I need dozens of helper classes. It´s not a concrete problem but I hope you have an idea.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用共享首选项来存储您的数据。请阅读本教程 --->
http://androidandandroid.wordpress.com/2010/07/25/ android-tutorial-16/
Use Shared Preferences to store your data. Please read this tutorial --->
http://androidandandroid.wordpress.com/2010/07/25/android-tutorial-16/
对于少量数据,共享首选项可能是一种选择,但数据类型有限。我启动了开源项目,以在使用它们时消除样板代码( https://github.com/ko5tik/andject )
另一种解决方案是以 JSON 形式存储数据并使用一些数据绑定工具(例如: https://github.com/ko5tik/jsonserializer ) - 也可以存储 JSON 数据
Shared preferences may be an option for small amount of data, but data types are limited. I started opensource project to eliminate boilerplate code while using them ( https://github.com/ko5tik/andject )
Another solution would be storing data in JSON form and use some databinding tool ( like: https://github.com/ko5tik/jsonserializer ) - JSON data can be also stored
Android Jetpack 引入了 Room,这是一种使用 POJO 在 Sqlite 中存储数据的优雅方式。示例:
User.java
UserDao.java
AppDatabase.java
创建上述文件后,您可以使用以下代码获取所创建数据库的实例:
开始玩吧!
如果您使用 Kotlin(强烈推荐),它对于数据对象来说仍然更加简洁。
Android Jetpack introduced Room, an elegant way to store data in Sqlite using POJOs. Example:
User.java
UserDao.java
AppDatabase.java
After creating the files above, you get an instance of the created database using the following code:
Time to play!
If you use Kotlin (highly recommended) it is still more concise with data objects.