[Xamarin] 透過 IsolatedStorageFile儲存資料(转帖)

本文介绍了在Android应用开发中如何利用IsolatedStorage实现数据的存储与读取,包括存储数据的方法和读取数据的过程。通过简单的示例代码演示了在App被中断时保存状态和恢复状态的功能,与Windows Phone的开发经验相呼应。

開發手機App通常都會遇到想要儲存資料的,舉個例來說,像是

2013-07-15_155114

(圖片來源:http://docs.xamarin.com/guides/android/application_fundamentals/activity_lifecycle)

在android 生命週期中,OnReusme 可能需要把上次狀態讀取出來,在OnStop中因為App被中斷,所以必須把現在狀態寫起來

以方便還原,這時候就會用到這儲存的機制..

看一下官方文件: http://docs.xamarin.com/guides/cross-platform/application_fundamentals/building_cross_platform_applications/part_5_-_practical_code_sharing_strategies


2013-07-15_155430
他直接連結到MSDN-Isolated Storage Overview for Windows Phone 那不就等於方便到爆炸,直接拿Windows Phone 的Code就可以用了..

來介紹一下今天範例..

Screenshot_2013-07-15-15-46-44222

按下儲存資料(btnSave1)的時候,就將EditView(editTextMain)資料寫入,

按下讀取資料(btnRead1)時就會將寫入的資料讀取出來,因為是範例,所以盡量單純點..直接來看Code

儲存資料:

 

var btnSave1 = FindViewById<Button>(Resource.Id.btnSave1);
btnSave1.Click += delegate
{
   IsolatedStorageFile storageFiles = IsolatedStorageFile.GetUserStoreForApplication();
    //如果判斷已經有檔案就把它砍掉
    if (storageFiles.FileExists("UserInfo/data.txt"))
    {
        storageFiles.DeleteFile("UserInfo/data.txt");
    }
    //建立檔案夾
    storageFiles.CreateDirectory("UserInfo");
    StreamWriter fileWriter = new StreamWriter(new IsolatedStorageFileStream("UserInfo/data.txt", FileMode.OpenOrCreate, storageFiles));
    //寫入至目標
    fileWriter.Write(editTextMain.Text);
    fileWriter.Close();
    storageFiles.Dispose();
    Toast.MakeText(this, "Success Save", ToastLength.Short).Show();
};

讀取資料:

var btnRead1 = FindViewById<Button>(Resource.Id.btnRead1);
btnRead1.Click += delegate
{
    IsolatedStorageFile storageFiles = IsolatedStorageFile.GetUserStoreForApplication();
    StreamReader fileReader = null;
    //判斷檔案是否存在
    if (storageFiles.FileExists("UserInfo/data.txt"))
    {
        try
        {
            fileReader = new StreamReader(new IsolatedStorageFileStream("UserInfo/data.txt", FileMode.Open, storageFiles));
            var result = fileReader.ReadToEnd();
            Toast.MakeText(this, result, ToastLength.Long).Show();
            fileReader.Close();
        }
        catch(Exception ex)
        {
            Toast.MakeText(this, "Error:"+ex.Message, ToastLength.Long).Show();
        }
    }
    else
    {
        Toast.MakeText(this, "Error:" + "Sorry我找不到檔案喔!", ToastLength.Long).Show();
    }
};

結果:
Screenshot_2013-07-15-15-46-40

Screenshot_2013-07-15-15-46-44

是不是整個跟在Windows Phone 上面開發經驗一致..真的是很溫馨..

reference:  
 

转载于:https://www.cnblogs.com/whatthehell/p/3444600.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值