我想檢查用戶是否已經登錄到應用程序,所以如果用戶沒有登錄,他將被定向到Login.class
,如果用戶已經登錄,他將被定向到他的Profile.class
。android檢查用戶是否已登錄
我看到一個關於檢查用戶使用SplashActivity.class
登錄的用戶的教程,但我試過了,並沒有爲我工作,我不知道也許我只是不知道它是如何工作的,因爲我是新的在編程
我的代碼:
登錄類
public class DocLogin extends Fragment {
ImageView ivIcon;
TextView tvItemName, tvRegister;
EditText user, pass;
Button btnLogin;
String username, password;
SQLController dbcon;
SharedPreferences sh_Pref;
Editor editor;
private static final String IS_LOGIN = "IsLoggedIn";
int PRIVATE_MODE = 0;
public DocLogin() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.doc_log_in, container, false);
dbcon = new SQLController(getActivity());
dbcon.open();
// Log in
user = (EditText) view.findViewById(R.id.etUser);
pass = (EditText) view.findViewById(R.id.etPassword);
btnLogin = (Button) view.findViewById(R.id.btnLogin);
// Sign up
tvRegister = (TextView) view.findViewById(R.id.tvRegDoc);
tvRegister.setMovementMethod(LinkMovementMethod.getInstance());
tvRegister.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, new DocReg());
ft.commit();
return false;
}
});
// btnLogin onClickListener
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
dbcon = new SQLController(getActivity());
dbcon.open();
username = user.getText().toString();
password = pass.getText().toString();
sharedPreferences();
Toast.makeText(getActivity(), "Login Successful", 20).show();
Log.v("LoginDetails", user.getText().toString() + "../.."
+ pass.getText().toString());
Cursor cur = dbcon.getuser_information(user.getText()
.toString(), pass.getText().toString());
if (cur.getCount() != 0) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content_frame, new DocProfile());
ft.commit();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Login Error");
alertDialog
.setMessage("Doctor Code and Password does not match");
alertDialog.setButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
// dismiss dialog
}
});
alertDialog.show();
}
}
});
return view;
}
public void sharedPreferences() {
sh_Pref = getActivity().getSharedPreferences("Login Credentials", PRIVATE_MODE);
editor = sh_Pref.edit();
editor.putBoolean(IS_LOGIN, true);
editor.putString("Username", username);
editor.putString("Password", password);
editor.commit();
}
}
請指引我正確的方式來實現我的目標。
我可以在SplashActivity使用它? – user3766257
您可以在您想要檢查登錄的應用中的任何位置使用此代碼段。 – Xkorpion