Android实验九——使用SharedPreferences存储简单数据

完成如下程序(主Activity界面如图1所示):

在图1中点击“参数设置”按钮,启动如图2所示的Activity。在图2中用户输入完用户名后,点击“确定”按钮,将关闭该Activity(此时需要使用SharedPreferences.Editor

保存用户名),主Activity重新回到运行状态,如图3所示(需重写主Activity的生命周期回调方法onStart()或onResume(),完成对SharedPreferences中保存的用户名的读取)。

布局文件

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_welcome"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="216dp"
        android:text="欢迎来到我的家园"
        android:textSize="25dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_set"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"
        android:text="参数设置"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tv_welcome" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

activity_new.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".NewActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="208dp"
        android:text="请输入用户名:"
        android:textSize="25dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/et_name"
        android:layout_width="198dp"
        android:layout_height="53dp"
        android:layout_marginTop="12dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/btn_submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="48dp"
        android:text="确定"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_name" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.example.test9;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    private SharedPreferences preferences;
    private TextView tv_welcome;
    private Button btn_set;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_welcome=findViewById(R.id.tv_welcome);
        preferences= this.getSharedPreferences("usersetting",MODE_PRIVATE);
        tv_welcome.setText("欢迎"+preferences.getString("username"," ")+"来到我的家园");

        btn_set=findViewById(R.id.btn_set);
        btn_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,NewActivity.class);
                //启动指定Activity并等待返回的结果,其中0是请求码,用于标识该请求。
                startActivity(intent);
                MainActivity.this.finish();
            }
        });

    }
}

NewActivity.java

package com.example.test9;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NewActivity extends Activity {

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private Button btn_submit;
    private EditText et_name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new);

        et_name=findViewById(R.id.et_name);
        btn_submit=findViewById(R.id.btn_submit);

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                preferences=getSharedPreferences("usersetting",MODE_PRIVATE);
                editor=preferences.edit();
                //将输入的数据写入SharedPreference
                editor.putString("username",et_name.getText().toString());
                editor.commit();


                Intent intent=new Intent(NewActivity.this,MainActivity.class);
                startActivity(intent);
                NewActivity.this.finish();
            }
        });

    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SharedPreferences提供了一种轻量级的数据存储方式,可以用来存储简单的键值对数据SharedPreferences存储数据是以XML文件的形式保存在设备的本地文件系统中的。 具体的步骤如下: 1. 获取SharedPreferences对象。可以通过Context的getSharedPreferences()方法或Activity的getPreferences()方法获取SharedPreferences对象。 ``` // 通过Context获取SharedPreferences对象 SharedPreferences preferences = getSharedPreferences("my_preferences", Context.MODE_PRIVATE); // 通过Activity获取SharedPreferences对象 SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE); ``` 2. 使用SharedPreferences.Editor对象保存数据。可以通过SharedPreferences的edit()方法获取SharedPreferences.Editor对象,然后使用putXxx()方法存储数据。其中Xxx可以是int、float、boolean、long、String等数据类型。 ``` // 获取SharedPreferences.Editor对象 SharedPreferences.Editor editor = preferences.edit(); // 存储数据 editor.putString("username", "Tom"); editor.putInt("age", 20); editor.putBoolean("isMale", true); // 提交数据 editor.apply(); ``` 3. 使用SharedPreferences对象获取数据。可以使用SharedPreferences的getXxx()方法获取数据。其中Xxx可以是int、float、boolean、long、String等数据类型。 ``` // 获取数据 String username = preferences.getString("username", ""); int age = preferences.getInt("age", 0); boolean isMale = preferences.getBoolean("isMale", false); ``` 在这个示例中,我们通过SharedPreferences存储了用户名、年龄和性别的数据,并通过SharedPreferences获取了这些数据。 需要注意的是,SharedPreferences存储数据是以键值对的形式保存的,其中键是一个字符串,值可以是任意基本类型数据。在存储和获取数据时,需要使用相应的putXxx()和getXxx()方法,并指定键的名称和默认值(可选)。另外,为了保护用户的隐私,建议不要将敏感信息存储SharedPreferences中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值