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);
Related
I am currently using Email/Password in sign in and sign up .
I want to add Phone number in sign up (with vérification of otp )
and will be sign in with (Email or Phone (EditText)+ password (EditText)).
the problem is if i can do it ? or not ?
if i can there is my code what will i add
This activity of Sign in :
private TextInputLayout mEmail,mPass;
private Button mLogin,mCallRegister ;
private ProgressDialog mProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener fbAutLis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_login);
//progress bar
mProgress =new ProgressDialog(this);
String titleId="Signing in...";
mProgress.setTitle(titleId);
mProgress.setMessage("Please Wait...");
mAuth= FirebaseAuth.getInstance();
fbAutLis= new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
mProgress.dismiss();
Intent inte =new Intent(ClientLoginAct.this,ClientMapAct.class);
startActivity(inte);
finish();
return ;
}
}
};
mEmail =(TextInputLayout)findViewById(R.id.email);
mPass =(TextInputLayout)findViewById(R.id.pass);
mLogin =(Button)findViewById(R.id.login);
mCallRegister =(Button) findViewById(R.id.callRegister);
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if( !validateEmail()|!validatePassword()){
return;
}
mProgress.show();
final String email=mEmail.getEditText().getText().toString();
final String password=mPass.getEditText().getText().toString();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(ClientLoginAct.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
mProgress.dismiss();
Snackbar.make(v, "Email or Password incorrect", Snackbar.LENGTH_LONG).show();
//Toast.makeText(ClientLoginAct.this,"Email or Password incorrect ",Toast.LENGTH_SHORT).show();
}
}
});
}
});
mCallRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ClientLoginAct.this,ClientRegAct.class);
startActivity(intent);
}
});
}
private Boolean validateEmail() {
String val = mEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
mEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
mEmail.setError("Invalid email address");
return false;
} else {
mEmail.setError(null);
mEmail.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = mPass.getEditText().getText().toString();
String passwordVal = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
//"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=.*[a-zA-Z0-9])" + //any letter
"(?=\\S+$)" + //no white spaces
".{6,}" + //at least 6 characters
"$";
if (val.isEmpty()) {
mPass.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
mPass.setError("Password is too weak(at least 6 characters & no white spaces)");
return false;
} else {
mPass.setError(null);
mPass.setErrorEnabled(false);
return true;
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(fbAutLis);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(fbAutLis);
}
}
This is activity of Sign up :
private TextInputLayout mEmail,mPass;
private Button mRegister,mCallLogin;
private ProgressDialog mProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener fbAutLis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_reg);
//progress bar
mProgress =new ProgressDialog(this);
String titleId="Signing up...";
mProgress.setTitle(titleId);
mProgress.setMessage("Please Wait...");
mAuth= FirebaseAuth.getInstance();
fbAutLis= new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
mProgress.dismiss();
Intent inte =new Intent(ClientRegAct.this,ClientMapAct.class);
startActivity(inte);
finish();
return ;
}
}
};
mEmail =(TextInputLayout)findViewById(R.id.email);
mPass =(TextInputLayout)findViewById(R.id.pass);
// mPhone =(TextInputLayout)findViewById(R.id.phone);
mRegister =(Button)findViewById(R.id.register);
mCallLogin =(Button) findViewById(R.id.callLogin);
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if( !validateEmail()|!validatePassword()){
return;
}
mProgress.show();
final String email=mEmail.getEditText().getText().toString();
final String password=mPass.getEditText().getText().toString();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(ClientRegAct.this,new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task){
if (!task.isSuccessful()){
mProgress.dismiss();
Snackbar.make(v, "This email is already exist", Snackbar.LENGTH_LONG).show();
//Toast.makeText(ClientRegAct.this,"This email is already exist",Toast.LENGTH_SHORT).show();
}else{
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Clients").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
mCallLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
private Boolean validateEmail() {
String val = mEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
mEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
mEmail.setError("Invalid email address");
return false;
} else {
mEmail.setError(null);
mEmail.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = mPass.getEditText().getText().toString();
String passwordVal = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
//"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=.*[a-zA-Z0-9])" + //any letter
"(?=\\S+$)" + //no white spaces
".{6,}" + //at least 6 characters
"$";
if (val.isEmpty()) {
mPass.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
mPass.setError("Password is too weak(at least 6 characters & no white spaces)");
return false;
} else {
mPass.setError(null);
mPass.setErrorEnabled(false);
return true;
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(fbAutLis);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(fbAutLis);
}
}
This code of activity Vérify_Otp but i dont know how to link with other activity :
String verificationCodeBySystem;
private Button mVerify;
private EditText mCode;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_verify);
mVerify = findViewById(R.id.verify_btn);
mCode = findViewById(R.id.verification_code_entered_by_user);
mProgressBar = findViewById(R.id.progress_bar);
String phoneNo = getIntent().getStringExtra("phoneNo");
sendVerificationCodeToUser(phoneNo);
mVerify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = mCode.getText().toString();
if (code.isEmpty() || code.length() < 6) {
mCode.setError("Wrong OTP...");
mCode.requestFocus();
return;
}
mProgressBar.setVisibility(View.VISIBLE);
verifycode(code);
}
});
}
private void sendVerificationCodeToUser(String phoneNo) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+213" + phoneNo, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
TaskExecutors.MAIN_THREAD, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCodeBySystem = s ;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if(code!=null){
mProgressBar.setVisibility(View.VISIBLE);
verifycode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(OtpVerify.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
};
private void verifycode (String codeByUser){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem,codeByUser);
signInTheUserByCredentials(credential);
}
private void signInTheUserByCredentials(PhoneAuthCredential credential){
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(OtpVerify.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(OtpVerify.this, "Your Account has been created successfully!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(OtpVerify.this,ClientMapAct.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(intent);
}else{
Toast.makeText(OtpVerify.this,task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
So please what i change to got what i ask in first lines ...
I'm trying to retrieve data from current logged in user from my firebase realtime database, but when i go into activity that suppose to show the data, the app crash with the following error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.rsolveapp.User.getEmail()' on a null object reference"
This is the activity for showing the data
public class RsolverAccount extends AppCompatActivity {
TextView showEmail;
private static final String TAG = RsolverAccount.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rsolveraccount);
setWidget();
showData();
}
private void showData () {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if(firebaseUser != null) {
String email = firebaseUser.getEmail();
Log.d(TAG, email);
}
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference().child("sraboetapp").child("userdesc").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
showEmail.setText(user.getEmail());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabase.addValueEventListener(postListener);
}
public void setWidget() {
showEmail = (TextView) findViewById(R.id.showEmail);
}
}
This is my User class
public class User implements Serializable{
private String email;
private String name, pass, id, phone;
private String key;
public User(){
}
public String getKey(){
return key;
}
public void setKey(String key){
this.key=key;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email=email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getPass(){
return pass;
}
public void setPass(String pass){
this.pass=pass;
}
public String getId(){
return id;
}
public void setId(String id){
this.id=id;
}
public String getPhone(){
return phone;
}
public void setPhone(String phone){
this.phone=phone;
}
#Override
public String toString(){
return " "+email+"/n"+
" "+name+"/n"+
" "+pass+"/n"+
" "+id+"/n"+
" "+phone;
}
public User(String Remail, String Rname, String Rpass, String Rid, String Rphone){
this.email=Remail;
this.name=Rname;
this.pass=Rpass;
this.id=Rid;
this.phone=Rphone;
}
}
This is my database structure
{
"description" : {
"-LpJNvsR3oIGA5pv1uOK" : {
"day" : "2",
"description" : "tes",
"eHour" : "12",
"eMin" : "12",
"sHour" : "12",
"sMin" : "12"
}
},
"userdesc" : {
"-LquV8N1AJbRdhSKMA2T" : {
"email" : "bryan5#gmail.com",
"id" : "870788464845",
"name" : "bry5",
"pass" : "123456",
"phone" : "484854484546"
}
}
}
This is how i insert the data
private void RegisterUser() {
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emailUser = e1.getText().toString().trim();
String passwordUser = e3.getText().toString().trim();
String name1 = e2.getText().toString();
String id = e5.getText().toString();
String phone = e6.getText().toString();
if (emailUser.isEmpty()){
e1.setError("Email tidak boleh kosong");
}
// jika email not valid
else if (!Patterns.EMAIL_ADDRESS.matcher(emailUser).matches()){
e1.setError("Email tidak valid");
}
// jika password kosong
else if (passwordUser.isEmpty()){
e3.setError("Password tidak boleh kosong");
}
//jika password kurang dari 6 karakter
else if (passwordUser.length() < 6){
e3.setError("Password minimal terdiri dari 6 karakter");
}
else {
//create user dengan firebase auth
auth.createUserWithEmailAndPassword(emailUser,passwordUser)
.addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//jika gagal register do something
if (!task.isSuccessful()){
Toast.makeText(Register.this,
"Register gagal karena "+ task.getException().getMessage(),
Toast.LENGTH_LONG).show();
}
else {
//jika sukses akan menuju ke login activity
if(!isEmpty(e1.getText().toString()) && !isEmpty(e2.getText().toString()) && !isEmpty(e3.getText().toString()) && !isEmpty(e5.getText().toString())&& !isEmpty(e6.getText().toString())) {
submitUser(new User(e1.getText().toString(), e2.getText().toString(), e3.getText().toString(), e5.getText().toString(), e6.getText().toString()));
//Toast.makeText(this,"Wassup",Toast.LENGTH_SHORT).show();
/*startActivity(new Intent(MainActivity.this,MainActivity2.class));*/
//EditText etLocation = (EditText) findViewById(R.id.desc);
SharedPreferences sharedPref = getSharedPreferences("myuser", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("user", emailUser);
editor.apply();
Intent intent = new Intent(Register.this, MainActivity.class);
//intent.putExtra("location", etLocation.getText().toString());
startActivity(intent);
}
else{
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
e1.getWindowToken(), 0);
}
}
}
});
}
}
});
}
private boolean isEmpty(String s) {
return TextUtils.isEmpty(s);
}
private void submitUser(User user) {
database.child("userdesc").push().setValue(user).addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
e1.setText("");
e2.setText("");
e3.setText("");
e4.setText("");
e5.setText("");
e6.setText("");
}
});
}
It seems like there is no valid User object in the data you're processing.
Your JSON is using push IDs for the child nodes under that, while your code is loading from FirebaseAuth.getInstance().getCurrentUser().getUid(). If you want to load the users by their UID, you should store them under their UID, with something like:
mDatabase = FirebaseDatabase.getInstance().getReference().child("sraboetapp").child("userdesc").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
mDatabase.setValue(user);
Based on the code you added to your question submitUser should be:
private void submitUser(User user) {
database.child("userdesc").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user).addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
e1.setText("");
e2.setText("");
e3.setText("");
e4.setText("");
e5.setText("");
e6.setText("");
}
});
}
I have referred to many of the answers but still my app does not show the registration screen when the app opens for first time. I have made use of shared preferences. Any help would be appreciated.Thanks!
MainActivity.java:
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String name;
SharedPreferences prefs = this.getSharedPreferences( "prefs", MODE_PRIVATE);
boolean firstStart=prefs.getBoolean("firstStart",true);
if (firstStart) {
//show start activity
showRegistration();
}
}
private void showRegistration() {
SharedPreferences prefs=getSharedPreferences("prefs",MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("firstStart",false);
editor.apply();
Intent intent =new Intent(MainActivity.this,RegisterActivity.class);
}
}
RegistrationActivity.java:
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "Main Activity";
Firebase mRootRef;
FirebaseAuth mAuth;
EditText mname;
Button mlogin;
Button msignin;
Button mregister;
EditText memail;
EditText maddress;
EditText mconfirmpassword; EditText mpwd;
private void updateUI(FirebaseUser user){
if (user !=null){
Toast.makeText(RegisterActivity.this,"Registration successful",Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
} }
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mRootRef=new Firebase("https://goorgano-8bdfe.firebaseio.com/Users");
msignin=(Button)findViewById(R.id.sign_in_admin);
mAuth = FirebaseAuth.getInstance();
mname=(EditText)findViewById(R.id.username);
mlogin=(Button)findViewById(R.id.login);
memail=(EditText)findViewById(R.id.email);
maddress=(EditText)findViewById(R.id.address);
mconfirmpassword=(EditText)findViewById(R.id.confirmpassword);
mpwd= (EditText)findViewById(R.id.password);
mregister=(Button)findViewById(R.id.register);
mlogin.setOnClickListener(this);
msignin.setOnClickListener(this);
mregister.setOnClickListener(this);
}
public void onClick(View v)
{
int i=v.getId();
if(i==R.id.sign_in_admin)
{
}
else if(i==R.id.login)
{
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
else if(i==R.id.register)
{
createAccount();
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
}
private void createAccount()
{
Log.e(TAG, "createAccount:" + memail.getText().toString());
if (!validateForm(memail.getText().toString(),mpwd.getText().toString(),maddress.getText().toString(),mname.getText().toString()))
{
return;
}
String value=mname.getText().toString();
String key="name";
Firebase childref=mRootRef.child(value);Firebase c=childref;
childref.setValue(value);
value=memail.getText().toString();
String email=value;
key="email";
childref=childref.child(key);
childref.setValue(value);
value=maddress.getText().toString();
String pwd=mpwd.getText().toString();
key="address";
childref=c.child(key);
childref.setValue(value);
mAuth.createUserWithEmailAndPassword(email,pwd)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.e(TAG, "createAccount: Success!");
// update UI with the signed-in user's information
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
Log.e(TAG, "createAccount: Fail!", task.getException());
Toast.makeText(getApplicationContext(), "Authentication failed!", Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
private boolean validateForm(String email, String password, String address, String username)
{
if (TextUtils.isEmpty(email))
{
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return false;
}
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
Toast.makeText(getApplicationContext(), "Enter valid email address!", Toast.LENGTH_SHORT).show();
return false;
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return false;
}
if (TextUtils.isEmpty(username))
{
Toast.makeText(getApplicationContext(), "Enter username!", Toast.LENGTH_SHORT).show();
return false;
}
if (TextUtils.isEmpty(address))
{
Toast.makeText(getApplicationContext(), "Enter address!", Toast.LENGTH_SHORT).show();
return false;
}
if (password.length() < 6)
{
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
}
Update your onCreate with this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String name;
SharedPreferences prefs = this.getSharedPreferences( "prefs", MODE_PRIVATE);
boolean firstStart=prefs.contains("firstStart");
if (!firstStart) {
//show start activity
showRegistration();
}
}
And let me know it worked
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());
}
}
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();
}