android getSharedPreferences()实现本地注册登录 适合新手!()

来源:互联网 发布:手机添加网络怎么设置 编辑:程序博客网 时间:2024/05/01 09:26

SharedPreferences数据的四种操作模式
  • Context.MODE_PRIVATE
  • Context.MODE_APPEND
  • Context.MODE_WORLD_READABLE
  • Context.MODE_WORLD_WRITEABLE
Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.
Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入




该工程分为2个模块和一个登录成功界面

UserLogin 实现SharedPreferences()的读操作

UserResgister 实现SharedPreferences()的写操作

目录结构

--------------------------------------------------



UserLogin.java

public class UserLogin extends Activity {private Context context;private Button btnlogin;private EditText tx_name;private EditText tx_pass;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.login);btnlogin = (Button) findViewById(R.id.btnlogin);tx_name = (EditText) findViewById(R.id.tx_name);tx_pass = (EditText) findViewById(R.id.tx_pass);context = getApplicationContext();}@Overridepublic 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;}public void loginCheck(View v) {SharedPreferences userinfo = context.getSharedPreferences("userinfo",context.MODE_PRIVATE);// 获取了我们的用户配置对象String getname = tx_name.getText().toString();String getpass = tx_pass.getText().toString();//从userinfo文件中读取name和pass的数据,如果没有则赋值为noString name = userinfo.getString("name", "no");String pass = userinfo.getString("pass", "no");// 登录判断if (name.equals(getname)&&pass.equals(getpass)) {//执行跳转Toast.makeText(context, "登录成功,"+name+"欢迎您", 1).show();Intent intent = new Intent(context,userSucc.class);startActivity(intent);}else{Toast.makeText(context, "用户名或密码错误!", 1).show();}}public void register(View v) {Intent intent = new Intent(context, UserRegister.class);startActivity(intent);}}

UserRegister.java

public class UserRegister extends Activity {private EditText tx_name;private EditText tx_pass;private Context context;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.register);tx_name = (EditText) findViewById(R.id.editText1);tx_pass = (EditText) findViewById(R.id.editText2);context = getApplicationContext();}public void register(View v){SharedPreferences userinfo = context.getSharedPreferences("userinfo",context.MODE_PRIVATE);// 获取了我们的用户配置对象Editor edit = userinfo.edit();//启动编辑String namestr = tx_name.getText().toString();String passstr = tx_pass.getText().toString();edit.putString("pass", passstr);edit.putString("name", namestr);edit.commit();// 生成配置文件Toast.makeText(context, "注册成功", 1).show();Intent intent = new Intent(context,UserLogin.class);startActivity(intent);}}


0 0
原创粉丝点击