zoukankan      html  css  js  c++  java
  • Android-SharedPreferences

    [返回文件夹]

    SharedPreferences提供一种按“Key=value”的形式进行数据存储

    android.content.SharedPreferences借口所保存的信息仅仅能是一些主要的数据类型,如字符串,整形,布尔型等

    SharedPreferences保存的是配置文件。文件后缀默觉得 *.xml,跟Java中的Properties类一样(仅仅能保存主要的数据类型

    不能保存中文,中文须要转码

    默认情况下。全部配置文件都保存在系统目录中。/data/data/包名/shared prefs下

    Window->show View->Others->File Explorer能够查看系统目录


    如:

    <span style="font-family:SimHei;font-size:18px;">package com.example.testsharedpreferences;
    
    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    
    public class MainActivity extends Activity {
    	private final String FILENAME="potato"; //保存文件名称,最后生成potato.xml文件
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);		
    		SharedPreferences sharedPreferences=super.getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
    		SharedPreferences.Editor edit=sharedPreferences.edit();
    		edit.putString("name", "potato");
    		edit.putInt("age", 22);
    		edit.putBoolean("isStudent", true);
    		edit.commit();
    	
    	}
    }
    </span>

    在系统目录中的/data/data/ com.example.testsharedpreferences/shared prefs下会添加一个 potato.xml文件

    当中,SharedPreferences中保存数据是通过SharedPreferences.Editor接口进行的


    读取SharedPreferences的数据方法例如以下:

    <span style="font-family:SimHei;font-size:18px;">package com.example.testsharedpreferences;
    
    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.util.Log;
    
    public class MainActivity extends Activity {
    	private final String FILENAME="potato"; //保存文件名称。最后生成potato.xml文件
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);		
    		SharedPreferences sharedPreferences=super.getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);
    
    		Log.e("Potato", "Name:"+sharedPreferences.getString("name", "我是默认值"));
    		Log.e("Potato", "Age:"+sharedPreferences.getInt("age", 1));
    		Log.e("Potato", "isStudent:"+sharedPreferences.getBoolean("isStudent", false));
    	
    	}
    }
    </span>




    版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 相关阅读:
    Elasticsearch 快速入门
    Linux 非互联网环境安装依赖包
    linux 安装mysql(rpm文件安装)
    Nginx安装与配置文件nginx.conf详解
    Linux 知识
    MySQL Windows安装连接
    post请求body格式
    MySQL 数据库备份
    SOAP与restful webservice
    大数据架构工具hadoop
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4877194.html
Copyright © 2011-2022 走看看