zoukankan      html  css  js  c++  java
  • Android两种存储用户临时数据的方式比较:Preferences & Bundle

    Preferences 用于当按键Home or Back时保存用户临时输入的数据。

    常常在OnCreate() 和OnStop()函数中使用。

    用法:

    public static final String PREFS_NAME = "MyPrefsFile";
     
    OnCreate() 方法中调用

    // Restore preferences 

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 

    boolean silent = settings.getBoolean("silentMode", false); 

    setSilent(silent); 

    OnStop()函数调用

    // Save user preferences. We need an Editor object to 

    // make changes. All objects are from android.context.Context 

    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 

    SharedPreferences.Editor editor = settings.edit(); 

    editor.putBoolean("silentMode", mSilentMode); 

    // Don't forget to commit your edits!!! 

    editor.commit();

    一、Bundle在API文档的说明

      1.介绍

        用于不同Activity之间的数据传递

      1.重要方法

        clear():清除此Bundle映射中的所有保存的数据。

        clone():克隆当前Bundle

        containsKey(String key):返回指定key的值

        getString(String key):返回指定key的字符

        hasFileDescriptors():指示是否包含任何捆绑打包文件描述符

        isEmpty():如果这个捆绑映射为空,则返回true

        putString(String key, String value):插入一个给定key的字符串值

        readFromParcel(Parcel parcel):读取这个parcel的内容

        remove(String key):移除指定key的值

        writeToParcel(Parcel parcel, int flags):写入这个parcel的内容

    二、实例

      Bundle bundle = new Bundle();  //保存输入的信息  

      bundle.putString("name", info);    

     Intent intent=new Intent(BundleDemo.this,BundleDemo1.class);   

      intent.putExtras(bundle);

    //接受 传递后的值

    Bundle b=getIntent().getExtras();
      //获取Bundle的信息
    String info=b.getString("name");

    总结:

    SharedPreferences是简单的存储持久化的设置,就像用户每次打开应用程序时的主页,它只是一些简单的键值对来操作。它将数据保存在一个xml文件中

    Bundle是将数据传递到另一个上下文中或保存或回复你自己状态的数据存储方式。它的数据不是持久化状态。(类似于Session的用法)。

  • 相关阅读:
    使用SWFUpload无刷新上传图片
    WP多语言
    C#将DataTable转化为List<T>
    Android 多语言
    Android开发 Failed to install *.apk on device 'emulator-5554': EOF
    ASP.NET MVC中将数据从Controller传递到视图
    安装和卸载程序时总是出现2502,2503错误代码的解决方法
    position固定菜单栏
    [position]返回顶部
    [css]后台管理系统布局
  • 原文地址:https://www.cnblogs.com/nidongde/p/2791998.html
Copyright © 2011-2022 走看看