开发者

Android - Is there are super comfortable way to store persistent data?

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 {开发者_JAVA百科
     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.


Use Shared Preferences to store your data. Please read this tutorial ---> http://androidandandroid.wordpress.com/2010/07/25/android-tutorial-16/


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 introduced Room, an elegant way to store data in Sqlite using POJOs. Example:

User.java

@Entity
public class User {
    @PrimaryKey
    private int uid;

    @ColumnInfo(name = "first_name")
    private String firstName;

    @ColumnInfo(name = "last_name")
    private String lastName;

    // Getters and setters are ignored for brevity,
    // but they're required for Room to work.
}

UserDao.java

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
           + "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);
}

AppDatabase.java

@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
}

After creating the files above, you get an instance of the created database using the following code:

AppDatabase db = Room.databaseBuilder(getApplicationContext(),
        AppDatabase.class, "database-name").build();
UserDao dao = db.userDao

Time to play!

List<User> users = dao.getAll();
dao.insertAll(users);
// ...

If you use Kotlin (highly recommended) it is still more concise with data objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜