Android数据存储之SharePreferences实例

java文件

import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public Button saveData;
    public Button seeData;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         saveData=(Button)findViewById(R.id.save_data);
        seeData=(Button)findViewById(R.id.see_data);
        saveData.setOnClickListener(this);
        seeData.setOnClickListener(this);
    }
    public void onClick(View v){
        switch (v.getId()){
            case R.id.save_data:
                SharedPreferences.Editor editor=getSharedPreferences("data",MODE_APPEND).edit();//写操作,获取SharedPrefeferences.Edito对象。
                editor.putBoolean("is_login",true);//键值对存储
                editor.putString("name","Tom");
                editor.putInt("age",20);
                editor.putBoolean("married",false);
                editor.commit();
                Toast.makeText(MainActivity.this,"hello",Toast.LENGTH_LONG).show();
                break;
            case R.id.see_data:
                SharedPreferences pref=getSharedPreferences("data",MODE_APPEND);/*data为文件名,MODE_APPEND为操作模式。
                int age=pref.getInt("age",0);
                String name=pref.getString("name","00");
                Log.d("MainActivity","name is"+name);
                Log.d("MainActivity","age is"+age);

        }
    }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/save_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="存储"
        />
    <Button
        android:id="@+id/see_data"
        android:text="读取"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值