1. 程式人生 > >Android基礎_資料儲存二_SharedPreferences儲存

Android基礎_資料儲存二_SharedPreferences儲存

SharedPreferences是使用鍵值對的方式來儲存資料的。也就是說當儲存一條資料的時候,需要給這條資料提供一個對應的鍵,這樣在讀取資料的時候就可以通過這個鍵把相應的值取出來。而且SharedPreferences還支援多種不同的資料型別儲存,如果儲存的資料型別是整型,那麼讀取出來的資料也是整型的,儲存的資料是一個字串,讀取出來的資料仍然是字串。

儲存資料

想要使用sharedPreferences來儲存資料,首先需要獲取sharedPreferences物件。Android提供了3中方式:

① Context類中的getSharedPreferences()方法

此方法接收兩個引數,第一個引數用於指定SharedPreferences檔案的名稱,如果指定的檔案不存在則會建立一個,SharedPreferences檔案都是存放在/data/data/<package name>/shared_prefs/目錄下的。第二個引數用於指定操作模式,主要有兩種模式可以選擇,MODE_PRIVATE和MODE_MULTI_PROCESS。

MODE_PRIVATE:是預設的操作模式,和直接傳入0效果是相同的,表示只有當前的應用程式才可以對這個SharedPreferences檔案進行讀寫。

MODE_MULTI_PROCESS:是用於會有多個程序中對同一個SharedPreferences檔案進行讀寫的情況。

② Activity類中的getPreferences()方法

這個方法和Context中的getSharedPreferences()方法很相似,不過它只接收一個操作模式引數,因為使用這個方法時會自動將當前活動的類名作為SharedPreferences的檔名。

③ PreferenceManager類中的getDefaultSharedPreferences()方法

這是一個靜態方法,它接收一個Context引數,並自動使用當前應用程式的包名作為字首來命名SharedPreferences檔案。

得到了SharedPreferences物件之後,就可以開始向SharedPreferences檔案中儲存資料了,主要可以分為三步實現。
1. 呼叫SharedPreferences物件的edit()方法來獲取一個SharedPreferences.Editor物件。
2. 向SharedPreferences.Editor物件中新增資料,比如新增一個布林型資料就使用putBoolean方法,新增一個字串則使用putString()方法,以此類推。
3. 呼叫commit()方法將新增的資料提交,從而完成資料儲存操作。

例子:

private void saveDataBySharedPreferences(){
    SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
    editor.putString("Name", "戚東亮");
    editor.putInt("Age", 21);
    editor.commit();
}

讀取資料

SharedPreferences物件中提供了一系列的get方法用於對儲存的資料進行讀取,每種get方法都對應了SharedPreferences。這些get方法都接收兩個引數,第一個引數是鍵,傳入儲存資料時使用的鍵就可以得到相應的值了,第二個引數是預設值,即表示當傳入的鍵找不到對應的值時,會以什麼樣的預設值進行返回。

例子:

private void readDataBySharedPreferences(){
    SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
    String name = pref.getString("Name", "");
    int age = pref.getInt("Age", 0);
    showRead.setText("姓名:" + name + "年齡:" + age);
}


下面我們利用SharedPreferences儲存方式來實現記住密碼的功能

MainActivity.java

package com.example.testfile;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
	
	Button login;
	CheckBox checkBox;
	EditText userName, userPassword;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initObjects();
		initPassword();
	}
	
	private void initObjects(){
		login = (Button) findViewById(R.id.xml_login);
		checkBox = (CheckBox) findViewById(R.id.xml_remember);
		userName = (EditText) findViewById(R.id.xml_userName);
		userPassword = (EditText) findViewById(R.id.xml_userPassword);
		login.setOnClickListener(this);
	}
	
	private void initPassword(){
		SharedPreferences pref = getSharedPreferences("Password", MODE_PRIVATE);
		boolean remember = pref.getBoolean("remember", false);
		if(remember){
			userName.setText(pref.getString("userName", ""));
			userPassword.setText(pref.getString("userPassword", ""));
			checkBox.setChecked(true);
		}
	}

	@Override
	public void onClick(View v) {
		//我們就把正確密碼當成123
		if(userPassword.getText().toString().equals("123")){
			SharedPreferences.Editor editor = getSharedPreferences("Password", MODE_PRIVATE).edit();
			if(checkBox.isChecked()){
				editor.putString("userName", userName.getText().toString());
				editor.putString("userPassword", userPassword.getText().toString());
				editor.putBoolean("remember", true);
			}else{
				editor.clear();
			}
			editor.commit();
			Toast.makeText(MainActivity.this, "登陸成功", Toast.LENGTH_SHORT).show();
			finish();
		}else{
			userPassword.setText("");
			Toast.makeText(MainActivity.this, "密碼錯誤", Toast.LENGTH_SHORT).show();
		}
	}
	
	
	
}	


activity_main.xml

<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testfile.MainActivity" >

    <TableLayout 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:stretchColumns="1">
        
        <TableRow android:gravity="center_vertical">
            <TextView android:text="使用者名稱"/>
            <EditText 
                android:id="@+id/xml_userName"
          	    android:maxLines="1"/>
        </TableRow>
        
        <TableRow android:gravity="center_vertical">
            <TextView android:text="密碼"/>
            <EditText 
                android:id="@+id/xml_userPassword"
                android:maxLines="1"
                android:inputType="textPassword"/>
        </TableRow>
        
        <CheckBox android:id="@+id/xml_remember"/>
        
        <Button 
            android:id="@+id/xml_login"
            android:text="登陸"/>
        
    </TableLayout>

</RelativeLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testfile"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />

    <!--往sdcard中寫入資料的許可權 -->
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
	<!--在sdcard中建立/刪除檔案的許可權 -->
	<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"></uses-permission>
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


相關推薦

Android基礎_資料儲存_SharedPreferences儲存

SharedPreferences是使用鍵值對的方式來儲存資料的。也就是說當儲存一條資料的時候,需要給這條資料提供一個對應的鍵,這樣在讀取資料的時候就可以通過這個鍵把相應的值取出來。而且SharedPreferences還支援多種不同的資料型別儲存,如果儲存的資料型別是整型

Android基礎_資料儲存_檔案儲存

檔案儲存在Android中最基本的一種儲存方式,它不對儲存內容進行任何格式化處理,只是將資料原封不動地儲存到檔案當中,因此它適合儲存一些簡單的檔案和二進位制內容。Context類中提供了一個openFileOutput ()方法,可以用於將資料儲存到指定的檔案中。這個方法接

Android基礎資料儲存(SharedPreference)

Android資料持久化是說在斷電後資料不會丟失,而根據儲存位置和實現方式一般有3種方式,這裡說sharedpreferences: 一,sharedpreferences儲存 該種方式是在應用獨有目錄data/data/[packgename]/shared_prefs/下

python基礎—基本資料型別(set 集合,深淺拷貝)

1、基礎資料型別彙總補充 str int list bool dict tuple 2、集合 set {} 可變的資料型別,(不可雜湊)裡面的元素必須是不可變的資料型別,無序,不重複 以下是集合最重要的兩點:   去重,把一個列表變成集合,就自動去重了。   關係測試,測試兩組資料之前的

android基礎--列表資料View重新整理動畫

該效果類似於iPhone中View的切換動畫效果 效果一: 效果二: 效果三: 效果四: 效果五(迴旋效果一): 效果六(迴旋效果二): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Android基礎_頁面佈局_LinearLayout(線性佈局)

LinearLayout線性佈局有兩種,即水平佈局、垂直佈局。LinearLayout中屬性android:orientation設定佈局方式。 android:orientation="horizo

Android基礎_頁面佈局_碎片(Fragment)

有些佈局可能在手機上看起來很漂亮,但是拿到螢幕比較大的橫屏平板上面,有些控制元件可能會遭到拉伸,嚴重影響使用者體驗,作為一個合格的開發人員我們應該兼顧這兩種情況,所以在Android3.0之後,Android引入了碎片的概念,它可以讓介面更好的在平板上展示。在Android

Android中Json資料解析()--使用Gson、Jackson和FastJson解析Json資料

/**-----------------Jackson資料解析----------------------------*/ private static ObjectMapper mObjectMapper; private static JsonGenerator mJsonGenerator; pr

Android基礎_通知(Notification)

通知(Notification)是Android系統中比較有特色的一個功能,當某個應用程式希望向使用者發出一些提示資訊,而該應用程式又不在前臺執行時,就可以藉助通知來實現。發出一條通知後,手機最上方的狀態列中會顯示一個通知的圖示,下拉狀態列後可以看到通知的詳細內容。通知可以

Android基礎_頁面佈局_TableLayout(表格佈局)

表格佈局模型以行列的形式管理子控制元件,每一行為一個TableRow的物件,當然也可以是一個View的物件。TableRow可以新增子控制元件,每新增一個為一列。 TableLayout屬性: android:collapseColumns:將TableLayout裡面指定

Android基礎_活動_啟動模式

瞭解了活動的生命週期就必須瞭解一下活動的啟動模式,活動的啟動並沒有看起來startActivity(new Intent(A.this, B.class))那麼簡單。 活動的啟動模式分為4種:stan

Android基礎()資料儲存1.SharedPreferences儲存

SharedPreferences經常用來儲存一些預設歡迎語,使用者登入名和密碼等簡單資訊,一般用於儲存量小的資訊 exampleHelper.java import android.content.Context; import android.content

Android基礎()資料儲存3.ContentProvider儲存

ContentProvider,Android四大元件之一,主要用於不同程式間的資料互動功能 Uri(通用資源識別符號 Universal Resource Identifer),代表資料操作的地址,每一個ContentProvider釋出資料時都會有唯一的地址

Android應用開發-資料儲存和介面展現()

SQLite資料庫 // 自定義類MyOpenHelper繼承自SQLiteOpenHelper MyOpenHelper oh = new MyOpenHelper(getContext(), "school.db", null, 1); // 獲取資料庫物件,如果資料庫不存在,會自動建立

請問叉樹等資料結構的物理儲存結構是怎樣的?

  請問二叉樹等資料結構的物理儲存結構是怎樣的?   好吧,咱們書上說了,一般兩種儲存方式: 1. 以完全二叉樹的形式用連續空間的陣列儲存; 2. 以連結串列形式儲存,即各個資料之間儲存了相關的資料的指標地址!  如果回答就是這樣,那麼我想大家也不費那神了,直接洗洗睡吧? 咱們能不能深入點: 

Python爬蟲_資料儲存

文章目錄 HTML正文抽取 多媒體檔案抽取 Email提醒 HTML正文抽取 HTML正文儲存主要分為兩種格式:JSON和CSV 儲存為JSON 需求:抽取小說標題、章節、章節名稱

資料):hive分桶及抽樣查詢、自定義函式、壓縮與儲存

一、分桶及抽樣查詢 1.分桶表資料儲存         分割槽針對的是資料儲存路徑(HDFS中表現出來的便是資料夾),分桶針對的是資料檔案。分割槽提供一個隔離資料和優化查詢的便利方式。不過,並非所有的資料集都可形成合理的分割槽,特別是當資料要

Android五種資料儲存方式之SQLite資料庫儲存 載入SD卡資料庫 sql操作 事務 防止SQL注入

資料庫 前言 資料庫儲存 資料庫建立 內建儲存資料庫 外接儲存資料庫 編寫DAO 插入操作 更新操作 刪除操作 查詢操作

Android五種資料儲存方式之檔案儲存 內部儲存 外部儲存 檔案讀取儲存操作封裝

檔案儲存 前言 檔案儲存 記憶體 內部儲存 外部儲存 內部儲存操作 API 讀寫操作 外部儲存操作 公共目錄 私有目錄

計算系統基礎-第二章資料的表示和儲存-總結

                      一數制和編碼 (1)“轉換”的概念在資料表示中的反映         (2)資訊的二進位制編碼   (3)數值資料的表示   (4)