Android---sp存储

sp存储数据类型:boolean,float,int,long,String
数据保存路径:/data/data/packageName/shared_prefs/xxx.xml

可以设置的数据只能是当前应用读取,别的应用不可以
应用卸载时会删除此数据
public class MyLoginDemo extends AppCompatActivity implements View.OnClickListener {

    private EditText et_one;
    private EditText et_two;
    private Button btn_one;
    private Button btn_two;

    private SharedPreferences sp;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_login_demo);

        initView();

        //得到sp对象
        sp=getSharedPreferences("name", MODE_PRIVATE);
    }

    private void initView() {
        et_one=(EditText)findViewById(R.id.et_one);
        et_two=(EditText)findViewById(R.id.et_two);
        btn_one=(Button)findViewById(R.id.btn_one);
        btn_two=(Button)findViewById(R.id.btn_two);
        btn_one.setOnClickListener(this);
        btn_two.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_one:
                save();
                break;
            case R.id.btn_two:
                read();
                break;
        }
    }

    private void read() {//读取

        String username=et_one.getText().toString();
        if(TextUtils.isEmpty(username)){
            Toast.makeText(this, "Input cannot is empty!", Toast.LENGTH_SHORT).show();
            return;
        }
        //通过username读取password
        String password = sp.getString(username, "null");
        if(password.equals("null")){
            Toast.makeText(this, "No corresponding value found", Toast.LENGTH_SHORT).show();
        }else {
            et_two.setText(password);
        }

    }

    private void save() {

        String username=et_one.getText().toString();
        String password=et_two.getText().toString();
        if(TextUtils.isEmpty(username)|| TextUtils.isEmpty(password)){
            Toast.makeText(this, "Input cannot is empty!", Toast.LENGTH_SHORT).show();
            return;
        }
        //保存数据
        //获得Editor对象
        SharedPreferences.Editor editor=sp.edit();
        //记得commit
        editor.putString(username, password).commit();


        Toast.makeText(this, "save success", Toast.LENGTH_SHORT).show();
        et_one.setText("");
        et_two.setText("");
    }
}

原创文章 158 获赞 2 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43616001/article/details/105865619
今日推荐