Android练级塔Android知识Android开发经验谈

八.Android数据持久化四种方法之一——sharedpref

2016-08-02  本文已影响533人  KaelQ

1.sharedpreferences的存储和读取

<map>
    <string name="username">18883340065</string>
    <string name="password">6b28020697bf708712a824caca5fea5f</string>
</map>

此文件名为自定义,文件存储目录为/data/data/包名/shared_prefs。

SharedPreferences.Editor editor=getSharedPreferences("文件名",模式 ).edit();
editor.putString(键,值);
editor.commist();
SharedPreferences pref=getSharedPreferences("文件名",模式);
Sring name=pref.getString(键,默认值);

2.使用SharedPreferences实现用户自动登录

2.1 思路

  1. 用户注册成功时就将用户名和密码使用SP保存在user.xml中。
  2. 每次启动APP,先启动WelcomeActivity界面,然后进行判断。
  3. 如果user.xml中用户名和密码都存在时,就自动登录。如果用户名密码不存在时,就跳转到登录页面。
  4. 考虑到安全性,存储方式不能直接存明文密码,需要进行加密。于是使用了MD5加密。

2.2 流程

2.3 代码

public class WelcomeActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        //获取用户名密码
        SharedPreferences pref = getSharedPreferences("user", MODE_PRIVATE);
        String username = pref.getString("username", "");
        String password = pref.getString("password", "");
        //进行判定
        Intent intent=new Intent();
        if(!username.equals("")&&!password.equals("")){
            intent.setClass(this,MainActivity.class);
        }else{
            intent.setClass(this,LoginActivity.class);
        }
        this.finish();
        startActivity(intent);
    }
}
    public void onClick(View v) {
        Intent intent1 = new Intent();
        switch (v.getId()) {
            case R.id.login:
                //取数据
                SharedPreferences pref = getSharedPreferences("user", MODE_PRIVATE);
                String username = pref.getString("username", "");
                String password = pref.getString("password", "");
                //对输入的密码进行MD5加密
                String passwordGet=MD5Utils.encode(password_tx.getText().toString());
                //判定
                if (username.equals(username_tx.getText().toString()) && password.equals(passwordGet)) {
                    intent1.setClass(LoginActivity.this, MainActivity.class);
                    startActivity(intent1);
                }else{
                    Toast.makeText(this, password, Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.register:
                intent1.setClass(LoginActivity.this, RegisterActivity.class);
                startActivity(intent1);
                break;
        }
    }
 public void check() {
        //正则表达
        Pattern pattern_user = Pattern.compile("\\d{11}");
        Matcher matcher_user = pattern_user.matcher(username.getText().toString());
        boolean user = matcher_user.matches();
        Pattern pattern_pass = Pattern.compile("\\w{8}");
        Matcher matcher_pass = pattern_pass.matcher(password.getText().toString());
        boolean pass = matcher_pass.matches();
        //存储数据
        if (user && pass) {
            SharedPreferences.Editor editor = getSharedPreferences("user", MODE_PRIVATE).edit();
            editor.putString("username", username.getText().toString());
            password_tx=password.getText().toString();
            password_tx=MD5Utils.encode(password_tx);
            editor.putString("password", password_tx);
            editor.commit();
            Toast.makeText(this, password_tx, Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setClass(RegisterActivity.this, MainActivity.class);
            startActivity(intent);
        } else if (!user) {
            Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
        } else if (!pass) {
            Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_SHORT).show();
        }

    }
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtUser=(TextView)findViewById(R.id.txt_user);
        SharedPreferences pref = getSharedPreferences("user", MODE_PRIVATE);
        String username = pref.getString("username","");
        txtUser.setText(username);

        btnExit=(Button)findViewById(R.id.btn_exit);
        btnExit.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });
    }
package com.luffy.sharedpreferencesdemo;
import java.security.MessageDigest;
public class MD5Utils {
    /**
     * md5加密的工具类
     *
     * @param password
     * @return
     */
    public static String encode(String password) {
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] results = digest.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for(byte b : results){
                int number = b&0xff;
                String hex = Integer.toHexString(number);
                if(hex.length()==1){
                    sb.append("0");
                }
                sb.append(hex);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

3.日常福利

上一篇下一篇

猜你喜欢

热点阅读