使用SharedPreferences记住用户名、密码


title: 使用SharedPreferences记住用户名、密码

一、存储数据

第一次登录的时候要记录下登录的用户名和密码。首先新建一个preference 和editor。

        preferences = getSharedPreferences("USERINFO", MODE_PRIVATE);
        editor = preferences.edit();

在点击登录按键并且处理好成功登录信息后就可以对用户名和密码等信息进行保存。

        editor.clear();
        editor.putString("USERNAME", USER_NAME);
        editor.putString("PASSWORD", USER_PASSWORD);
        editor.commit();

二、读取数据并自动登录

        if (!preferences.getString("USERNAME", "").toString().equals("")) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("正在登录....");
            builder.setMessage("请稍后!");
            builder.create().show();
            loginIn(preferences.getString("USERNAME", ""), preferences.getString("PASSWORD", ""));
            AUTO_LOGIN_FLAG = 1;
        }
        else{
            setContentView(R.layout.activity_login);
            loginEditText = (EditText) findViewById(R.id.loginEditTextId);
            pswEditText = (EditText) findViewById(R.id.pswEditTextId);
            loginBtn = (Button) findViewById(R.id.bnLogin);
            loginBtn.setOnClickListener(this);
            loginLL = (LinearLayout) findViewById(R.id.loginLLId);
        }

你可能感兴趣的:(使用SharedPreferences记住用户名、密码)