zoukankan      html  css  js  c++  java
  • SharedPreferences的基本数据写入和读取

    1、布局

    1. <?xml version="1.0" encoding="utf-8"?>
    2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    3. android:layout_width="match_parent"
    4. android:layout_height="match_parent"
    5. android:orientation="vertical">
    6. <Button
    7. android:id="@+id/btn"
    8. android:layout_width="match_parent"
    9. android:layout_height="wrap_content"
    10. android:text="我是一个按钮" />
    11. <Button
    12. android:id="@+id/btn1"
    13. android:layout_width="match_parent"
    14. android:layout_height="wrap_content"
    15. android:text="恢复数据吧少年" />
    16. </LinearLayout>


    2、java文件

    1. package lpc.com.project631;
    2. import android.app.Activity;
    3. import android.content.SharedPreferences;
    4. import android.os.Bundle;
    5. import android.view.View;
    6. import android.widget.Button;
    7. import android.widget.Toast;
    8. /**
    9. * Created by Administrator on 2016/1/7.
    10. */
    11. public class MainActivity1 extends Activity implements View.OnClickListener{
    12. /**
    13. * oncreate方法里很简单,只有两个按钮,绑定了OnClick方法
    14. * */
    15. @Override
    16. protected void onCreate(Bundle savedInstanceState) {
    17. super.onCreate(savedInstanceState);
    18. setContentView(R.layout.activity_main);
    19. Button button = (Button) findViewById(R.id.btn);
    20. Button button1 = (Button) findViewById(R.id.btn1);
    21. button.setOnClickListener(this);
    22. button1.setOnClickListener(this);
    23. }
    24. /**
    25. * 根据不同的按钮,触发不同的逻辑,
    26. * */
    27. @Override
    28. public void onClick(View v) {
    29. switch (v.getId()){
    30. case R.id.btn:
    31. SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
    32. editor.putString("name","刘朋程");
    33. editor.putInt("age",28);
    34. editor.apply();
    35. break;
    36. case R.id.btn1:
    37. SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);
    38. String name = pref.getString("name","李莉");
    39. int age = pref.getInt("age",27);
    40. Toast.makeText(MainActivity1.this,"我的名字是" + name + "我的年龄是" +
    41. age,Toast.LENGTH_SHORT).show();
    42. break;
    43. default:
    44. break;
    45. }
    46. }
    47. }





  • 相关阅读:
    常见邮件服务器(接收服务器和发送邮件服务器)地址
    Linux下搭建SVN服务器(CentOS)
    macBook下更新python
    画画练习20180627
    如何用Photoshop画一个发光金币(unity游戏素材教程)
    Python+VSCode+Git 学习总结
    如何在MFC DLL中向C#类发送消息
    MFC信号量使用指南
    回归cnBlogs
    Web自动化测试框架Watir(基于Ruby)
  • 原文地址:https://www.cnblogs.com/liupengcheng/p/5126307.html
Copyright © 2011-2022 走看看