码迷,mamicode.com
首页 > 移动开发 > 详细

Android数据保存之SharedPreference

时间:2015-05-27 10:05:47      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:数据保存   android   sharedpreference   

SharedPreference非常适合用来保存零散的简单的数据,如用户名和密码等

package com.test.storage;

import android.app.Activity;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.os.Bundle;

import android.view.View;

import android.widget.TextView;

public class SharePreferenceDemo extends Activity{

    private TextView et_name;

    private TextView et_password;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    // TODO Auto-generated method stub

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        SharedPreferences sp = getSharedPreferences("info",MODE_PRIVATE);

    //获取数据 第一个参数为存储的字符串的值,第二个参数是设置没取到对应的数据时,默认显示的值

        String name = sp.getString("name""");

        String password = sp.getString("password""");

        et_name = (TextViewthis.findViewById(R.id.name);

        et_password = (TextViewthis.findViewById(R.id.password);

        et_name.setText(name);

        et_password.setText(password);

    }

    public void click(View v){

    //路径在data/data/程序标示包名/shared_prefs/

    //不用为文件添加后缀名,添加也是无效的.数据是保存在xml中。

        String name = et_name.getText().toString().trim();

        String password = et_password.getText().toString().trim();

         SharedPreferences sp = getSharedPreferences("info"MODE_PRIVATE);

     //获取sp的编辑器

         Editor editer = sp.edit();

      //通过编辑器存放数据

         editer.putString("name", name);

         editer.putString("password", password);

         //提交,保存的数据需要提交才能生效。

        editer.commit();

    }

}

Android数据保存之SharedPreference

标签:数据保存   android   sharedpreference   

原文地址:http://blog.csdn.net/ning_xian_hong/article/details/46042241

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!