Shared Preferences - SharedPreferences

1. Shared Preferences-SharedPreferences

(1) Overview
Some applications need to save configuration information, such as whether to turn on the sound effect switch, whether to save the last entered user name and password when logging in. Android provides SharedPreferences (shared preferences) for these types of applications. Shared preferences are suitable for applications with a small amount of data and data are saved in the form of key/value pairs.

(2) Common classes/interfaces
1. SharedPreferences interface
function: This interface defines methods for shared preference operations and an important internal interface: Editor.

2. Editor interface
function: This interface defines the methods of storing and deleting data.

(3) Common methods
1. context.getSharedPreferences(String fileName, int mode);
Function: Create an object of the implementation class of the SharedPreferences interface. The

first parameter - fileName: specifies the file name for saving and reading shared preference data. The file is stored in the data/data/packageName/shared_prefs folder. The above folders in the current project can be found through the file-explorer view in the DDMS view in eclipse. Default filename: classname.xml.

The second parameter - mode: the access authority of the shared preference file, is set by the following constants:

MODE_WORLD_PRIVATE: private attribute, only this project can access the .xml file specified by the first parameter.

MODE_WORLD_READABLE: Allow other projects to read the contents of the xml file in this project.

MODE_WORLD_WRITEABLE: Allows other projects to write data to the .xml file in this project.

—————————Save data ————————————
2. Related methods of shared preference file storage:

1)Editor.putInt(String key,int value)
Function: store the data of type int with the key name key

2)Editor.putFloat(String key,float value)
Function: store data of type float with the key name key

3)Editor.putString(String key,String value)
Function: Store data of type String with the key name key

4)Editor.putBoolean(String key,Boolean value)
Function: Store the data of type Boolean with the key name key

5)Editor.putLong(String key,long value)
Function: store data of type long with the key name key

6)Editor.remove(String key)
Role: remove the key/value pair with the key name key

7)Eidtor.commit()
Role: submit changes, save results
Tip: Only after this method is executed, the data stored by the above put method can be truly effective.

 


—————————Get data ————————————
3. Related methods for file reading such as shared preferences (the following methods are all subordinate to the implementation class of the SharedPreferences interface)

1)int getInt(String key,int defValue)
Function: Get the data of type int whose key name is key. If there is no key, you can set a default value: defValue

2)boolean getBoolean(String key,Boolean defValue)
Function: Get the data of type boolean whose key name is key. If there is no key, you can set a default value: defValue

3)float getFloat(String key,float defValue)
Function: Get the data of type float whose key name is key. If there is no key, you can set a default value: defValue

4)long getLong(String key,long defValue)
Function: Get the data of type long whose key name is key. If there is no key, you can set a default value: defValue

5)String getString(String key,String defValue)
Function: Get the data of String type whose key name is key. If there is no key, you can set a default value: defValue


 

 

 

Case:

 

package com.jxust.day06_05_sharedpreferencesdemo;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	EditText metId, metPwd;
	SharedPreferences mSp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		setListener();
		readData();
	}

	private void readData() {
		mSp = getSharedPreferences("login", MODE_PRIVATE);
		String id = mSp.getString("id", "");
		String password = mSp.getString("password", "");
		metId.setText(id);
		metPwd.setText(password);
	}

	private void setListener() {
		findViewById(R.id.btnLogin).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String id = metId.getText().toString();
				if(TextUtils.isEmpty(id)){
					metId.setError("Number cannot be empty!");
					return;
				}
				String password = metPwd.getText().toString();
				if(TextUtils.isEmpty(password)){
					metPwd.setError("Password cannot be empty!");
					return;
				}
				mSp  = getSharedPreferences("login", MODE_PRIVATE);
				Editor editor = mSp.edit(); //A reference variable of type Editor will be generated
				editor.putString("id", id);
				editor.putString("password", password);
				editor.commit();
				Toast.makeText(MainActivity.this, "Login complete!", 3000).show();
			}
		});
		findViewById(R.id.btnExit).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void initView() {
		metId = (EditText) findViewById(R.id.etId);
		metPwd = (EditText) findViewById(R.id.etPwd);
	}

}

 

 

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="login number" />

        <EditText
            android:id="@+id/etId"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="2-10 characters" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="login password" />

        <EditText
            android:id="@+id/etPwd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="2-10 characters"
            android:password="true" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:text="login" />

        <Button
            android:id="@+id/btnExit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_weight="1"
            android:text="退出" />
    </LinearLayout>

</LinearLayout>

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326778574&siteId=291194637