android实例教程

In this tutorial we’ll use Shared Preferences in our android application to store data in the form of key-value pair.
n

在本教程中,我们将在Android应用程序中使用“ 共享首选项 ”以键值对的形式存储数据。
ñ

Android共享首选项概述 (Android Shared Preferences Overview)

Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application.

共享首选项允许活动和应用程序以键-值对的形式保留首选项,类似于键映射对,即使用户关闭应用程序,该映射也将保留。

Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory().

Android将“共享首选项”设置作为XML文件存储在DATA / data / {application package}目录下的shared_prefs文件夹中。 可以通过调用Environment.getDataDirectory()获得DATA文件夹。

SharedPreferences is application specific, i.e. the data is lost on performing one of the following options:

SharedPreferences是特定于应用程序的,即在执行以下选项之一时数据会丢失:

  • on uninstalling the application关于卸载应用程序
  • on clearing the application data (through Settings)清除应用程序数据时(通过“设置”)

As the name suggests, the primary purpose is to store user-specified configuration details, such as user specific settings, keeping the user logged into the application.

顾名思义,其主要目的是存储用户指定的配置详细信息,例如用户特定的设置,以保持用户登录到应用程序中。

To get access to the preferences, we have three APIs to choose from:

要访问首选项,我们提供了三种API供您选择:

  • getPreferences() : used from within your Activity, to access activity-specific preferencesgetPreferences() :从您的“活动”内部使用,以访问特定于活动的首选项
  • getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferencesgetSharedPreferences() :从您的Activity(或其他应用程序上下文)内部使用,用于访问应用程序级首选项
  • getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference frameworkgetDefaultSharedPreferences() :在PreferenceManager上使用,以获取与Android总体首选项框架协同工作的共享首选项

In this tutorial we’ll go with getSharedPreferences(). The method is defined as follows:

在本教程中,我们将使用getSharedPreferences() 。 该方法定义如下:

getSharedPreferences (String PREFS_NAME, int mode)

getSharedPreferences (String PREFS_NAME, int mode)

PREFS_NAME is the name of the file.

PREFS_NAME是文件名。

mode is the operating mode.

模式是操作模式。

Following are the operating modes applicable:

以下是适用的操作模式:

  • MODE_PRIVATE: the default mode, where the created file can only be accessed by the calling applicationMODE_PRIVATE :默认模式,其中创建的文件只能由调用应用程序访问
  • MODE_WORLD_READABLE: Creating world-readable files is very dangerous, and likely to cause security holes in applicationsMODE_WORLD_READABLE :创建世界可读的文件非常危险,并且可能在应用程序中造成安全漏洞
  • MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and likely to cause security holes in applicationsMODE_WORLD_WRITEABLE :创建可写入世界的文件非常危险,并且可能在应用程序中引起安全漏洞
  • MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loadedMODE_MULTI_PROCESS :即使已加载共享首选项实例,此方法也将检查首选项的修改
  • MODE_APPEND: This will append the new preferences with the already existing preferencesMODE_APPEND :这会将新的首选项附加到已经存在的首选项中
  • MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write ahead logging by defaultMODE_ENABLE_WRITE_AHEAD_LOGGING :数据库打开标志。 设置后,默认情况下将启用预写日志记录

初始化 (Initialization)

We need an editor to edit and save the changes in shared preferences. The following code can be used to get the shared preferences.

我们需要一个编辑器来编辑并保存共享首选项中的更改。 以下代码可用于获取共享的首选项。

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();

储存资料 (Storing Data)

editor.commit() is used in order to save changes to shared preferences.

使用editor.commit()来将更改保存到共享首选项。

editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing longeditor.commit(); // commit changes

检索数据 (Retrieving Data)

Data can be retrieved from saved preferences by calling getString() as follows:

可以通过调用getString()从保存的首选项中检索数据,如下所示:

pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean

清除或删除数据 (Clearing or Deleting Data)

remove(“key_name”) is used to delete that particular value.

remove(“ key_name”)用于删除该特定值。

clear() is used to remove all data

clear()用于删除所有数据

editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key emaileditor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes

项目结构 (Project Structure)

Android共享首选项项目代码 (Android Shared Preferences Project Code)

The activity_main.xml layout consists of two EditText views which store and display name and email. The three buttons implement their respective onClicks in the MainActivity.

activity_main.xml布局由两个EditText视图组成,这些视图存储并显示名称和电子邮件。 这三个按钮在MainActivity实现各自的onClicks。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin" ><Buttonandroid:id="@+id/btnSave"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:onClick="Save"android:text="Save" /><Buttonandroid:id="@+id/btnRetr"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:onClick="Get"android:text="Retrieve" /><Buttonandroid:id="@+id/btnClear"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignRight="@+id/etEmail"android:layout_centerVertical="true"android:layout_alignParentRight="true"android:layout_alignParentEnd="true"android:onClick="clear"android:text="Clear" /><EditTextandroid:id="@+id/etEmail"android:layout_width="match_parent"android:layout_height="wrap_content"android:ems="10"android:hint="Email"android:inputType="textEmailAddress"android:layout_below="@+id/etName"android:layout_marginTop="20dp"android:layout_alignParentRight="true"android:layout_alignParentEnd="true" /><EditTextandroid:id="@+id/etName"android:layout_width="match_parent"android:layout_height="wrap_content"android:ems="10"android:hint="Name"android:inputType="text"android:layout_alignParentTop="true"android:layout_alignLeft="@+id/etEmail"android:layout_alignStart="@+id/etEmail" /></RelativeLayout>

The MainActivity.java file is used to save and retrieve the data through keys.

MainActivity.java文件用于通过键保存和检索数据。

package com.journaldev.sharedpreferences;import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;public class MainActivity extends Activity {SharedPreferences sharedpreferences;TextView name;TextView email;public static final String mypreference = "mypref";public static final String Name = "nameKey";public static final String Email = "emailKey";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);name = (TextView) findViewById(R.id.etName);email = (TextView) findViewById(R.id.etEmail);sharedpreferences = getSharedPreferences(mypreference,Context.MODE_PRIVATE);if (sharedpreferences.contains(Name)) {name.setText(sharedpreferences.getString(Name, ""));}if (sharedpreferences.contains(Email)) {email.setText(sharedpreferences.getString(Email, ""));}}public void Save(View view) {String n = name.getText().toString();String e = email.getText().toString();SharedPreferences.Editor editor = sharedpreferences.edit();editor.putString(Name, n);editor.putString(Email, e);editor.commit();}public void clear(View view) {name = (TextView) findViewById(R.id.etName);email = (TextView) findViewById(R.id.etEmail);name.setText("");email.setText("");}public void Get(View view) {name = (TextView) findViewById(R.id.etName);email = (TextView) findViewById(R.id.etEmail);sharedpreferences = getSharedPreferences(mypreference,Context.MODE_PRIVATE);if (sharedpreferences.contains(Name)) {name.setText(sharedpreferences.getString(Name, ""));}if (sharedpreferences.contains(Email)) {email.setText(sharedpreferences.getString(Email, ""));}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_main, menu);return true;}}

mypreference is the name of the file where the shared preferences key-value pair is stored.

mypreference是存储共享首选项键值对的文件的名称。

The image below shows the final output of our project:

下图显示了我们项目的最终输出:

This brings an end to this tutorial. You can download the project Android Shared Preferences from the below link.

本教程到此结束。 您可以从下面的链接下载项目Android共享首选项

Download Android Shared Preferences Example Project下载Android共享首选项示例项目

翻译自: https://www.journaldev.com/9412/android-shared-preferences-example-tutorial

android实例教程

android实例教程_Android共享首选项示例教程相关推荐

  1. android 类对象的存储,android - 以共享首选项存储和检索类对象

    android - 以共享首选项存储和检索类对象 在Android中,我们可以在共享首选项中存储类的对象,并在以后检索该对象吗? 如果有可能怎么办? 如果不可能做到这一点的其他可能性是什么? 我知道序 ...

  2. 共享首选项中commit()和apply()之间的区别是什么

    我在我的Android应用程序中使用共享首选项. 我正在使用共享首选项中的commit()和apply()方法. 当我使用AVD 2.3时它没有显示错误,但是当我在AVD 2.1中运行代码时, app ...

  3. SD卡读写,首选项,共享首选项

    Android-SD卡读写 adb shell mksdkcard 50m d:\xxx\xxxx.img 挂载/卸载sd卡 <uses-permission android:name=&quo ...

  4. android手机强制关机代码,android – 当应用程序强制关闭或设备重新启动时,共享首选项重置数据...

    我有一个登录屏幕,希望应用程序看起来好像在应用程序关闭/销毁/电话呼叫等后仍然在内部屏幕上"登录". 我有一个首选项对象来保存登录或注册后的值.我在所有关键屏幕onResume() ...

  5. Android studio设置代码风格首选项(Mac与Windows)

    介于Android Studio编程遵循的命名前缀有如下约定,设置Java代码风格的首选项. (1)成员变量的m前缀,如:private Button mTextButton; (2)静态变量的s前缀 ...

  6. linux命令实例教程,Linux xxd命令入门示例教程

    你是否需要使用二进制或十六进制格式显示文件内容? 寻找可以执行此操作的命令行实用程序? 那,你很幸运,因为存在一个名为xxd的命令可以为你做到这一点. 在本教程中,我们将使用一些易于理解的示例来讨论x ...

  7. a标签去下划线 菜鸟教程_HTML下划线标签示例教程

    a标签去下划线 菜鸟教程 HTML provides different styling options for the text. Underlining the HTML text is one ...

  8. android实例教程_Android内部存储示例教程

    android实例教程 Today we will look into android internal storage. Android offers a few structured ways t ...

  9. 如何在“首选项”摘要中显示Android首选项的当前值?

    这必须经常出现. 当用户在Android应用程序中编辑首选项时,我希望他们能够在Preference摘要中查看首选项的当前设置值. 示例:如果我有"丢弃旧邮件"的"首选项 ...

最新文章

  1. IIS发布 MVC 配置
  2. C# 集合类(四):Hashtable
  3. comsol稀物质传递_印刷指南丨印刷油墨传递的影响因素?
  4. 微课堂 | 典典养车COO:暴力运营美学,典典养车如何一年内拿到500万用户(今晚8点开始)...
  5. mysql insert报错_mysql数据库使用insert语句插入中文数据报错
  6. linux之shell
  7. ACL 2018 收录论文 | 如何高效提炼有效信息?
  8. centos 7 mysql随机密码_在centos中安装了mysql5.7之后解决不知道随机的密码的问题...
  9. mysql临时关闭索引功能_MYSQL中常用的强制性操作(例如强制索引)
  10. 转:Java NIO系列教程(一)Java NIO 概述
  11. VMware下安装CentOS
  12. 浅析基于微软SQL Server 2012 Parallel Data Warehouse的大数据解决方案
  13. 小程序中间放大轮播图_微信小程序实现类3D轮播图
  14. 罗技Ghub配置文件压枪编程——仅供学习
  15. Python数据挖掘框架
  16. 软件精选中的Windows软件安装目录,含软件包和安装教程
  17. windows认证密码抓取
  18. Ubuntu下Maven安装和使用
  19. 5G/NR 标识详解之5G-GUTI
  20. PhpSpreadsheet导入

热门文章

  1. VC++网络安全编程范例(2)-创建自签名证书
  2. BZOJ 4033: [HAOI2015]树上染色
  3. Ansible(自动化运维工具--playbook)
  4. jdbcdbcpc3p0
  5. Salesforce删除数据时出现Insufficient privileges的可能原因
  6. vb.net如何发送含双引号的字符串。转义双引号
  7. BZOJ3678: wangxz与OJ
  8. Android中GridView实现互相添加和删除
  9. 2012.12.26 晚 小雨
  10. Asp.Net IIS 管理类(全)