zoukankan      html  css  js  c++  java
  • android数据存储之SharedPreferences

    一、SharedPreferences简介      
     (1)SharedPreferences是Android平台上一个轻量级的存储类,用来保存应用的一些常用配置,比如Activity状态,Activity暂停时,将此activity的状态保存到SharedPereferences中;当Activity重载,系统回调方法onSaveInstanceState时,再从SharedPreferences中将值取出。
     (2)SharedPreferences提供了java常规的Long、Int、String等类型数据的保存接口。 
     (3)SharedPreferences类似过去Windows系统上的ini配置文件,但是它分为多种权限,可以全局共享访问。
     (4)SharedPreferences最终是以xml方式来保存,整体效率来看不是特别的高,对于常规的轻量级而言比SQLite要好不少,如果真的存储量不大可以考虑自己定义文件格式。xml处理时Dalvik会通过自带底层的本地XML Parser解析,比如XMLpull方式,这样对于内存资源占用比较好。
    二、实例
      (1)Layout中的布局文件main.xml
    <?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        
        <TableRow >
            <TextView 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="姓名:"
                android:textSize="20sp"/>
            <EditText 
                android:id="@+id/name"
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:text=""
                />
        </TableRow>
         <TableRow >
            <TextView 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="年龄:"
                android:textSize="20sp"/>
            <EditText 
                android:id="@+id/age"
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:text=""
                />
        </TableRow>
        
         <Button 
             android:id="@+id/save"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="保存"
             android:textSize="20sp"
             />
         <Button 
             android:id="@+id/show"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="显示"
             android:textSize="20sp"
             />
         <!-- 用于显示存储在SharedPreferences这种的数据 -->
        <TextView 
            android:id="@+id/result"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text=""
            android:textSize="20sp"/>
    
    </TableLayout>

      (2)Activity中的MainActivity.java

    package com.yby.sharedpreferences;
    
    import android.app.Activity;
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
        
        private EditText name,age;
        private Button save,show;
        private TextView result;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            //加载布局文件
            setContentView(R.layout.main);
            //初始化UI控件
            name = (EditText) findViewById(R.id.name);
            age = (EditText) findViewById(R.id.age);
            save = (Button) findViewById(R.id.save);
            show = (Button) findViewById(R.id.show);
            result = (TextView) findViewById(R.id.result);
            //为按钮监听事件
            save.setOnClickListener(listener);
            show.setOnClickListener(listener);
            
        }
        
        private OnClickListener listener = new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //获取SharedPreferences对象,最后会生成一个data.xml文件
          /**
                 *  SharedPreferences数据的四种操作模式
                    Context.MODE_PRIVATE
                    Context.MODE_APPEND
                    Context.MODE_WORLD_READABLE
                    Context.MODE_WORLD_WRITEABLE
                    Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
                    Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.
                    Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.
                    MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.
                    MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入
                 */
                SharedPreferences preferences = MainActivity.this.getSharedPreferences("data", Context.MODE_PRIVATE);
                switch (v.getId()) {
                case R.id.save:
                    //获取Editor对象
                    Editor editor = preferences.edit();
                    //Editor是一个map集合,通过putXXX()向里面塞值,key-value
                    editor.putString("name", name.getText().toString());
                    editor.putInt("age", Integer.parseInt(age.getText().toString()));
                    //此时必须要执行commit(),否则后面无法通过getXXX()来获取对应的值
                    editor.commit();
                    Toast.makeText(MainActivity.this,"保存成功" , Toast.LENGTH_SHORT).show();
                    break;
                case R.id.show:
                    //getXXX(param1,param2) 第一个参数是存的时候的key,第二个是当在文件中找不到对应的key时,给的一个默认的值
                    String name = preferences.getString("name", "null");
                    int age = preferences.getInt("age", 0);
                    //由于我在上面没有给bir这个变量,所以这个会显示出来为bir is null
                    String bir = preferences.getString("bir", "bir is null");
                    //往TextView里面放存储在SharedPreferences中的值
                    result.setText("name:"+name+",age:"+age+",bir:"+bir);
                    break;
                default:
                    break;
                }
            }
        };
    }

      (3)运行项目实现效果

      

       (4)通过SharedPreferences存储的数据保存在 /data/data/PACKAGE_NAME/shared_prefs目录下,可以通过eclipse中的DDMS导出XML文件查看,也可以用命令的方式进行查看

    <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
    <map>
    <string name="name">ffff</string>
    <int name="age" value="12" />
    </map>

    通过命令的方式查看

  • 相关阅读:
    利用服务器部署Web项目
    JavaWeb解决文件上传后项目需要刷新问题 以及 图片过大 文件上传时间延长
    JavaWeb接入支付宝支付
    JavaWeb实现文件上传功能
    Eclipse Server中没有TomCat
    Eclipse 中没有Dynamic web Project 解决办法
    JavaWeb图形验证码
    elasticsearch常用语句
    关于elasticsearch的安装教程和使用方法
    解决el-table渲染卡顿组件
  • 原文地址:https://www.cnblogs.com/yby-blogs/p/4373942.html
Copyright © 2011-2022 走看看