Data Storage tutorial, basic samples are included
SDK Version:
M3 - Data Storage Methods
- Preferences Preferences is a lightweight mechanism to store and retrieve key-value pairs of primitive data types.
- Files You can store your data in files on your mobile phone, or in a removable storage medium.
- Databases Android Api supports SQLite databases. All databases, SQLite and others, are stored on the device in /data/data/package_name/databases.
- Network You can also use the Internet to store and receive data, whether it's an SQLite database, or just a simple textfile.
Examples
Preferences
- // Restore preferences
- SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
"PREFS_NAME" is a String, for instance "myData"(.xml). You should know that it stores key- value pairs in .xml format.
- // Save preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
- SharedPreferences.Editor editor = settings.edit();
- // Don't forget to commit your edits!!!
- editor.commit();
That is it.
Files
Writing to the SD Card:
- // Reading it back..
Writing to files with Serialization / writing Objects to file:
- oos.writeObject(this); oos.close();
- // Reading it back..
- Flow f = (Flow) ois.readObject();
Network
You can also use Internet to store your data. Here's an example code how can you upload your file(s) to you remote web server:
- HttpRequest request = new HttpRequest("http://host/some_path");
- Part[] parts = { new StringPart("param_name", "value"), new FilePart(f.getName(), f) };
- filePost.setEntity( new MultipartRequestEntity(parts, filePost.getParams()) );
- HttpClient client = new HttpClient();
- int status = client.executeMethod(filePost);
Database
Storing your data in databases are not that simple like store key-value pairs in Preferences. That's why I'm going to show you the Database method in a next tutorial.




