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(https://code.google.com/p/google-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 (https://github.com/satyan/sugar & http://satyan.github.io/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
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”.
<application android:name="com.orm.SugarApp" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.Holo.Light" > <meta-data android:name="DATABASE" android:value="graph_values.db" /> <meta-data android:name="VERSION" android:value="2" /> <meta-data android:name="QUERY_LOG" android:value="true" /> <meta-data android:name="DOMAIN_PACKAGE_NAME" android:value="your.package.name" /> <!-- your <activity> stuff comes here --> </application>
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 :).