当前位置:首页 > Android > 正文内容

采用SharedPreferences保存用户偏好设置参数和读取设置参数

jsc10年前 (2016-04-05)Android3950

Android SDK支持那些文件存储技术?

1. 使用SharedPreferences保存key-value类型的数据

2. 流文件存储(使用openFileOutput和openFileInput方法,或FileInputStream和FileOutputStream)

3. XML半结构化存储

4. 用JSON保存数组和对象

5.用数据库保存结构化数据

6. 用第三方的面向对象数据库直接保存Java对象。


这篇博文主要介绍用SharedPreferences保存key-value对的步骤和读取设置参数的方法

1. 使用Context.getSharedPreferences方法获取SharedPreferences对象,其中存储key-value的文件的名称有getSharedPreferences方法第一个参数指定。

2. 使用SharedPreference.edit方法获取SharedPreferences.Editor对象。

3. 通过SharedPreference.Editor接口的putXxx方法保存key-value对。

4. 通过SharedPreference.Editor.commit方法提交要保存的key-value对。



实例:SharedPreferences

1366001990_6798.png

MainActivity.java

package com.wwj.setting;

import java.util.Map;

import com.wwj.service.PreferencesService;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends Activity {
    private EditText nameText;        //姓名框
    private EditText ageText;        //年龄框
    private RadioGroup radioGroup;    //单选框组
    
    //业务逻辑类
    private PreferencesService service;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        nameText = (EditText)findViewById(R.id.nameText);
        ageText = (EditText)findViewById(R.id.ageText);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        service = new PreferencesService(this);
        
        Map<String, String> params = service.getPerferences();
        nameText.setText(params.get("name"));
        ageText.setText(params.get("age"));
        radioGroup.check(Integer.valueOf(params.get("sex")));    //设置选择的单选按钮
        
    }
    
    /**
     * 在布局中按钮控件指定的onClick方法
     * @param v
     */
    public void save(View v) {
        String name = nameText.getText().toString();
        String age = ageText.getText().toString();
        Integer sex = radioGroup.getCheckedRadioButtonId();
        service.save(name, Integer.valueOf(age), sex);
        Toast.makeText(getApplicationContext(), R.string.success, 1).show();
    }
    
}

PreferencesService.java

package com.wwj.service;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class PreferencesService {
    private Context context;

    public PreferencesService(Context context) {
        this.context = context;
    }

    /**
     * 保存参数
     * @param name    姓名
     * @param age    年龄    
     * @param sex    性别
     */
    public void save(String name, Integer age, Integer sex) {
        //获得SharedPreferences对象
        SharedPreferences preferences = context.getSharedPreferences("wwj", Context.MODE_PRIVATE);
        Editor editor = preferences.edit();
        editor.putString("name", name);
        editor.putInt("age", age);
        editor.putInt("sex", sex);
        editor.commit();
    }

    /**
     * 获取各项参数
     * @return
     */
    public Map<String, String> getPerferences() {
        Map<String, String> params = new HashMap<String, String>();
        SharedPreferences preferences = context.getSharedPreferences("wwj", Context.MODE_PRIVATE);
        params.put("name", preferences.getString("name", ""));
        params.put("age", String.valueOf(preferences.getInt("age", 0)));
        params.put("sex", String.valueOf(preferences.getInt("sex", 0)));
        return params;
    }
    
    
    
}


布局文件activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/name"/>
    <EditText 
        android:id="@+id/nameText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <TextView 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/age"/>
    <EditText 
        android:id="@+id/ageText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numeric="integer"
        />
    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="性别" >

        <RadioButton
            android:id="@+id/radioButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/male" 
            android:checked="true"/>

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/female" />
    </RadioGroup>
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="save"
        android:text="@string/saveBtn" />
    
</LinearLayout>


扫描二维码推送至手机访问。

版权声明:本文由微小站发布,如需转载请注明出处。

本文链接:https://jsc0.com/post/60.html

分享给朋友:

“采用SharedPreferences保存用户偏好设置参数和读取设置参数 ” 的相关文章

Android中AsyncTask的简单用法

Android中AsyncTask的简单用法

        在开发Android移动客户端的时候往往要使用多线程来进行操作,我们通常会将耗时的操作放在单独的线程执行,避免其占用主线程而给用户带来不好 的用户体验。但是在子线程中无法去操作主线程(UI 线...

Android中使用PULL方式解析XML文件

Android中使用PULL方式解析XML文件

 Pull解析器的运行方式与 SAX 解析器相似。它提供了类似的事件,如:开始元素和结束元素事件,使用parser.next()可以进入下一个元素 并触发相应事件。跟SAX不同的是, Pull解析器产生的事件是一个数字,而非方法,因此可以使用一个s...

【代码】android 调用系统视频录制并生成缩略图

package com.example.videocapture; import android.app.Activity; import android.content.Intent; import android.database.Cursor;...

Android动态布局,并动态为TextView控件设置drawableLeft、drawableRight等属性添加图标

Android动态布局,并动态为TextView控件设置drawableLeft、drawableRight等属性添加图标

注:(图中每一个条目和图标都是由代码动态生成) 代码动态布局,并需要为每一个条目设置图标,此时用到了 android:drawableLeft="@drawable/icon" ...

Android ImageView的scaleType属性与adjustViewBounds属性

Android ImageView的scaleType属性与adjustViewBounds属性

ImageView的scaleType的属性有好几种,分别是matrix(默认)、center、centerCrop、centerInside、fitCenter、fitEnd、fitStart、fitXY android:sca...

Android中从SD卡中/拍照选择图片并进行剪裁的方法

Android中从SD卡中/拍照选择图片并进行剪裁的方法

效果图: 下面是代码的部分,部分是从网路上摘录的,自己整理后当做工具类使用   配置文件:布局很简单,一个ImageButton和一个Button,点击都可以实现图像选择的功能,具体的实现根据大家在实际中...