服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - android开发基础教程—SharedPreferences读写

android开发基础教程—SharedPreferences读写

2020-12-30 13:22Android开发网 Android

本文介绍SharedPreferences的读与写的实现思路,感兴趣的朋友可以了解下

复制代码 代码如下:


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
SharedPreferences sp = this.getSharedPreferences("myxml", Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("name", "nanguabing");
editor.putInt("age", 20);
//持久化操作到存储设备
editor.commit();
Toast.makeText(this, "写入sp完成", 1).show();
break;
case R.id.button2:
SharedPreferences sp1 = this.getSharedPreferences("myxml", Context.MODE_PRIVATE);
String name = sp1.getString("name", "nobody");
int age = sp1.getInt("age", 0);
Toast.makeText(this, "name=" + name + ",age=" + age, 1).show();
break;
default:
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}


文件格式:

复制代码 代码如下:


<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">nanguabing</string>
<int name="age" value="20" />
</map>

延伸 · 阅读

精彩推荐