How to Use SharedPreferences in Retrofit2 onResponse method? - android

I am trying to get a user's login credentials while he signing in. I am sending to my database User_Email and User_Password then returning a Json like below. Actually the problem is simple but i dont know the solution, i am kinda new. I am %100 sure the error in my onResponse method. Because I am seeing this successfull response Toast, so i am getting successfull response but the problem here i dont know how to get this Json response into sharedpreferences. Thanks.
{
"User": [
{
"SSN": "123456789",
"FirstName": "Furkan",
"User_Role": "1"
}
]
}
And my model class for this response is :
public class UserList {
#SerializedName("User")
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
public class User {
#SerializedName("SSN")
public String sSN;
#SerializedName("FirstName")
public String firstName;
#SerializedName("User_Role")
public intuserRole;
public String getsSN() {
return sSN;
}
public void setsSN(String sSN) {
this.sSN = sSN;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getUserRoleTypeId() {
return userRoleTypeId;
}
public void setUserRoleTypeId(int userRoleTypeId) {
this.userRoleTypeId = userRoleTypeId;
}
}
I am trying to add these userRoleTypeId, firstName and sSN to SharedPreferences in my call.enqueue onResponse. But i could not figure it out.
Here is my LoginActivity.class for the login:
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button bSignUp, bLogin;
EditText etPassword, etEmail;
private int userRoleTypeId;
private SharedPreferences sharedPreferences;
private ProgressDialog progressDialog;
Intent intent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bSignUp = (Button) findViewById(R.id.bSignUp);
bLogin = (Button) findViewById(R.id.bLogin);
bSignUp.setOnClickListener((View.OnClickListener) this);
bLogin.setOnClickListener((View.OnClickListener) this);
etPassword = (EditText) findViewById(R.id.etPassword);
etEmail = (EditText) findViewById(R.id.etEmail);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Logging in");
progressDialog.setMessage("Please wait ....");
sharedPreferences = getApplicationContext().getSharedPreferences("LoginActivity",MODE_PRIVATE);
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bSignUp:
Intent SignUpIntent = new Intent(this, SignUpActivity.class);
startActivity(SignUpIntent);
break;
case R.id.bLogin:
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (!email.isEmpty() && !password.isEmpty()) {
progressDialog.show();
loginProcess(email, password);
this.userRoleTypeId = sharedPreferences.getInt(Constants.USERROLE, 0);
if (userRoleTypeId == 1) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRoleTypeId == 2 || userRoleTypeId == 3) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
private void loginProcess(String email, String password) {
LoginAPI loginAPI = RetrofitService.getClient().create(LoginAPI.class);
retrofit2.Call<UserList> call = loginAPI.loginUser(email,password);
call.enqueue(new Callback<UserList>(){
#Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
//I am sure the fault in here. In below i tried to take Json response and fetch it into the Shared Preferences.
UserList userLists = response.body().getUser();
if(response.isSuccessful()){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(Constants.IS_LOGGED_IN, true);
// editor.putString(Constants.NAME, userLists.getFirstName);
//editor.putString(Constants.SSN, userLists.getsSN);
// editor.putInt(Constants.USERROLE, userLists.getuserRoleTypeId);
editor.apply();
// I am seeing this successfull response toast, so i am getting successfull response but the problem here i dont know how to get this Json response into sharedpref.
Toast.makeText(LoginActivity.this, "successfull response", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<UserList> call, Throwable t) {
Toast.makeText(LoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}

Try this
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
editor.putBoolean(Constants.IS_LOGGED_IN, true);
prefeditor.putString("UserName", userLists.getUser().getFirstName());
prefEditor.putString(Constants.SSN, userLists.getUser().getsSN());
prefEditor.putInt(Constants.USERROLE, userLists.getUser().getUserRoleTypeId());
prefEditor.commit();
}

Related

Can't log out on button click on my android app

i made an app using java language, Retrofit2 and REST API for server side. in me API class i have login and register parameters like
public interface ApiInterface {
#FormUrlEncoded
#POST("/login")
void login(#Field("email") String email, #Field("password") String password, Callback<LoginResult> cb);
public static class LoginResult
{
public int status;
public String user_api_hash;
}
#GET("/registration_status")
void registrationStatus(#Query("lang") String lang, Callback<RegistrationStatusResult> cb);
public static class RegistrationStatusResult
{
public int status;
}
#GET("/get_user_data")
void getMyAccountData(#Query("user_api_hash") String user_api_hash, #Query("lang") String lang, Callback<GetMyAccountDataResult> cb);
public static class GetMyAccountDataResult
{
public String email, expiration_date, plan;
public int days_left, devices_limit;
}
my login class is working properly i can login and register any time. when logged in i receive api_kay then it's saved and use in all the app for requests DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); my loginActivity looks like :
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "EditObjectActivity";
#Bind(R.id.username)
EditText username;
#Bind(R.id.password)
EditText password;
#Bind(R.id.signin)
Button signin;
#Bind(R.id.register)
Button pwreset;
private String UrlPrefix;
private String customServerAddress="https://voila_voila_mon_url.com/";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork == null) {
Intent intent = new Intent(LoginActivity.this, NoInternetActivity.class);
startActivity(intent);
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
progressDialog = new ProgressDialog(this);
signin = (Button) findViewById(R.id.signin);
pwreset = (Button) findViewById(R.id.register);
password = findViewById(R.id.password);
username = findViewById(R.id.username);
String ip = getResources().getString(R.string.ip);
String httpsOn = getResources().getString(R.string.https_on);
String server_base = customServerAddress;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
if (ip.isEmpty()) {
enableRegistration();
}
else {
API.getApiInterface(LoginActivity.this).registrationStatus("en", new Callback<ApiInterface.RegistrationStatusResult>()
{
#Override
public void success(ApiInterface.RegistrationStatusResult result, Response response)
{
if (result.status == 1) {
enableRegistration();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, "failure: retrofitError" + retrofitError.getMessage());
Toast.makeText(LoginActivity.this, getString(R.string.errorHappened), Toast.LENGTH_SHORT).show();
}
});
}
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(customServerAddress != null) {
String server_base = customServerAddress;
server_base = UrlPrefix + server_base;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
}
API.getApiInterface(LoginActivity.this).login(username.getText().toString(), password.getText().toString(), new Callback<ApiInterface.LoginResult>()
{
#Override
public void success(ApiInterface.LoginResult loginResult, Response response)
{ // progress dialogue
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Connexion au serveur"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
//end progress dialogue
DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash);
Log.d("LoginActivity", "api_key: " + loginResult.user_api_hash);
if(customServerAddress == null)
{
String url = "https://voila_voila_mon_url.com/";
DataSaver.getInstance(LoginActivity.this).save("server_base", url);
DataSaver.getInstance(LoginActivity.this).save("server", url + "api/");
}
Intent intent = new Intent(LoginActivity.this, MapActivity.class);
startActivity(intent);
finish();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(LoginActivity.this, getString(R.string.wrongLogin), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
now the thing is i'd look to log out in my mean activity. in my reseachs i have been told that once logged out the api_key in DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); should be null like api_key =null.also when i open the app it show that i am logged. i want to log out.here is my example on my_logout button i did this :
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String log_out = null;
if(DataSaver.getInstance(this).load("api_key") != null){
DataSaver.getInstance(this).load("api_key") == log_out;
finish();
}else{
//Toast.......(Toast with message ->>>>unable to log out).
}
});
This DataSaver.getInstance(this).load("api_key") is used in all the app when requesting for GET method when fetching users datas. the api_key saved in the app allow me to make some requests as said before. but when this is null it's impossible to make requests. i want to destroy the session when logged in by loggin out. if you understand what i say and can help please.
my account activity after logged in
public class MyAccountActivity extends AppCompatActivity
{
#Bind(R.id.back) View back;
#Bind(R.id.expandable_list) ExpandableListView expandable_list;
#Bind(R.id.loading_layout) View loading_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
ButterKnife.bind(this);
loading_layout.setVisibility(View.VISIBLE);
API.getApiInterface(this).getMyAccountData((String) DataSaver.getInstance(this).load("api_key"), getResources().getString(R.string.lang), new Callback<ApiInterface.GetMyAccountDataResult>() {
#Override
public void success(ApiInterface.GetMyAccountDataResult dataResult, Response response)
{
MyAccountAdapter adapter = new MyAccountAdapter(MyAccountActivity.this, dataResult);
expandable_list.setAdapter(adapter);
Utils.setGroupClickListenerToNotify(expandable_list, adapter);
loading_layout.setVisibility(View.GONE);
expandable_list.setVisibility(View.VISIBLE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MyAccountActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
i did this but it's not enough to log out #Syed Ibrahim
like this
but not working this is juste to stay connected not to log out
if (DataSaver.getInstance(this).load("api_key") == null)
{
startActivity(new Intent(MapActivity.this, LoginActivity.class));
finish();
return;
}
what i need is to set this api_key null whatever the app is running or not.

'java.lang.String com.google.firebase.auth.FirebaseUser.getEmail()' on a null object reference

So the app crashes when the user presses the sign-in button and only if the details he wrote down in the edit texts are correct by the firebaseAuth. reopening the app will make the app behave as nothing happened and the user will be signed in.
Here's the code:
public class LoginActivity extends Activity {
private Button btnRegister, btnSignIn, btnForgot;
private EditText etPhone, etPassword;
private ProgressBar mprogressBar;
private FirebaseAuth fbAuth;
private FirebaseUser fbUser;
private FirebaseFirestore db;
private DocumentReference uDocRef;
private CollectionReference uColctRef;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnRegister = findViewById(R.id.btnRegister);
btnSignIn = findViewById(R.id.btnSignIn);
btnForgot = findViewById(R.id.btnForgot);
etPhone = findViewById(R.id.etPhone);
etPassword = findViewById(R.id.etPassword);
mprogressBar = findViewById(R.id.mprogressBar);
fbAuth = FirebaseAuth.getInstance();
fbUser = fbAuth.getCurrentUser();
initFirebase();
}
private void initFirebase() {
db = FirebaseFirestore.getInstance();
uColctRef = db.collection(UserFirebase.UsersCollection);
if (fbUser != null)
{
Toast.makeText(this, "User already logged in: " + fbUser.getEmail(), Toast.LENGTH_LONG).show();
refreshListAndSubscribe();
Intent zone = new Intent(this, ZoneActivity.class);
startActivity(zone);
}
}
private void refreshListAndSubscribe() {
uColctRef
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot result,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("FirebaseDemo-Query", "Listen failed", e);
e.printStackTrace();
return;
}
Log.i("FirebaseDemo-Query", "Listen succeded");
checklist(result);
}
});
}
private void checklist(QuerySnapshot result) {
String email;
boolean isApproved;
sharedPreferences = getSharedPreferences("SaveData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (QueryDocumentSnapshot document : result) {
email = document.get(UserFirebase.email).toString();
if (etPhone.getText().toString().trim().equals(email))
{
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
if (fbUser != null)
{
if (fbUser.getEmail().equals(email))
{
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
}
}
}
public void onSign(View v)
{
if (isEmpty())
return;
inProgress(true);
fbAuth.signInWithEmailAndPassword(etPhone.getText().toString().trim(), etPassword.getText().toString())
.addOnSuccessListener(new OnSuccessLstnr("User Signed In", true))
.addOnFailureListener(new OnFailLstnr("Sign-in failed!"));
}
public void setPassword(View v)
{
Intent pass = new Intent(this, PasswordActivity.class);
startActivity(pass);
}
public void onRegister(View v)
{
Intent auth = new Intent (this, RegisterActivity.class);
startActivity(auth);
}
private void inProgress(boolean inProgress)
{
if (inProgress)
{
mprogressBar.setVisibility(View.VISIBLE);
btnSignIn.setEnabled(false);
btnRegister.setEnabled(false);
btnForgot.setEnabled(false);
}
else
{
mprogressBar.setVisibility(View.INVISIBLE);
btnSignIn.setEnabled(true);
btnRegister.setEnabled(true);
btnForgot.setEnabled(true);
}
}
private boolean isEmpty()
{
if (TextUtils.isEmpty(etPhone.getText().toString()))
{
etPhone.setError("REQUIRED!");
return true;
}
if (TextUtils.isEmpty(etPassword.getText().toString()))
{
etPassword.setError("REQUIRED!");
return true;
}
return false;
}
private class OnFailLstnr implements OnFailureListener
{
String msg;
public OnFailLstnr(String _msg)
{
this.msg = _msg;
}
#Override
public void onFailure(#NonNull Exception e)
{
inProgress(false);
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
public class OnSuccessLstnr implements OnSuccessListener<AuthResult>
{
String msg;
boolean open;
OnSuccessLstnr(String _msg, boolean _open)
{
this.msg = _msg;
this.open = _open;
}
#Override
public void onSuccess(AuthResult authResult)
{
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
inProgress(false);
if (open)
{
refreshListAndSubscribe();
Intent in = new Intent(LoginActivity.this, ZoneActivity.class);
startActivity(in);
finish();
}
}
}
The Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getEmail()' on a null object reference
at com.a.shon.scoutszone2.Activities.LoginActivity.checklist(LoginActivity.java:127)
at com.a.shon.scoutszone2.Activities.LoginActivity.access$000(LoginActivity.java:42)
at com.a.shon.scoutszone2.Activities.LoginActivity$1.onEvent(LoginActivity.java:101)
at com.a.shon.scoutszone2.Activities.LoginActivity$1.onEvent(LoginActivity.java:91)
I've Tried fixing it using answers to some similliar questions that were already posted in the site, but it didn't really change or fix the problem.
I would like to get help with solving this issue out and every help would be appreciated by A LOT!
Thanks in advance!
Found a solution, Seems like dealing with Already authenticated users (Users who already logged in, just reopening the app) and users who are just logged out from the app in one method (Check the - private void checklist(QuerySnapshot result), to understand what I'm talking about) is quite a messy way to deal with it, and making it really buggy.
The solution:
In InitFirebase() change the calling of refreshListAndSubscribe(); to a different new method, i called it refreshExistingUser(), its the same code as refreshListAndSubscribe()
the only part which is different between the two is the calling for the second method at the end of them.
Ill Add here a part of the code to make it simpler to understand:
private void initFirebase() {
db = FirebaseFirestore.getInstance();
uColctRef = db.collection(UserFirebase.UsersCollection);
if (fbUser != null)
{
Toast.makeText(this, "User already logged in: " + fbUser.getEmail(), Toast.LENGTH_LONG).show();
refreshExistingUser();
Intent zone = new Intent(this, ZoneActivity.class);
startActivity(zone);
}
}
private void refreshListAndSubscribe() {
uColctRef
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot result,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("FirebaseDemo-Query", "Listen failed", e);
e.printStackTrace();
return;
}
Log.i("FirebaseDemo-Query", "Listen succeded");
checklist(result);
}
});
}
private void checklist(QuerySnapshot result) {
String email;
boolean isApproved;
sharedPreferences = getSharedPreferences("SaveData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (QueryDocumentSnapshot document : result) {
email = document.get(UserFirebase.email).toString();
if (etPhone.getText().toString().trim().equals(email))
{
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
}
}
private void refreshExistingUser() {
uColctRef
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot result,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("FirebaseDemo-Query", "Listen failed", e);
e.printStackTrace();
return;
}
Log.i("FirebaseDemo-Query", "Listen succeded");
checkuser(result);
}
});
}
private void checkuser(QuerySnapshot result) {
String email;
boolean isApproved;
sharedPreferences = getSharedPreferences("SaveData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (QueryDocumentSnapshot document : result) {
email = document.get(UserFirebase.email).toString();
if (fbUser.getEmail().equals(email)) { //When the user isnt == null (Reopening the app and such)
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
}
}

Registration Page does not record user data with Firebase

public class RegisterActivity extends AppCompatActivity {
//create variables
private EditText mUsername, mPassword, mEmail, mPhone;
private Button mRegister;
private TextView mLogin;
private FirebaseAuth mAuth;
private ImageView mProfilePicture;
String user_email, user_name, user_phone, user_password;
//on creation of activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
setupViews();
//firebase instance declared
mAuth = FirebaseAuth.getInstance();
//When register is clicked
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if all fields are okay using validation method
if(validate()){
//get user info
String user_email = mEmail.getText().toString().trim();
String user_password = mPassword.getText().toString().trim();
String user_phone = mPhone.getText().toString().trim();
String user_name = mUsername.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(user_email, user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
sendEmailVerification();
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
//Return user back to login page
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
});
}
//setup views by id from xml
private void setupViews(){
mUsername = (EditText)findViewById(R.id.editTextNewUsername);
mPassword = (EditText)findViewById(R.id.editTextNewPassword);
mEmail = (EditText)findViewById(R.id.editTextNewEmail);
mPhone = (EditText)findViewById(R.id.editTextPhone);
mRegister = (Button)findViewById(R.id.buttonRegister);
mLogin = (TextView)findViewById(R.id.textViewLogin);
mProfilePicture = (ImageView)findViewById(R.id.imageViewProfilePicture);
}
//validate if all fields are okay and not empty
private Boolean validate() {
Boolean result = false;
//convert inputs to strings
String user_name = mUsername.getText().toString();
String user_password = mPassword.getText().toString();
String user_email = mEmail.getText().toString();
String user_phone = mPhone.getText().toString();
//check if any fields are empty, if not then return result
if (user_name.isEmpty() || user_password.isEmpty() || user_email.isEmpty() || user_phone.isEmpty()) {
Toast.makeText(this, "All fields are required for registration.", Toast.LENGTH_SHORT).show();
} else {
result = true;
}
return result;
}
private void sendEmailVerification(){
FirebaseUser firebaseUser = mAuth.getCurrentUser();
if(firebaseUser!=null){
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserData();
Toast.makeText(RegisterActivity.this, "Successfully Registered, Verification mail sent!", Toast.LENGTH_SHORT).show();
mAuth.signOut();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Verification mail has'nt been sent!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference(mAuth.getCurrentUser().getUid());
UserProfile userProfile = new UserProfile(user_phone, user_email, user_name);
myRef.setValue(userProfile);
}
}
Solved the crash with my profile page and got it to save artifical data, but found out my registration page is the problem and is not recording data. Here is my Userprofile.java for reference
public class UserProfile {
public String user_phone;
public String user_email;
public String user_name;
public UserProfile() {
}
public UserProfile(String user_phone, String user_email, String user_name) {
this.user_phone = user_phone;
this.user_email = user_email;
this.user_name = user_name;
}
public String getUser_phone() {
return user_phone;
}
public void setUser_phone(String user_phone) {
this.user_phone = user_phone;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
Any help would be appreciated, i'd read extensively on the topic and can't seem to see whatever small issue is causing the hold-up. Any other pointers are also welcome.
Try changing:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
assert userProfile != null;
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
With:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
if(userProfile != null){
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
}

android firebase database save data for current user

I have an app that send sms templates with firebase user login.
I want to save sms logs for each user on firbase database so I will be able to see what messages each user sent. I have no idea how to make it probably ..
my code
LoginActivity.java
public class LoginActivity extends AppCompatActivity {
private ProgressBar spinner;
EditText EMAIL, PASSWORD;
Button SIGNIN;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
EMAIL = (EditText) findViewById(R.id.email);
PASSWORD = (EditText) findViewById(R.id.password);
SIGNIN = (Button) findViewById(R.id.login);
spinner = (ProgressBar) findViewById(R.id.progressBar1);
spinner.setVisibility(View.GONE);
SIGNIN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ((TextUtils.isEmpty(EMAIL.getText().toString())) && (TextUtils.isEmpty(PASSWORD.getText().toString()))) {
Toast.makeText(getApplicationContext(), "make sure that you enter full ogin info ", Toast.LENGTH_SHORT).show();
}else if (!isEmailValid(EMAIL.getText().toString())){
Toast.makeText(getApplicationContext(), "enter a valid mail", Toast.LENGTH_SHORT).show();
} else {
SignIn(EMAIL.getText().toString(), PASSWORD.getText().toString());
}
}
});
SIGNIN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String pass = PASSWORD.getText().toString();
if(TextUtils.isEmpty(pass)) {
PASSWORD.setError("kindly enter password ");
return;
}
if ((TextUtils.isEmpty(EMAIL.getText().toString())) && (TextUtils.isEmpty(PASSWORD.getText().toString()))) {
Toast.makeText(getApplicationContext(), "wrong info", Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
} else {
spinner.setVisibility(View.VISIBLE);
SignIn(EMAIL.getText().toString(), PASSWORD.getText().toString());
}
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
}
}
};
mAuth.addAuthStateListener(mAuthListener);
}
private void SignIn(String email, String password) {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
finish();
Toast.makeText(getApplicationContext(), "login done",
Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
Toast.makeText(getApplicationContext(), "Error username",
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
}
});
}
public static boolean isEmailValid(String email) {
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
}
sms.java
public class Harsh extends AppCompatActivity {
RadioButton lo, hi, mid;
String sense;
Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.harsh_layout);
lo = (RadioButton) findViewById(R.id.lo_btn);
hi = (RadioButton) findViewById(R.id.hi_btn);
mid = (RadioButton) findViewById(R.id.mid_btn);
submit = (Button) findViewById(R.id.submitButton);
SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE);
final String num = prefs.getString("nameKey", "0");
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lo.isChecked()) {
sendSMS( num, " message one");
} else if (hi.isChecked()) {
sendSMS( num, " message 2");
// for example save this message for current logged user
} else if (mid.isChecked()) {
sendSMS( num, " message 3");
}
Toast.makeText(getApplicationContext(), "Command Sent", Toast.LENGTH_LONG).show(); // print the value of selected super star
}
});
}
public void sendSMS(String phoneNo, String msg) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, msg, null, null);
Toast.makeText(getApplicationContext(), "Command Sent",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
}
after alot of researches i found that set and get class and i modify my code as below
public class Post {
private String message;
private String number;
private String user;
private String date;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
then in activity that i need to Post data to firbase database i add that simple code
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference posts = database.getReference("Messages:");
//this code for keep posts even app offline until the app online again
posts.keepSynced(true);
Post post = new Post();
post.setMessage("Messsage");
post.setUser(name);
post.setNumber(num);
post.setDate(s);
posts.push().setValue(post);

how can i put session on my app so that i don't need to login again after closing the app?

i am making a login page where if user logged in for order ,he can order his request etc,even after the closing of app if he opens the app again he doesnt need to login again..i have facebook button also but that is other thing...kindly help?
here is my code :
public class Login extends AppCompatActivity {
private String eml;
private String pswrd;
private ProfileTracker mProfileTracker;
private ProgressDialog pDialog;
String status = "";
private Button fbbutton;
Profile profile;
Button login;
// private int serverResponseCode = 0;
TextView tac1;
EditText email, pass;
private static String url_create_book = "http://cloud.....com/broccoli/login.php";
public static CallbackManager callbackmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_login);
Get_hash_key();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// AppEventsLogger.activateApp(this);
fbbutton = (Button) findViewById(R.id.fbtn);
fbbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call private method
onFblogin();
}
});
email = (EditText)findViewById(R.id.email);
pass = (EditText) findViewById(R.id.password);
tac1 = (TextView)findViewById(R.id.cAcc);
tac1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, RegistrationForm.class));
}
}
);
login = (Button) findViewById(R.id.lbtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
eml = email.getText().toString();
pswrd = pass.getText().toString();
// new CreateNewProduct().execute();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_create_book,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
if (response.trim().equals("success")) {
Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Login.this, Home.class));
//your intent code here
} else {
Toast.makeText(Login.this, "username/password incorrect", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", eml);
params.put("password", pswrd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Login.this);
requestQueue.add(stringRequest);
}
});
}
public void Get_hash_key() {
PackageInfo info;
try {
info = getPackageManager().getPackageInfo("com.example.zeba.broccoli", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
private void onFblogin() {
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().registerCallback(callbackmanager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try {
if (Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) {
// profile2 is the new profile
profile = profile_new;
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
profile = Profile.getCurrentProfile();
}
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("FACEBOOK LOGIN", response.toString());
// Application code
try {
String fb_id = object.getString("id");
String fb_name = object.getString("name");
String profilePicUrl = "https://graph.facebook.com/" + fb_id + "/picture?width=200&height=200";
String fb_gender = object.getString("gender");
String fb_email = object.getString("email");
String fb_birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
//use shared preferences here
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();
//go to Home page
Intent intent = new Intent(getApplicationContext(), Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
// Log.d(TAG_CANCEL, "On cancel");
}
#Override
public void onError(FacebookException error) {
//Log.d(TAG_ERROR, error.toString());
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackmanager.onActivityResult(requestCode, resultCode, data);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
p.s i am new to android so gives answers with coding and try to replace my code with ur correct code...thx in advance
You can use shared preferences, save your user name in your shared preferences,
and put check on the main launching activity (for example if you login activity as launcher activity), if username exists then redirect user to some other activity using intent otherwise ask user to login again.
Hope it helps you.
when I login for the very first time i did this after login(read about shared preferences if you don`t know how to use it)
CommonObjects.saveSharedPreferences(Login.this, "user_id", user_id);
CommonObjects.saveSharedPreferences(Login.this, "name", name);
this i close my app and open app again, hence my login activity is the first activity which always shows first when i open my app, then in very beginning of the of the login activity do this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (CommonObjects.hasSharedPreference(context,"user_id")){
Intent intMain=new Intent(Login.this,DashboardActivity.class);
startActivity(intMain);
finish();
}
}
hope you understand now.
public class Login extends AppCompatActivity {
private String eml;
private String pswrd;
private ProfileTracker mProfileTracker;
private ProgressDialog pDialog;
String status = "";
private Button fbbutton;
Profile profile;
Button login;
// private int serverResponseCode = 0;
TextView tac1;
EditText email, pass;
private static String url_create_book = "http://cloud.....com/broccoli/login.php";
public static CallbackManager callbackmanager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
setContentView(R.layout.activity_login);
Get_hash_key();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences sf_shared_pref = getSharedPreferences("variable", 0);
Boolean on_time_login = sf_shared_pref.getBoolean("flag", false);
if (on_time_login) {
Intent intent = new Intent(getApplicationContext(), HomeClass.class);
startActivity(intent);
}
// AppEventsLogger.activateApp(this);
fbbutton = (Button) findViewById(R.id.fbtn);
fbbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Call private method
onFblogin();
}
});
email = (EditText)findViewById(R.id.email);
pass = (EditText) findViewById(R.id.password);
tac1 = (TextView)findViewById(R.id.cAcc);
tac1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
startActivity(new Intent(Login.this, RegistrationForm.class));
}
}
);
login = (Button) findViewById(R.id.lbtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
eml = email.getText().toString();
pswrd = pass.getText().toString();
// new CreateNewProduct().execute();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url_create_book,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.dismiss();
if (response.trim().equals("success")) {
Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show();
SharedPreferences settings = getApplicationContext().getSharedPreferences("variable", MODE_PRIVATE); // 0 - for private mode
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("flag", true);
editor.apply();
startActivity(new Intent(Login.this, Home.class));
//your intent code here
} else {
Toast.makeText(Login.this, "username/password incorrect", Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", eml);
params.put("password", pswrd);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Login.this);
requestQueue.add(stringRequest);
}
});
}
public void Get_hash_key() {
PackageInfo info;
try {
info = getPackageManager().getPackageInfo("com.example.zeba.broccoli", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
//String something = new String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
private void onFblogin() {
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));
LoginManager.getInstance().registerCallback(callbackmanager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try {
if (Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) {
// profile2 is the new profile
profile = profile_new;
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
profile = Profile.getCurrentProfile();
}
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("FACEBOOK LOGIN", response.toString());
// Application code
try {
String fb_id = object.getString("id");
String fb_name = object.getString("name");
String profilePicUrl = "https://graph.facebook.com/" + fb_id + "/picture?width=200&height=200";
String fb_gender = object.getString("gender");
String fb_email = object.getString("email");
String fb_birthday = object.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
//use shared preferences here
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday,picture.type(small)");
request.setParameters(parameters);
request.executeAsync();
//go to Home page
Intent intent = new Intent(getApplicationContext(), Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
// Log.d(TAG_CANCEL, "On cancel");
}
#Override
public void onError(FacebookException error) {
//Log.d(TAG_ERROR, error.toString());
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackmanager.onActivityResult(requestCode, resultCode, data);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
public class CommonUtilities {
private static SharedPreferences.Editor editor;
private static SharedPreferences sharedPreferences;
private static Context mContext;
/**
* Create SharedPreference and SharedPreferecne Editor for Context
*
* #param context
*/
private static void createSharedPreferenceEditor(Context context) {
try {
if (context != null) {
mContext = context;
} else {
mContext = ApplicationStore.getContext();
}
sharedPreferences = context.getSharedPreferences(IAdoddleConstants.ADODDLE_PREF, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Put String in SharedPreference Editor
*
* #param context
* #param key
* #param value
*/
public static void putPrefString(Context context, String key, String value) {
try {
createSharedPreferenceEditor(context);
editor.putString(key, value);
editor.commit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
For this you can use "SharedPreferences".
When a user logs into the application, save a boolean variable say: "USERLOGGED_IN" into the shared preferences, like this:
The below code is to be written inside "AsyncTask":
SharedPreferences prefs;
Editor editor = prefs.edit();<br></br>
editor .putBoolean("USERLOGGED_IN",true); //If user has logged in successfully<br></br>
//or
editor .putBoolean("USERLOGGED_IN",false);//If user has not logged in<br></br>
editor.commit();
Once the value has been saved in the "SharedPreferences", the only thing left is to check this value, when a user opens the application again.
Then do this:
SharedPreferences prefs;
boolean USERLOGGED_IN = prefs.getBoolean("USERLOGGED_IN"); // the value you saved during logging in the user.
if(USERLOGGED_IN == true)
{
//User has logged in already, so direct the user to home screen.
}
else
{
//User is new, so direct the user to login screen.
}
I hope this helps.

Categories

Resources