简体   繁体   中英

Caching JSON (Xamarin C#)

I writing Android app and want professional advice.

I have category with products.

I have JSON with this products.

    Array
(
    [0] => Array
        (
            [post_title] => Яблочный десерт
            [post_excerpt] => Мус топленный шоколад, яблоко в карамели с ореховым тестом.
            [img_url] => http://new.murakami.ua/wp-content/uploads/Untitled-1.jpg
            [visibility] => visible
            [price] => 78.00
            [weight] => 90
            [sku] => 594
        )

    [1] => Array
        (
            [post_title] => Сладкий ролл Филадельфия с клубникой и ананасом
            [post_excerpt] => 
            [img_url] => http://new.murakami.ua/wp-content/uploads/roll_sladkiy2.jpg
            [visibility] => visible
            [price] => 68.00
            [weight] => 100
            [sku] => 846
        )

    [2] => Array
        (
            [post_title] => Тирамису
            [post_excerpt] => Бисквит, сыр креметте, сливки, какао, кофе Lavazza, ликер Triple Sec Volare
            [img_url] => http://new.murakami.ua/wp-content/uploads/Tiramisu.jpg
            [visibility] => visible
            [price] => 59.00
            [weight] => 110
            [sku] => 248
        )

    [3] => Array
        (
            [post_title] => Наполеон   

            [post_excerpt] => Торт из слоёных коржей с заварным кремом.
            [img_url] => http://new.murakami.ua/wp-content/uploads/Napoleon.jpg
            [visibility] => visible
            [price] => 58.00
            [weight] => 140
            [sku] => 633
        )

    [4] => Array
        (
            [post_title] => Ассорти мини чизкейков
            [post_excerpt] => Чизкейк с ванильно-сырным муссом, с фисташковым муссом Баваруа и шоколадным крем-брюле, в основе которых ореховый чизкейк с миндального бисквита и крем-сыра Президент.
            [img_url] => http://new.murakami.ua/wp-content/uploads/535_520-Assorti-CHizkejkov.jpg
            [visibility] => visible
            [price] => 84.00
            [weight] => 130
            [sku] => 141
        )

    [5] => Array
        (
            [post_title] => Шоколадно-авокадовый десерт
            [post_excerpt] => Шоколадный бисквит, слой миндаля, шоколадный мусс с авокадо, сироп Амаретто, шоколад.
            [img_url] => http://new.murakami.ua/wp-content/uploads/SHokoladno-avokadovyj-desert.jpg
            [visibility] => visible
            [price] => 64.00
            [weight] => 100
            [sku] => 225
        )

)

I need to cache it and then show some of fields in UI.

Now I Download it and show in UI,like this.

Downloading:

    string url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=74";
            JsonValue json = await FetchAsync(url2);
 private async Task<JsonValue> FetchAsync(string url)
        {
            System.IO.Stream jsonStream;
            JsonValue jsonDoc;

            using (var httpClient = new System.Net.Http.HttpClient())
            {
                jsonStream = await httpClient.GetStreamAsync(url);
                jsonDoc = JsonObject.Load(jsonStream);
            }

            return jsonDoc;
        }

And Displaying :

 private void ParseAndDisplay(JsonValue json)
    {



        TextView productname = FindViewById<TextView>(Resource.Id.posttittle);
        TextView price = FindViewById<TextView>(Resource.Id.price);
        TextView weight = FindViewById<TextView>(Resource.Id.weight);
        ImageView imagen = FindViewById<ImageView>(Resource.Id.image1);
        ImageButton add = FindViewById<ImageButton> (Resource.Id.add);

        JsonValue firstitem = json[0];
        //Console.Out.WriteLine(firstitem["post_title"].ToString());

        productname.Text = firstitem["post_title"];
        price.Text = firstitem["price"] + " грн";
        weight.Text = firstitem["weight"] + "г";
        var imageBitmap = GetImageBitmapFromUrl(firstitem["img_url"]);
        imagen.SetImageBitmap(imageBitmap);


    }

How can I make a cache for this JSON and don't download this JSON each time , when user goes to product category?

Thank's for help & advice.

You can store a serialized json object as string into the preferences.

The Xamarin.Android equivalent of SharedPreferences is an interface called ISharedPreferences .

You'll want to get an instance of ISharedPreferences and use that to update/change/delete preferences. There are a couple of ways to get an instance of ISharedPreferences:

  • Activity.GetPreferences would get you preferences specific to that activity. Probably not what you want.

  • Context.GetSharedPreferences can get you application level preferences.

  • PreferenceManager.DefaultSharedPreferences will give you an ISharedPreference instance for a given context.

Use it in the same way, and you will be able to easily port Android code across.

For example, to save a string you can do the following:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
ISharedPreferencesEditor editor = prefs.Edit ();
editor.PutString(key, value);
// editor.Commit();    // applies changes synchronously on older APIs
editor.Apply();        // applies changes asynchronously on newer APIs

To read the saved values you can do:

ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences (mContext);
mString = prefs.GetString(key, default_value_to_return_in_case_no_value_is_found);

Where key is of course the same previously used to store the string. Once you have your mString you can deserialize it into any complex json object.

You can also explore the other types of data that you can store (int, bool ...)

Check here https://forums.xamarin.com/discussion/4758/android-shared-preference for more examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM