SharedPreferences (接口)保存的数据类似于 配置信息格式的数据 简单的key-value对
实例:
通过SharedPreferences保存用户名和密码:
package com.example.login;
import com.example.loginservice.LoginService;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button btn1;
private CheckBox cb1;
private EditText edt1;
private EditText edt2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(Button)findViewById(R.id.btn1);
cb1=(CheckBox)findViewById(R.id.cb1);
edt1=(EditText)findViewById(R.id.edit1);
edt2=(EditText)findViewById(R.id.edit2);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void login(View v){
String username=edt1.getText().toString().trim();
String password=edt2.getText().toString().trim();
if("".equals(password)||"".equals(username))
{
Toast.makeText(MainActivity.this, "用户名或者密码不能为空!", 0).show();;
}
else
{
if(cb1.isChecked())
{
LoginService.saveUserInfo(this, username, password);
Toast.makeText(MainActivity.this, "保存用户信息成功!", 0).show();
}
if("123".equals(username)&&"123".equals(password))
{
Toast.makeText(MainActivity.this, "登陆成功!", 0).show();
}
else
Toast.makeText(MainActivity.this, "登陆失败!", 0).show();
}
}
}
package com.example.loginservice;
import android.R.bool;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class LoginService {
public static void saveUserInfo(Context context,String username,String password){
SharedPreferences sp=context.getSharedPreferences("config", Context.MODE_PRIVATE);//接口 通过Context提供的getSharedPreferences方法创建实例
Editor editor=sp.edit();//获取Editor对象
editor.putString("username", username);//写入数据
editor.putString("password", password);
editor.commit();//提交
}
}
运行结果: