Android之Sharedprefences的数据储存

package com.example.mirana.myapplication;

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 MainActivity extends AppCompatActivity {
    private SharedPreferences sharedPreferences;///
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText=findViewById(R.id.editText);
        sharedPreferences=getSharedPreferences("test",Context.MODE_PRIVATE);//
 }
    public void  write(View view){/
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putString("test",editText.getText().toString());
        editor.commit();
        Toast.makeText(this, "储存ok", Toast.LENGTH_SHORT).show();
    }
    public void read(View view){
        String str=sharedPreferences.getString("test","");
        editText.setText(str);
    }
}

首先要定义一个SharedPrefenced对象,然后在初始化函数里面进行注册即得到一个SharedPrefences对象,并传入名字和模式。

在储存数据的时候需要SharedPrefence类中的Editor对象,并实例化出该类对象,再调用该对象输入对应类型数据,并提交。

读取的时候要定义一个String类型的变量来储存所读取的数据,注意格式

String str=sharedPreferences.getString("test","");

test为键,后面用的是“”。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_41967600

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值