【Android基础入门〖14〗】SharedPreferences
来源:互联网 发布:网络编程 博客园 编辑:程序博客网 时间:2024/05/01 15:47
1 简介
SharedPreferences是一种轻量级的数据存储方式,它可以用键值对的方式把简单数据类型(boolean、int、float、long和String)存储在应用程序的私有目录下(data/data/[包名] /shared_prefs/)自己定义的xml文件中
SharedPreferences 创建时可选的模式
MODE_PRIVATE //该文件只能被应用本身访问,写入的内容会覆盖原文件的内容
MODE_APPEND //该模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件
2 具体实现如下:
2.1 主要代码
MainActivity.java
package com.michael.mysharedpreferences;import android.app.Activity;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.widget.TextView;public class MainActivity extends Activity { public static final String SETTINGS_NAME="mysettings"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //开始配置 SharedPreferences //--------------------------------------- //第一个参数为 配置文件名 SharedPreferences spref = getSharedPreferences(SETTINGS_NAME, MODE_PRIVATE); Editor editor=spref.edit(); //保存数据至配置文件 editor.putString("user1", "michael"); editor.putInt("user1_age", 24); editor.putString("user1_sex", "男"); editor.commit(); //--------------------------------------- //结束 //现在开始测试获取数据 //--------------------------------------- String str; str=spref.getString("user1", "default"); str+='\n'; str+=spref.getInt("user1_age", 0); str+='\n'; str+=spref.getString("user1_sex", "default"); str+='\n'; TextView textview=(TextView)findViewById(R.id.textview); textview.setText(str); //--------------------------------------- }}
2.2 布局文件
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textview" android:layout_width="wrap_content" android:layout_height="wrap_content"/></LinearLayout>
3 运行结果
参考 :http://www.oschina.net/question/54100_31831
转载请注明出处!
- 【Android基础入门〖14〗】SharedPreferences
- 【Android基础入门〖14〗】SharedPreferences
- android基础入门数据存储之SharedPreferences(14)
- Android 入门基础(9) ---SharedPreferences
- Android入门:SharedPreferences
- Android入门(5) SharedPreferences
- Android入门之SharedPreferences
- Android基础之SharedPreferences
- Android基础之SharedPreferences
- Android基础之SharedPreferences
- Android入门--SharedPreferences使用总结
- Android基础学习之SharedPreferences
- Android基础--首选项(SharedPreferences)
- 【Android 初学】14、SharedPreferences
- 【Android基础入门〖0〗】AndroidStudio
- 【Android基础入门〖11〗】Fragment
- 【Android基础入门〖13〗】Gallery
- 【Android基础入门〖11〗】Fragment
- 跟ini文件相关的api
- Lua初学
- openam + opendj 安装
- 只允许遍历一遍字符串,找出字符串中第一个只出现一次的字符
- 一个测试电池状态的actiivity
- 【Android基础入门〖14〗】SharedPreferences
- Poj1149 PIGS (经典网络流)
- Sprite Kit 高级场景处理
- 探索推荐引擎内部的秘密,第 3 部分: 深入推荐引擎相关算法 - 聚类
- HDU2795 Billboard
- “黑马程序员“宣传语有奖大征集
- JAVA集合
- Windows Storage Server 2008 R2 Standard(64位)之ASM(Automated Storage Manager)管理
- Linux USB Gadget--设备枚举