National Stadium for Tokyo 2020 Summer Olympics

android: database in 5 minutes

I’m working on an application where I need to save and read data fast and uncomplicated. As I always have had problems with databases and so on. This time I first tried a combination of Gson( and a file in the filesystem. But this was complicated and I had the problem that the file got removed after a special amount of time.

I then came along sugar ( & And this is the solution for all basic database-problems you will ever have and it only needs 5 minutes to integrate.

1. Get the sugar library and include it into your project

Screen Shot 2013-09-08 at 09.27.45


2. Extend your Object:

public class GraphValue extends SugarRecord<GraphValue>

3. Modify the AndroidManifest.xml
I modified the application tag as shown below. You kinda need to set the android:name=”com.orm.SugarApp”.

android:theme="@android:style/Theme.Holo.Light" >
android:value="graph_values.db" />
android:value="2" />
android:value="true" />
android:value="" />
<!--  your <activity> stuff comes here -->

4. Save data

You now can simply call  save() on the object you want to save onto the database.;

5. Read data

If you want to read all values from a table you can do this in one line:

List<GraphValue> allValues = GraphValue.listAll(GraphValue.class);

When you want to specify which data you want to have, then you can use the following code:

GraphValue.find(GraphValue.class, "name = ?", editText.getText().toString())

Here name reffers to the name I gave the variable in the Object class.

6. That’s it.

It took me like 5 minutes to integrate this for the first time, because it’s really very easy, but limited. I had problems to store a Date. The workaround for this is to save it as a String, but I guess for simple data storing this is alright. Have fun with the library :).