Android——SharedPreferences

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();//提交
	
		
	}
}

运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值