安卓开发-SharedPreference应用实例

安卓开发-SharedPreference应用实例

SharedPrefernce多用于配置文件的使用,此文用账号密码来做讲解

1、创建一个工程,并建立一个简单的UI,如图

代码如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<EditText
    android:id="@+id/qq"
    android:inputType="number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="输入QQ号码"/>
<EditText
    android:id="@+id/pwd"
    android:inputType="textPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="输入密码"/>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <CheckBox
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="记住密码"/>
</LinearLayout>
<Button
    android:onClick="login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="登录"/>
</LinearLayout>

2、编写核心逻辑代码:

public class MainActivity extends AppCompatActivity {
private EditText qq;
private EditText pwd;
private CheckBox checkbox;
private SharedPreferences sp;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    qq=(EditText)findViewById(R.id.qq);
    pwd=(EditText)findViewById(R.id.pwd);
    checkbox=(CheckBox)findViewById(R.id.checkbox);
    sp=getSharedPreferences("config",MODE_PRIVATE);
    String num=sp.getString("qq","");
    String password=sp.getString("pwd","");
    qq.setText(num);
    pwd.setText(password);
}
//这里为登录按钮绑定的方法
public void login(View view){
    String q=qq.getText().toString().trim();//使用字符串q来获取qq号码的值
    String p=pwd.getText().toString().trim();
    if (checkbox.isChecked()){
        Editor editor=sp.edit();
        editor.putString("qq",q);
        editor.putString("pwd",p);
        editor.apply();
    }
    else{

    }
}
}

使用sharedpreference的步骤:

  1. 创建sharedpreference对象:

    SharedPreference sp=getSharedPreferences("config",MODE_PRIVATE);//MODE_PRIVATE可以使用0代替
    
  2. 获取编辑器:

    Editor editor=sp.edit();
    
  3. 写入数据:

     editor.putString("qq",q);
    
  4. 提交:

    editor.apply();//也可以使用editor.commit(),但不推荐
    
  5. 回显数据:

    String num=sp.getString("qq","");//使用sp.getxxx来获取key为qq的数据
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值