Codementor Events

Xamarin.Forms : Save Data Locally from a JSON API to the phone.

Published Jul 25, 2018Last updated Jul 31, 2018

Saving data locally is one of the best approaches on mobile phones, and this is helpful to keep data on the phone even though there's no network connection.

There are so many approaches to deal with this one such sqlite etc. but today we are going to tackle an amazing approach called Application.Current.Properties.
It's precise and easy to understand.

Let's get started:

Am going to use JSON placeholer to get a fake testing GET HTTP request Endpoint.
fake json placeholder

Suppose this is the link list of posts
to our JSON data we want to GET in our application with the the following output:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  },
  .
  .
  .
  ]

STEP 1:
We have to first create an Async method in c# which is going to the data or content :

public async void GetPost()
        {
                    //URL for the content or JSON data.
                    string myURL ="https://jsonplaceholder.typicode.com/posts";
                    //Gettting the content from the web
                    var content = await _client.GetStringAsync(myURL);
                    //Test to see the data or content from web in the Debug console.
                    Debug.WriteLine("URL ->  " + myURL);       
         }

STEP 2:
Then let's create a method for saving the data locally :

public static void set_post_data(string json)
        {
            //assigning Application.Current.Properties data 
            Application.Current.Properties["post_data"] = json;


        }

On the above code you have to name the data you are trying to save , for our case we used post_data as the name, but you can rename it according the your context.
Then your code would look like this :

public async void GetPost()
        {
                    //URL for the content or JSON data.
                    string myURL ="https://jsonplaceholder.typicode.com/posts";
                    //Gettting the content from the web
                    var content = await _client.GetStringAsync(myURL);
                  //save data locally 
                    set_post_data(content);
                        
         }

STEP 3:

Make another method to get the JSON saved data , so that you perform any operation you want such JSON deserialization.etc.But as you can see i gave Application.Current.Properties the same name post_data so that it matches or gets the data set with that name.

 public static string get_post_data()
        {
            return Application.Current.Properties["post_data"].ToString();

        }

STEP 4:

Then finally you call get_post_data() wherever you want and manipulate the data, or you can even print it out as below to see if the data is there :

Debug.WriteLine("JSON-"+ get_post_data());

cheers

Discover and read more posts from Lutaaya Huzaifah Idris
get started
post comments3Replies
SpiritChrusher
4 years ago

Thank you very much!! This is simple, short and works perfect!

iosman
6 years ago

wow great information totally love it buddy.

Lutaaya Huzaifah Idris
6 years ago

Thanks for the appreciation. Kindly like my post please.