Android的登录/注册共享preferences [英] Android login/registration with shared preferences
问题描述
我是新来的Android。我在做一个应用程序为大学考试。我必须做一个旅行社的应用程序。我想管理才能与共享preferences用户会话保存基本信息和最终旅行用户预订。我找不到,结合注册和登录形式在网络上的例子。我写这篇code,但它不工作。它不显示任何错误。我想我写的不是逻辑。我想先注册,并与我在登记表给的信息登录。谢谢你的帮助。
这是我的Login.java:
包com.example.trip;进口android.content.Context;
进口android.content.Intent;
进口android.os.Bundle;
进口android.support.v7.app.ActionBarActivity;
进口android.view.Menu;
进口android.view.MenuInflater;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Toast;公共类扩展登录{ActionBarActivity公共静态android.content.Shared preferences共享preferences = NULL;私有静态最后弦乐preFER_NAME = NULL;按钮buttonLogin;的EditText txtUsername,txtPassword;//用户会话管理器类
UserSession会议;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.login); 按钮switchButton =(按钮)findViewById(R.id.buttonReg);
switchButton.setOnClickListener(新View.OnClickListener(){ @覆盖
公共无效的onClick(视图v){
意向意图=新意图(Login.this,Reg.class);
startActivity(意向); }
});
//用户会话管理器
会话=新UserSession(getApplicationContext()); //获取电子邮件,密码输入文本
txtUsername =(EditText上)findViewById(R.id.txtUsername);
txtPassword =(EditText上)findViewById(R.id.txtPassword); Toast.makeText(getApplicationContext(),
用户登录状态:+ session.isUserLoggedIn()
Toast.LENGTH_LONG).show();
//用户登录按钮
buttonLogin =(按钮)findViewById(R.id.buttonLogin); 共享preferences = getShared preferences(preFER_NAME,Context.MODE_PRIVATE);
//登录按钮单击事件
buttonLogin.setOnClickListener(新View.OnClickListener(){ @覆盖
公共无效的onClick(查看为arg0){ //从EditText上获取用户名,密码
字符串username = txtUsername.getText()的toString()。
。字符串密码= txtPassword.getText()的toString(); //如果验证用户名,密码是充满
如果(username.trim()长度()方式> 0&放大器;&放大器; password.trim()长度()方式> 0){ 如果(共享preferences.contains(名字))
{
字符串的uname =(共享preferences).getString(名,); } 如果(共享preferences.contains(电子邮件))
{
字符串uEmail =(共享preferences).getString(电子邮件,); } 对象的uname = NULL;
对象uEmail = NULL;
如果(username.equals(UNAME)及&放大器; password.equals(uEmail)){ session.createUserLoginSession(UNAME,
uEmail); //开始MainActivity
意图I =新意图(getApplicationContext(),MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //添加新的标志,开始新的活动
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(ⅰ); 完(); }其他{ //用户名/密码不匹配和放大器;
Toast.makeText(getApplicationContext(),
用户名/密码不正确,
Toast.LENGTH_LONG).show(); }
}其他{ //用户没有输入的用户名或密码
Toast.makeText(getApplicationContext(),
请输入用户名和密码
Toast.LENGTH_LONG).show(); } }
});
}
公共布尔onCreateOptionsMenu(菜单菜单){
MenuInflater吹气=新MenuInflater(本);
inflater.inflate(R.menu.main,菜单);
返回true;
}
@覆盖
公共布尔onOptionsItemSelected(菜单项项){
INT ID = item.getItemId();
开关(ID){
案例R.id.MENU_1:
意图intent1 =新意图(这一点,Login.class);
this.startActivity(intent1);
打破;
案例R.id.MENU_2:
意图intent2 =新意图(这一点,MainActivity.class);
this.startActivity(intent2);
打破;
默认:
返回super.onOptionsItemSelected(项目);
} 返回true;
}
}
这是UserSession.java:
包com.example.trip;进口的java.util.HashMap;进口android.content.Context;
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.content.Shared preferences.Editor;公共类UserSession {
//共享preferences参考
共享preferences preF;//为共享preferences编辑器参考
编辑器编辑;//上下文
上下文_context;//共享preferences模式
INT PRIVATE_MODE = 0;//共享preferences文件名
公共静态最后弦乐preFER_NAME =AndroidExample preF;//所有共享preferences键
公共静态最后弦乐IS_USER_LOGIN =IsUserLoggedIn;//用户名(请可变公众从外部访问)
公共静态最后弦乐KEY_NAME =名;//电子邮件地址(请可变公众从外部访问)
公共静态最后弦乐KEY_EMAIL =电子邮件;//构造
公共UserSession(上下文的背景下){
this._context =背景;
preF = _context.getShared preferences(preFER_NAME,PRIVATE_MODE);
编辑= pref.edit();
}//创建登录会话
公共无效createUserLoginSession(对象的uname,对象uEmail){
//存储登录值TRUE
editor.putBoolean(IS_USER_LOGIN,真); //在preferences存储名称
editor.putString(KEY_NAME,(串)的uname); //在preferences存储电子邮件
editor.putString(KEY_EMAIL,(字符串)uEmail); //提交更改
editor.commit();
}/ **
*检查登录方法将检查用户的登录状态
*如果假时,将用户重定向到登录页面
*否则做任何事
* * /
公共布尔checkLogin(){
//检查登录状态
如果(!this.isUserLoggedIn()){ //用户没有登录重定向他登录活动
意图I =新意图(_context,Login.class); //关闭从堆栈中的所有活动
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //添加新的标志,开始新的活动
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //凝视登录活动
_context.startActivity(ⅰ); 返回true;
}
返回false;
}/ **
*获取存储会话数据
* * /
公众的HashMap<字符串,字符串> getUserDetails(){ //使用HashMap中存储用户凭据
HashMap的<字符串,字符串>用户=新的HashMap<字符串,字符串>(); // 用户名
user.put(KEY_NAME,pref.getString(KEY_NAME,NULL)); //用户电子邮件ID
user.put(KEY_EMAIL,pref.getString(KEY_EMAIL,NULL)); //回报用户
返回用户;
}/ **
*清除会话的详细信息
* * /
公共无效logoutUser(){ //清除从共享preferences所有用户数据
editor.clear();
editor.commit(); //注销后重定向用户MainActivity
意图I =新意图(_context,MainActivity.class); //关闭所有的活动
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //添加新的标志,开始新的活动
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //凝视登录活动
_context.startActivity(ⅰ);
}
//检查登录
公共布尔isUserLoggedIn(){
返回pref.getBoolean(IS_USER_LOGIN,FALSE);
}
}
这是MainActivity.java:
公共类MainActivity扩展ActionBarActivity {@覆盖
保护无效的onCreate(捆绑savedInstanceState)
{
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
}公共布尔onCreateOptionsMenu(菜单菜单){
MenuInflater吹气=新MenuInflater(本);
inflater.inflate(R.menu.main,菜单);
返回true;
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
INT ID = item.getItemId();
开关(ID){
案例R.id.MENU_1:
意图intent1 =新意图(这一点,Login.class);
this.startActivity(intent1);
打破;
案例R.id.MENU_2:
意图intent2 =新意图(这一点,MainActivity.class);
this.startActivity(intent2);
打破;
默认:
返回super.onOptionsItemSelected(项目);
} 返回true;
}
}
这是我的Reg.java:
包com.example.trip;进口android.content.Intent;
进口android.content.Shared preferences;
进口android.content.Shared preferences.Editor;
进口android.os.Bundle;
进口android.support.v7.app.ActionBarActivity;
进口android.view.Menu;
进口android.view.MenuInflater;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Toast;
进口android.view.View.OnClickListener;公共类注册扩展ActionBarActivity {共享preferences共享preferences;
编辑器编辑;
按钮buttonReg2;
的EditText txtUsername,txtPassword,txtEmail;
UserSession会议;@覆盖
保护无效的onCreate(捆绑savedInstanceState){ super.onCreate(savedInstanceState);
的setContentView(R.layout.reg);txtUsername =(EditText上)findViewById(R.id.Name);
txtPassword =(EditText上)findViewById(R.id.txtPassword);
txtEmail =(EditText上)findViewById(R.id.Email);
buttonReg2 =(按钮)findViewById(R.id.buttonReg2);//创建的信息的共享preference文件将被存储
//第一个参数是文件和第二的名称模式,0是私模共享preferences = getShared preferences(寄存器,0);
//获取编辑器中的文件进行编辑
编辑=共享preferences.edit();buttonReg2.setOnClickListener(新View.OnClickListener(){ 公共无效的onClick(视图v){
字符串名称= txtUsername.getText()的toString()。
。字符串email = txtEmail.getText()的toString();
。字符串传递= txtPassword.getText()的toString(); 如果(txtUsername.getText()长()< = 0){
Toast.makeText(Reg.this,输入名称,Toast.LENGTH_SHORT).show();
}
否则,如果(txtEmail.getText()长()< = 0){
Toast.makeText(Reg.this,输入电子邮件,Toast.LENGTH_SHORT).show();
}
否则,如果(txtPassword.getText()长()< = 0){
Toast.makeText(Reg.this,输入密码,Toast.LENGTH_SHORT).show();
}
其他{ //像现在我们在字符串信息。让它们存储与编辑器的帮助
editor.putString(姓名,姓名);
editor.putString(电子邮件,电子邮件);
editor.putString(txtPassword,PASS);
editor.commit();} //提交值 //保存值旁开后活动
意图OB =新意图(Reg.this,Login.class);
startActivity(OB); }
});
} 公共布尔onCreateOptionsMenu(菜单菜单){
MenuInflater吹气=新MenuInflater(本);
inflater.inflate(R.menu.main,菜单);
返回true;
} @覆盖
公共布尔onOptionsItemSelected(菜单项项){
INT ID = item.getItemId();
开关(ID){
案例R.id.MENU_1:
意图intent1 =新意图(这一点,Login.class);
this.startActivity(intent1);
打破;
案例R.id.MENU_2:
意图intent2 =新意图(这一点,MainActivity.class);
this.startActivity(intent2);
打破;
默认:
返回super.onOptionsItemSelected(项目);
} 返回true;
}
}
在MainActivity的XML code:
<?XML版本=1.0编码=UTF-8&GT?;
< TableLayout的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=顶
机器人:shrinkColumns =0
机器人:stretchColumns =1> <的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/ destinazione/> <的EditText
机器人:layout_width =match_parent
机器人:layout_height =match_parent
安卓的inputType =TEXT/>
< /&的TableRow GT; <的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/签入/> <的EditText
机器人:layout_width =match_parent
机器人:layout_height =match_parent
安卓的inputType =日期/>
< /&的TableRow GT; <的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/结帐/> <的EditText
机器人:layout_width =match_parent
机器人:layout_height =match_parent
安卓的inputType =日期/>
< /&的TableRow GT; <的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/ viaggiatori/> <的EditText
机器人:layout_width =match_parent
机器人:layout_height =match_parent
安卓的inputType =号/>
< /&的TableRow GT; <的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/颗星/> <微调
机器人:ID =@ + ID /飞旋
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:项=@阵列/颗星/>
< /&的TableRow GT; <按钮
机器人:ID =@ + ID / buttonFind
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=@字符串/ buttonFind/> < / TableLayout>
中的XML code登录表单:
<?XML版本=1.0编码=UTF-8&GT?;
< TableLayout的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=顶
机器人:shrinkColumns =0
机器人:stretchColumns =1> <的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/ txtUsername/> <的EditText
机器人:ID =@ + ID / txtUsername
机器人:layout_width =match_parent
机器人:layout_height =match_parent
安卓的inputType =TEXT/>
< /&的TableRow GT; <的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/ txtPassword/> <的EditText
机器人:ID =@ + ID / txtPassword
机器人:layout_width =match_parent
机器人:layout_height =match_parent
安卓的inputType =textPassword/>
< /&的TableRow GT; <按钮
机器人:ID =@ + ID / buttonLogin
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=@字符串/ buttonLogin/> <按钮
机器人:ID =@ + ID / buttonReg
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=@字符串/ buttonReg/> < / TableLayout>
这是XML code代表登记表:
<?XML版本=1.0编码=UTF-8&GT?;
< TableLayout的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=顶
机器人:shrinkColumns =0
机器人:stretchColumns =1> <的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/名称/> <的EditText
机器人:ID =@ + ID /名称
机器人:layout_width =match_parent
机器人:layout_height =match_parent
安卓的inputType =TEXT/>
< /&的TableRow GT; <的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/邮件/> <的EditText
机器人:ID =@ +帐号/电邮
机器人:layout_width =match_parent
机器人:layout_height =match_parent
安卓的inputType =textEmailAddress/>
< /&的TableRow GT;
<的TableRow
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:重力=fill_horizontal | center_vertical> <的TextView
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:重力=fill_horizontal | center_vertical
机器人:文字=@字符串/ txtPassword/> <的EditText
机器人:ID =@ + ID / txtPassword
机器人:layout_width =match_parent
机器人:layout_height =match_parent
安卓的inputType =textPassword/>
< /&的TableRow GT; <按钮
机器人:ID =@ + ID / buttonReg2
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:文字=@字符串/ buttonReg2/> < / TableLayout>
这是工作code,试试吧。
MainActivity.java
进口android.content.Intent;
进口android.os.Bundle;
进口android.support.v7.app.ActionBarActivity;
进口android.view.Menu;
进口android.view.MenuInflater;
进口android.view.MenuItem;公共类MainActivity扩展ActionBarActivity {@覆盖
保护无效的onCreate(捆绑savedInstanceState)
{
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
}公共布尔onCreateOptionsMenu(菜单菜单){
MenuInflater吹气=新MenuInflater(本);
inflater.inflate(R.menu.main,菜单);
返回true;
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
INT ID = item.getItemId();
开关(ID){
案例R.id.menu1:
意图intent1 =新意图(这一点,Login.class);
this.startActivity(intent1);
打破;
案例R.id.menu2:
意图intent2 =新意图(这一点,MainActivity.class);
this.startActivity(intent2);
打破;
默认:
返回super.onOptionsItemSelected(项目);
} 返回true;
}
}
Reg.java
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.content.Shared preferences.Editor;
进口android.os.Bundle;
进口android.support.v7.app.ActionBarActivity;
进口android.view.Menu;
进口android.view.MenuInflater;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Toast;公共类注册扩展ActionBarActivity {共享preferences共享preferences;
编辑器编辑;
按钮buttonReg2;
的EditText txtUsername,txtPassword,txtEmail;
UserSession会议;@覆盖
保护无效的onCreate(捆绑savedInstanceState){ super.onCreate(savedInstanceState);
的setContentView(R.layout.reg);txtUsername =(EditText上)findViewById(R.id.Name);
txtPassword =(EditText上)findViewById(R.id.txtPassword);
txtEmail =(EditText上)findViewById(R.id.Email);
buttonReg2 =(按钮)findViewById(R.id.buttonReg2);//创建的信息的共享preference文件将被存储
//第一个参数是文件和第二的名称模式,0是私模。共享preferences = getApplicationContext()getShared preferences(注册,0);
//获取编辑器中的文件进行编辑
编辑=共享preferences.edit();buttonReg2.setOnClickListener(新View.OnClickListener(){ 公共无效的onClick(视图v){
字符串名称= txtUsername.getText()的toString()。
。字符串email = txtEmail.getText()的toString();
。字符串传递= txtPassword.getText()的toString(); 如果(txtUsername.getText()长()< = 0){
Toast.makeText(Reg.this,输入名称,Toast.LENGTH_SHORT).show();
}
否则,如果(txtEmail.getText()长()< = 0){
Toast.makeText(Reg.this,输入电子邮件,Toast.LENGTH_SHORT).show();
}
否则,如果(txtPassword.getText()长()< = 0){
Toast.makeText(Reg.this,输入密码,Toast.LENGTH_SHORT).show();
}
其他{ //像现在我们在字符串信息。让它们存储与编辑器的帮助
editor.putString(姓名,姓名);
editor.putString(电子邮件,电子邮件);
editor.putString(txtPassword,PASS);
editor.commit();} //提交值 //保存值旁开后活动
意图OB =新意图(Reg.this,Login.class);
startActivity(OB); }
});
} 公共布尔onCreateOptionsMenu(菜单菜单){
MenuInflater吹气=新MenuInflater(本);
inflater.inflate(R.menu.main,菜单);
返回true;
} @覆盖
公共布尔onOptionsItemSelected(菜单项项){
INT ID = item.getItemId();
开关(ID){
案例R.id.menu1:
意图intent1 =新意图(这一点,Login.class);
this.startActivity(intent1);
打破;
案例R.id.menu2:
意图intent2 =新意图(这一点,MainActivity.class);
this.startActivity(intent2);
打破;
默认:
返回super.onOptionsItemSelected(项目);
} 返回true;
}
}
Login.java
进口android.content.Context;
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.os.Bundle;
进口android.support.v7.app.ActionBarActivity;
进口android.view.Menu;
进口android.view.MenuInflater;
进口android.view.MenuItem;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Toast;公共类扩展登录{ActionBarActivity//公共静态android.content.Shared preferences共享preferences = NULL;私有静态最后弦乐preFER_NAME =注册;按钮buttonLogin;的EditText txtUsername,txtPassword;//用户会话管理器类
UserSession会议;私人共享preferences共享preferences;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.login); 按钮switchButton =(按钮)findViewById(R.id.buttonReg);
switchButton.setOnClickListener(新View.OnClickListener(){ @覆盖
公共无效的onClick(视图v){
意向意图=新意图(Login.this,Reg.class);
startActivity(意向); }
});
//用户会话管理器
会话=新UserSession(getApplicationContext()); //获取电子邮件,密码输入文本
txtUsername =(EditText上)findViewById(R.id.txtUsername);
txtPassword =(EditText上)findViewById(R.id.txtPassword); Toast.makeText(getApplicationContext(),
用户登录状态:+ session.isUserLoggedIn()
Toast.LENGTH_LONG).show();
//用户登录按钮
buttonLogin =(按钮)findViewById(R.id.buttonLogin); 共享preferences = getShared preferences(preFER_NAME,Context.MODE_PRIVATE);
//登录按钮单击事件
buttonLogin.setOnClickListener(新View.OnClickListener(){ @覆盖
公共无效的onClick(查看为arg0){ //从EditText上获取用户名,密码
字符串username = txtUsername.getText()的toString()。
。字符串密码= txtPassword.getText()的toString(); //如果验证用户名,密码是充满
如果(username.trim()长度()方式> 0&放大器;&放大器; password.trim()长度()方式> 0){
字符串的uname = NULL;
字符串uPassword = NULL; 如果(共享preferences.contains(姓名))
{
的uname =共享preferences.getString(姓名,); } 如果(共享preferences.contains(txtPassword))
{
uPassword =共享preferences.getString(txtPassword,); } //对象的uname = NULL;
//对象uEmail = NULL;
如果(username.equals(UNAME)及&放大器; password.equals(uPassword)){ session.createUserLoginSession(UNAME,
uPassword); //开始MainActivity
意图I =新意图(getApplicationContext(),MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //添加新的标志,开始新的活动
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(ⅰ); 完(); }其他{ //用户名/密码不匹配和放大器;
Toast.makeText(getApplicationContext(),
用户名/密码不正确,
Toast.LENGTH_LONG).show(); }
}其他{ //用户没有输入的用户名或密码
Toast.makeText(getApplicationContext(),
请输入用户名和密码
Toast.LENGTH_LONG).show(); } }
});
}
公共布尔onCreateOptionsMenu(菜单菜单){
MenuInflater吹气=新MenuInflater(本);
inflater.inflate(R.menu.main,菜单);
返回true;
}
@覆盖
公共布尔onOptionsItemSelected(菜单项项){
INT ID = item.getItemId();
开关(ID){
案例R.id.menu1:
意图intent1 =新意图(这一点,Login.class);
this.startActivity(intent1);
打破;
案例R.id.menu2:
意图intent2 =新意图(这一点,MainActivity.class);
this.startActivity(intent2);
打破;
默认:
返回super.onOptionsItemSelected(项目);
} 返回true;
}
}
UserSession.java
包com.example.tripmanager;进口的java.util.HashMap;进口android.content.Context;
进口android.content.Intent;
进口android.content.Shared preferences;
进口android.content.Shared preferences.Editor;公共类UserSession {
//共享preferences参考
共享preferences preF;//为共享preferences编辑器参考
编辑器编辑;//上下文
上下文_context;//共享preferences模式
INT PRIVATE_MODE = 0;//共享preferences文件名
公共静态最后弦乐preFER_NAME =注册;//所有共享preferences键
公共静态最后弦乐IS_USER_LOGIN =IsUserLoggedIn;//用户名(请可变公众从外部访问)
公共静态最后弦乐KEY_NAME =姓名;//电子邮件地址(请可变公众从外部访问)
公共静态最后弦乐KEY_EMAIL =电子邮件;//密码
公共静态最后弦乐KEY_PASSWORD =txtPassword;//构造
公共UserSession(上下文的背景下){
this._context =背景;
preF = _context.getShared preferences(preFER_NAME,PRIVATE_MODE);
编辑= pref.edit();
}//创建登录会话
公共无效createUserLoginSession(UNAME字符串,字符串uPassword){
//存储登录值TRUE
editor.putBoolean(IS_USER_LOGIN,真); //在preferences存储名称
editor.putString(KEY_NAME,UNAME); //在preferences存储电子邮件
editor.putString(KEY_EMAIL,uPassword); //提交更改
editor.commit();
}/ **
*检查登录方法将检查用户的登录状态
*如果假时,将用户重定向到登录页面
*否则做任何事
* * /
公共布尔checkLogin(){
//检查登录状态
如果(!this.isUserLoggedIn()){ //用户没有登录重定向他登录活动
意图I =新意图(_context,Login.class); //关闭从堆栈中的所有活动
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //添加新的标志,开始新的活动
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //凝视登录活动
_context.startActivity(ⅰ); 返回true;
}
返回false;
}/ **
*获取存储会话数据
* * /
公众的HashMap<字符串,字符串> getUserDetails(){ //使用HashMap中存储用户凭据
HashMap的<字符串,字符串>用户=新的HashMap<字符串,字符串>(); // 用户名
user.put(KEY_NAME,pref.getString(KEY_NAME,NULL)); //用户电子邮件ID
user.put(KEY_EMAIL,pref.getString(KEY_EMAIL,NULL)); //回报用户
返回用户;
}/ **
*清除会话的详细信息
* * /
公共无效logoutUser(){ //清除从共享preferences所有用户数据
editor.clear();
editor.commit(); //注销后重定向用户MainActivity
意图I =新意图(_context,MainActivity.class); //关闭所有的活动
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //添加新的标志,开始新的活动
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //凝视登录活动
_context.startActivity(ⅰ);
}
//检查登录
公共布尔isUserLoggedIn(){
返回pref.getBoolean(IS_USER_LOGIN,FALSE);
}
}
I'm new to Android. I'm doing an app for an university exam. I have to do an application for a travel agency. I'd like to manage the user session with shared preferences in order to save basic information and the eventually travels that the user booked. I can't find an example on the web that combine the registration and login forms. I wrote this code but it's not working. It doesn't show any error. I think what I wrote it's not logic. I'd like to register first and login with the information I gave in the registration form. Thank you for your help.
This is my Login.java:
package com.example.trip;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends ActionBarActivity {
public static android.content.SharedPreferences SharedPreferences = null;
private static final String PREFER_NAME = null;
Button buttonLogin;
EditText txtUsername, txtPassword;
// User Session Manager Class
UserSession session;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button switchButton = (Button)findViewById(R.id.buttonReg);
switchButton.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Login.this, Reg.class);
startActivity(intent);
}
});
// User Session Manager
session = new UserSession(getApplicationContext());
// get Email, Password input text
txtUsername = (EditText) findViewById(R.id.txtUsername);
txtPassword = (EditText) findViewById(R.id.txtPassword);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
// User Login button
buttonLogin = (Button) findViewById(R.id.buttonLogin);
SharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
// Login button click event
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Get username, password from EditText
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
if (SharedPreferences.contains("name"))
{
String uName = (SharedPreferences).getString("name", "");
}
if (SharedPreferences.contains("email"))
{
String uEmail = (SharedPreferences).getString("email", "");
}
Object uName = null;
Object uEmail = null;
if(username.equals(uName) && password.equals(uEmail)){
session.createUserLoginSession(uName,
uEmail);
// Starting MainActivity
Intent i = new Intent(getApplicationContext(),MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}else{
// username / password doesn't match&
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
}else{
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.MENU_1:
Intent intent1 = new Intent(this, Login.class);
this.startActivity(intent1);
break;
case R.id.MENU_2:
Intent intent2 = new Intent(this, MainActivity.class);
this.startActivity(intent2);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
This is the UserSession.java:
package com.example.trip;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "AndroidExamplePref";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
// Constructor
public UserSession(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(Object uName, Object uEmail){
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_NAME, (String) uName);
// Storing email in preferences
editor.putString(KEY_EMAIL, (String) uEmail);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
* */
public boolean checkLogin(){
// Check login status
if(!this.isUserLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Login.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn(){
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
This is the MainActivity.java:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.MENU_1:
Intent intent1 = new Intent(this, Login.class);
this.startActivity(intent1);
break;
case R.id.MENU_2:
Intent intent2 = new Intent(this, MainActivity.class);
this.startActivity(intent2);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
This is my Reg.java:
package com.example.trip;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class Reg extends ActionBarActivity {
SharedPreferences SharedPreferences;
Editor editor;
Button buttonReg2;
EditText txtUsername, txtPassword, txtEmail;
UserSession session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg);
txtUsername = (EditText) findViewById(R.id.Name);
txtPassword = (EditText) findViewById(R.id.txtPassword);
txtEmail = (EditText) findViewById(R.id.Email);
buttonReg2 = (Button) findViewById(R.id.buttonReg2);
// creating an shared Preference file for the information to be stored
// first argument is the name of file and second is the mode, 0 is private mode
SharedPreferences = getSharedPreferences("Reg", 0);
// get editor to edit in file
editor = SharedPreferences.edit();
buttonReg2.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
String name = txtUsername.getText().toString();
String email = txtEmail.getText().toString();
String pass = txtPassword.getText().toString();
if(txtUsername.getText().length()<=0){
Toast.makeText(Reg.this, "Enter name", Toast.LENGTH_SHORT).show();
}
else if( txtEmail.getText().length()<=0){
Toast.makeText(Reg.this, "Enter email", Toast.LENGTH_SHORT).show();
}
else if( txtPassword.getText().length()<=0){
Toast.makeText(Reg.this, "Enter password", Toast.LENGTH_SHORT).show();
}
else{
// as now we have information in string. Lets stored them with the help of editor
editor.putString("Name", name);
editor.putString("Email",email);
editor.putString("txtPassword",pass);
editor.commit();} // commit the values
// after saving the value open next activity
Intent ob = new Intent(Reg.this, Login.class);
startActivity(ob);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.MENU_1:
Intent intent1 = new Intent(this, Login.class);
this.startActivity(intent1);
break;
case R.id.MENU_2:
Intent intent2 = new Intent(this, MainActivity.class);
this.startActivity(intent2);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
The XML code of the MainActivity:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:shrinkColumns="0"
android:stretchColumns="1" >
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/destinazione" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="text" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/checkin" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="date" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/checkout" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="date" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/viaggiatori" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="number" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/stelle" />
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="@array/stelle"/>
</TableRow>
<Button
android:id="@+id/buttonFind"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonFind" />
</TableLayout>
The XML code for the login form:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:shrinkColumns="0"
android:stretchColumns="1" >
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/txtUsername" />
<EditText
android:id="@+id/txtUsername"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="text" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/txtPassword" />
<EditText
android:id="@+id/txtPassword"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textPassword" />
</TableRow>
<Button
android:id="@+id/buttonLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonLogin" />
<Button
android:id="@+id/buttonReg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonReg" />
</TableLayout>
This is the XML code for the registration form:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:shrinkColumns="0"
android:stretchColumns="1" >
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/Name" />
<EditText
android:id="@+id/Name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="text" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/Email" />
<EditText
android:id="@+id/Email"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textEmailAddress" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="fill_horizontal|center_vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_horizontal|center_vertical"
android:text="@string/txtPassword" />
<EditText
android:id="@+id/txtPassword"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textPassword" />
</TableRow>
<Button
android:id="@+id/buttonReg2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonReg2" />
</TableLayout>
This is working code, try it.
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu1:
Intent intent1 = new Intent(this, Login.class);
this.startActivity(intent1);
break;
case R.id.menu2:
Intent intent2 = new Intent(this, MainActivity.class);
this.startActivity(intent2);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
Reg.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Reg extends ActionBarActivity {
SharedPreferences sharedPreferences;
Editor editor;
Button buttonReg2;
EditText txtUsername, txtPassword, txtEmail;
UserSession session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg);
txtUsername = (EditText) findViewById(R.id.Name);
txtPassword = (EditText) findViewById(R.id.txtPassword);
txtEmail = (EditText) findViewById(R.id.Email);
buttonReg2 = (Button) findViewById(R.id.buttonReg2);
// creating an shared Preference file for the information to be stored
// first argument is the name of file and second is the mode, 0 is private mode
sharedPreferences = getApplicationContext().getSharedPreferences("Reg", 0);
// get editor to edit in file
editor = sharedPreferences.edit();
buttonReg2.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
String name = txtUsername.getText().toString();
String email = txtEmail.getText().toString();
String pass = txtPassword.getText().toString();
if(txtUsername.getText().length()<=0){
Toast.makeText(Reg.this, "Enter name", Toast.LENGTH_SHORT).show();
}
else if( txtEmail.getText().length()<=0){
Toast.makeText(Reg.this, "Enter email", Toast.LENGTH_SHORT).show();
}
else if( txtPassword.getText().length()<=0){
Toast.makeText(Reg.this, "Enter password", Toast.LENGTH_SHORT).show();
}
else{
// as now we have information in string. Lets stored them with the help of editor
editor.putString("Name", name);
editor.putString("Email",email);
editor.putString("txtPassword",pass);
editor.commit();} // commit the values
// after saving the value open next activity
Intent ob = new Intent(Reg.this, Login.class);
startActivity(ob);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu1:
Intent intent1 = new Intent(this, Login.class);
this.startActivity(intent1);
break;
case R.id.menu2:
Intent intent2 = new Intent(this, MainActivity.class);
this.startActivity(intent2);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
Login.java
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends ActionBarActivity {
//public static android.content.SharedPreferences SharedPreferences = null;
private static final String PREFER_NAME = "Reg";
Button buttonLogin;
EditText txtUsername, txtPassword;
// User Session Manager Class
UserSession session;
private SharedPreferences sharedPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button switchButton = (Button)findViewById(R.id.buttonReg);
switchButton.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Login.this, Reg.class);
startActivity(intent);
}
});
// User Session Manager
session = new UserSession(getApplicationContext());
// get Email, Password input text
txtUsername = (EditText) findViewById(R.id.txtUsername);
txtPassword = (EditText) findViewById(R.id.txtPassword);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
// User Login button
buttonLogin = (Button) findViewById(R.id.buttonLogin);
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
// Login button click event
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Get username, password from EditText
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
String uName = null;
String uPassword =null;
if (sharedPreferences.contains("Name"))
{
uName = sharedPreferences.getString("Name", "");
}
if (sharedPreferences.contains("txtPassword"))
{
uPassword = sharedPreferences.getString("txtPassword", "");
}
// Object uName = null;
// Object uEmail = null;
if(username.equals(uName) && password.equals(uPassword)){
session.createUserLoginSession(uName,
uPassword);
// Starting MainActivity
Intent i = new Intent(getApplicationContext(),MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}else{
// username / password doesn't match&
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
}else{
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu1:
Intent intent1 = new Intent(this, Login.class);
this.startActivity(intent1);
break;
case R.id.menu2:
Intent intent2 = new Intent(this, MainActivity.class);
this.startActivity(intent2);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
UserSession.java
package com.example.tripmanager;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "Name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "Email";
// password
public static final String KEY_PASSWORD = "txtPassword";
// Constructor
public UserSession(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uName, String uPassword){
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_NAME, uName);
// Storing email in preferences
editor.putString(KEY_EMAIL, uPassword);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
* */
public boolean checkLogin(){
// Check login status
if(!this.isUserLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Login.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn(){
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
这篇关于Android的登录/注册共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!