SharedPreferences作业

安卓作业:

使用SharedPreference将姓名和年龄信息保存到文件,然后再读取

1.主要xml文件代码:

<EditText

android:id="@+id/name"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="请输入姓名:"/>

<EditText

android:id="@+id/age"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="请输入年龄:"/>

<LinearLayout

android:orientation="horizontal"

android:layout_width="wrap_content"

android:layout_height="wrap_content">

<Button

android:id="@+id/write"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="写入"/>

<Button

android:id="@+id/read"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="读取" />

</LinearLayout>

 

2.java部分代码

@Override

protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activit

      xingming = (EditText)findViewById(R.id.name);

      nianling=(EditText)findViewById(R.id.age);

      xieru=(Button)findViewById(R.id.write);

      qudu=(Button)findViewById(R.id.read);

      xieru.setOnClickListener(new View.OnClickListener() {

          @Override

          public void onClick(View v) {

                 String name=xingming.getText().toString();

                 String age = nianling.getText().toString();

                 savaToPrefs(name,age);

                 //显示

                 Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_LONG).show();

         }

        private boolean savaToPrefs(String name,String age) {

               SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);

               SharedPreferences.Editor edit = preferences.edit();

               edit.putString("name",name);

               edit.putString("age",age);

               edit.apply();

               return true;

                 }

});

duchulai.setOnClickListener(new View.OnClickListener() {

       @Override

       public void onClick(View v) {

             readFromprefs();

       }

       private void readFromprefs() {

            SharedPreferences preferences1 =getSharedPreferences("data",MODE_PRIVATE);

            String name = preferences1.getString("name","");

            String age = preferences1.getString("age","");

            Toast.makeText(MainActivity.this,"姓名:"+name+" "+"年龄是:"+age,Toast.LENGTH_LONG).show();

            xingming.setText("");

            nianling.setText("");

       }

  });

}

}

转载于:https://www.cnblogs.com/qiuqiuhui/p/6833094.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值