dcsimg
September 27, 2016
Hot Topics:

Data Storage Using Xamarin

  • June 3, 2015
  • By Uma Narayanan
  • Send Email »
  • More Articles »

Introduction

In this article, we will look at the various options of saving data when developing mobile applications with Xamarin. Xamarin is a tool that helps to create applications where one code can be used across different mobile platforms like Android, IOS, and Windows to name a few. The important thing to remember is in all these platforms there are certain platform-specific features that should be kept separate from the generic code. In this article, the examples are based on Android; however, the same can be leveraged for both IOS & Windows.

Overview

Data is the key component in any application, whether it's mobile or any other application. Because the data storage and processing capabilities in mobile applications are limited as compared to a web-based application, it's more important to understand when to use which storage option to ensure the application's performance is enhanced.

Data Storage Options

The options can be mainly categorized in three ways: key value, files, and database. We will discuss each of these options and also discuss the scenarios where these can be used.

Key Value or Preferences

This is basically data stored in key value pair. A key value pair is also called a preference. Let's understand with the help of a scenario. Say in a mobile application the user is navigating through different pages. Saving the last browsed page in an application can be done with a key value pair. This can be used to save a small subset of data.

The following code is an example to save the last page accessed by the user. Line 1 in the code snippet gets the context for the preference container. In Line 2, it gets the preference in the edit mode, Line 3 adds the key, and Line 4 saves the data.

1. var contextPref = Application.Context.GetSharedPreferences
      ("DemoApp",FileCreationMode.Private);
2. var contextEdit = contextPref.Edit();
3. contextEdit.PutString("lastAccessedPage", "3");
4. contextEdit.Commit();

File

A file is an object to store data like texts or images. You would store those data in files that are completely read from start to end. There are two kinds of file storage available: 'internal' and 'external'.

Internal storage is specific to an application and is on the device where the application is installed. If the application is uninstalled, the files are all deleted.

The next code gives an example of storing data in an 'internal' file location: private to the application.

 1. string path = Application.Context.FilesDir.Path;
 2. var filePath = Path.Combine(path, "test.txt");
 3. System.IO.File.WriteAllText(filePath, "Hello World");

Line 1 gets the application's file path. Line 3 writes the data to a file.

 4. System.IO.File.ReadAllText(filePath);

Line 4 below reads the data from the file location.

The 'external' storage is a location outside of the installed application. The file, when externally stored, is accessible from outside the application also. In other words, the file can be accessed from other applications. This again can be further categorized into two categories:

Public files: Files such as images that can be shared publicly and should not be deleted even if your application gets uninstalled. To save the file as a public file, use the following:

Android.OS.Environment.GetExternal
   StoragePublicDirectory

to retrieve the path to store the file. (Editor's note: The preceding line should not be broken.)

Private files: Files that are available for other applications to use but will be removed if the application gets uninstalled. To save the file as a public file but private to the application, use:

Application.Context.GetExternalFilesDir

Database

Android and IOS provide an built-in database named 'SQL-Lite'. Let's take an example of a system that posts messages on the company web site. The company also has a mobile app version of the site. In the mobile app, we create a local database that stores the latest 10-15 messages published on the company's web site. In this case, the app does a sync periodically and saves the messages locally in the device's database. The reason it saves only the latest messages is because over a period of time the database will grow and reach a storage limitation.

The following code explains how to create a database and table, and perform basic operations.

 1. string path = Application.Context.FilesDir.Path;
 2. var pathToDatabase = Path.Combine(path,
       "db_messages.db");
 3. SQLiteDatabase sqlDB = SQLiteDatabase.
       OpenOrCreateDatabase(pathToDatabase,null );>

Lines 1-3 create and open the database connection.

 4. string createTbl = "CREATE Table Messages
       (_ID INTEGER PRIMARY KEY, message TEXT) ";
 5. sqlDB.ExecSQL(createTbl);
 6. ContentValues values = new ContentValues();
 7. values.Put("_ID", 1);
 8. values.Put("message", "test message");
 9. sqlDB.Insert("Messages", null, values);

Lines 4-5 create a table in the database. Lines 6-9 insert records to the table.

10. Android.Database.ICursor cursor =
       sqlDB.RawQuery("SELECT * FROM Messages", null);
11. string p="";
12. StartManagingCursor(cursor);
13.
14. if (cursor.MoveToFirst())
15.    {
16.       do
17.       {
18.          p += cursor.GetInt(cursor.GetColumnIndex("_ID"))
               + cursor.GetString(cursor.GetColumnIndex
               ("message"));
19.       } while (cursor.MoveToNext());
20.    }
21.    StopManagingCursor(cursor);
22. cursor.Close();

Line 10 creates a cursor for all the rows from the 'Messages' table that was created in Lines 4-5. Line 12 opens the cursor and Line 14 points the cursor to the first record. Lines 16-19 loop through the cursor and get the data from the fields. Lines 21-22 stop and close the cursor.

Summary

In this article, we saw the various ways to save information in mobile applications. The different ways suit different scenarios. Key-Value helps when storing the application and user preferences setting. Files can be used to store images or unstructured data, and the database is mainly used to save structured data.

References

http://developer.xamarin.com/guides/cross-platform/application_fundamentals/data/part_1_introduction/

http://developer.xamarin.com/recipes


Tags: database, Windows, data, Android, IOS, Storage Optimization, Storage, Xamarin, Xamarin.Mobile, SQL Light




Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel