SP存储

sp存储专门用来存储一些单一的小数据

存储数据的类型 boolean float int long String

数据保存的路径/data/data/xxx(packageName)/shared_prefs/xxx.xml

xml




    

    

    

        

activity中的代码

package com.servicedemo.datastorage;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class Spactivity extends AppCompatActivity {

    private EditText et_sp_key;
    private EditText et_sp_value;
    private SharedPreferences.Editor edit;
    SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spactivity);
        et_sp_key = findViewById(R.id.et_sp_key);
        et_sp_value = findViewById(R.id.et_sp_value);
        sp = getSharedPreferences("godv", Context.MODE_PRIVATE);
        edit = sp.edit();

    }

    public void save(View v) {
        String key = et_sp_key.getText().toString();
        String value = et_sp_value.getText().toString();
        edit.putString(key, value).commit();
        Toast.makeText(Spactivity.this, "保存成功~", Toast.LENGTH_SHORT).show();
    }

    public void read(View v) {
        String key = et_sp_key.getText().toString();
        String string = sp.getString(key, null);
        if(string==null){
            Toast.makeText(Spactivity.this, "没有找到对应的值~", Toast.LENGTH_SHORT).show();
        }else{
            et_sp_value.setText(string);
        }
    }
}

 

你可能感兴趣的:(安卓基础学习,安卓)