在Android中使用SharedPreferences保存简单的数据
16lz
2022-08-01
在Android中保存一些简单的数据,使用SharedPreferences是比较方便的。比如用SharedPreferences保存软件的配置文件等,SharedPreferences实质是把数据写在一个xml文件中。具体实现代码如下; xml布局文件
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".MainActivity" >
- android:id="@+id/btnsave"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/save"
- android:onClick="SaveBtn"
- />
- android:id="@+id/btnread"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/btnsave"
- android:text="@string/read"
- android:onClick="ReadBtn"
- />
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Toast;
- import android.app.Activity;
- import android.content.Context;
- import android.content.SharedPreferences;
- import android.content.SharedPreferences.Editor;
- public class MainActivity extends Activity{
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- public void SaveBtn(View v){ //保存数据
- SharedPreferences sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
- Editor editor = sp.edit();
- editor.putString("username", "用户名:55484946");
- editor.putString("password", "密码:12345678");
- editor.commit();
- Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
- }
- public void ReadBtn(View v){ //读取数据
- SharedPreferences sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
- String str = sp.getString("username", "用户名不存在");
- str += sp.getString("password", null);
- Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show();
- }
- }
更多相关文章
- mybatisplus的坑 insert标签insert into select无参数问题的解决
- python起点网月票榜字体反爬案例
- NPM 和webpack 的基础使用
- 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
- 读取android手机流量信息
- android 使用html5作布局文件: webview跟javascript交互
- 《Android开发从零开始》——25.数据存储(4)
- Android(安卓)多媒体扫描过程(Android(安卓)Media Scanner Proces
- Android系统配置数据库注释(settings.db)