How can I get token with Retrofit2? - java

I have a web service link for token login. But in this link, there is no "/" at the end of link. And android studio make error called baseUrl must end in /. When I put / it don't get token and say token is not truth :( because the link is not correct in my think. I use retrofit2library. Please help me to solve it.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://website.net/token")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
UserClient userClient = retrofit.create(UserClient.class);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button loginButton=(Button)findViewById(R.id.btn_login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
/* Intent intentLogin=new Intent(MainActivity.this,MainPageActivity.class);
startActivity(intentLogin);*/
}
});
}
private static String token;
private void login() {
Login login = new Login("abcd", "1234");
Call<User> call = userClient.login(login);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()){
Toast.makeText(MainActivity.this, response.body().getToken(), Toast.LENGTH_SHORT).show();
token = response.body().getToken();
}
else {
Toast.makeText(MainActivity.this, "Token is not truth :(", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Toast.makeText(MainActivity.this, "error!", Toast.LENGTH_SHORT).show();
}
});
}
}
`Login.java
public class Login {
private String user;
private String password;
public Login(String user, String password) {
this.user = user;
this.password = password;
}
}
User.java
public class User {
private int id;
private String email;
private String token;
public int getId(){
return id;
}
public void setId(){
this.id = id;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getToken(){return token;}
public void setToken(String token){this.token = token;}
}
UserClient.java
import com.squareup.okhttp.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
public interface UserClient {
#POST("Login")
Call<User> login(#Body Login login);
// #GET("secretinfo")
// Call<ResponseBody> getSecret(#Header("Authorization") String authToken);
}

Use upto this in
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://website.net/")
.addConverterFactory(GsonConverterFactory.create());
and in the UserClient interface class
public interface UserClient {
#POST("token") Call<User> login(#Body Login login);
}

Related

Android login not validating input

I am new to android development and I am working on a simple inventory app for a project in school. I have everything set up with a room database for the users. Registering users works just fine but currently the authentication of users is not working. It will let you login no matter what you put as the user name and password. I'm not sure what I am doing wrong. All relevant code is attached.
Here is the user DAO:
public interface UserDAO {
#Query("SELECT * FROM User ORDER BY last_name ASC")
LiveData<List<User>> getAllUsers();
#Query("SELECT * FROM User WHERE User.user_name == :userName AND User.password == :password")
LiveData<User> getUser(String userName, String password);
#Insert
void insertUser(User user);
#Update
void updateUser(User user);
#Delete
void deleteUser(User user);
}
Here is the repository:
public class AppRepository {
private InventoryDAO inventoryDAO;
private UserDAO userDAO;
private LiveData<List<Inventory>> allItems;
private LiveData<List<User>> allUsers;
public AppRepository(Application application) {
AppDatabase appDb = AppDatabase.getDatabase(application);
inventoryDAO = appDb.inventoryDAO();
userDAO = appDb.userDAO();
allItems = inventoryDAO.getAllInventory();
allUsers = userDAO.getAllUsers();
}
public LiveData<List<Inventory>> getAllData() { return allItems; }
public LiveData<List<User>> getAllUsersData() {return allUsers;}
public LiveData<Inventory> get(int id) {
return inventoryDAO.get(id);
}
public LiveData<User> getUser(String userName, String password) {
return userDAO.getUser(userName, password); }
//Insert Method
public void insert(Inventory inventory) {
AppDatabase.databaseWriteExecutor.execute(() -> {
inventoryDAO.insertInventory(inventory);
});
}
//Update Method
public void update(Inventory inventory) {
AppDatabase.databaseWriteExecutor.execute(() -> {
inventoryDAO.updateInventory(inventory);
});
}
//Delete Method
public void delete(Inventory inventory) {
AppDatabase.databaseWriteExecutor.execute(() -> {
inventoryDAO.deleteInventory(inventory);
});
}
//User Insert Method
public void insertUser(User user) {
AppDatabase.databaseWriteExecutor.execute(() -> {
userDAO.insertUser(user);
});
}
//User Update Method
public void updateUser(User user) {
AppDatabase.databaseWriteExecutor.execute(()-> {
userDAO.updateUser(user);
});
}
//User Delete Method
public void deleteUser(User user) {
AppDatabase.databaseWriteExecutor.execute(()-> {
userDAO.deleteUser(user);
});
}
}
Here is the view model:
public class UserViewModel extends AndroidViewModel {
public static AppRepository repository;
public final LiveData<List<User>> allUsers;
//constructor
public UserViewModel (Application application) {
super(application);
repository = new AppRepository((application));
allUsers = repository.getAllUsersData();
}
public LiveData<List<User>> getAllUsers() {return allUsers;}
public LiveData<User> getUser(String userName, String password) {
return repository.getUser(userName, password);}
public static void insertUser(User user) {repository.insertUser(user);}
public static void updateUser(User user) {repository.updateUser(user);}
public static void deleteUser(User user) {repository.deleteUser(user);}
}
Finally, here is the login activity:
public class Login extends AppCompatActivity {
private EditText username;
private EditText password;
private Button login;
private Button forgotPassword;
private Button newUser;
private int userId = 0;
private UserViewModel userViewModel;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userViewModel = new ViewModelProvider.AndroidViewModelFactory(Login.this
.getApplication())
.create(UserViewModel.class);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
login = findViewById(R.id.loginBtn);
forgotPassword = findViewById(R.id.forgotPassword);
newUser = findViewById(R.id.newUserBtn);
login.setOnClickListener(view -> {
String userNameText = username.getText().toString();
String userPassword = password.getText().toString();
LiveData<User> user = userViewModel.getUser(userNameText, userPassword);
if (user != null) {
Toast.makeText(getApplicationContext(),
"Redirecting...", Toast.LENGTH_SHORT).show();
Intent newIntent = new Intent(Login.this, MainActivity.class);
Login.this.startActivity(newIntent);
}
else {
Toast.makeText(getApplicationContext(),
"Error wrong credentials", Toast.LENGTH_SHORT).show();
}
});
newUser.setOnClickListener(view -> {
Intent newIntent = new Intent(Login.this, RegisterUser.class);
Login.this.startActivity(newIntent);
});
}
}
Thanks in advance.
I think when you are trying to return LiveData from a Query, the LiveData itself will never be null, but the value inside could be null. So, to check whether the value is null or not, change it to this:
// Check the LiveData value instead of the LiveData itself
if (user.value != null) {
Toast.makeText(getApplicationContext(), "Redirecting...", Toast.LENGTH_SHORT).show();
Intent newIntent = new Intent(Login.this, MainActivity.class);
Login.this.startActivity(newIntent);
} else {
Toast.makeText(getApplicationContext(), "Error wrong credentials", Toast.LENGTH_SHORT).show();
}
I'm not an expert, but i bet it's because of SQL. See if changing == to = helps. This might be helpful
#Query("SELECT * FROM User WHERE User.user_name == :userName AND User.password == :password")
LiveData<User> getUser(String userName, String password);

Null Pointer when trying to retrieve user details from Firebase Realtime Database

In my Android app, I have a database repository to contact Firebase Realtime Database and a service layer with some methods. My SaveUserProfile method works but I keep getting a null pointer on my GetUserFromUid.
The 'user' object it returns is null and I don't know why. The node in my DB is called "users" (all lowercase) and I want to retrieve a user as a model via their userId and display the name and email onscreen.
Can anybody see where I'm going wrong?
My DbContext:
public class DbContext implements IDbContext {
User user = null;
Context context;
DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference("users");
public DbContext(Context context){
super();
this.context = context;
}
#Override
public void AddUserAccount(User user1) {
databaseUsers.child(user1.userId).setValue(user1);
}
#Override
public User GetUserFromFirebase(String uid) {
databaseUsers.child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return user;
}
My DbService:
public class DbService implements IDbService {
//instance of DbContext for firebase handling
private DbContext dbContext;
public DbService(Context context){
super();
dbContext = new DbContext(context);
}
#Override
public User SaveUserProfile(User u) {
dbContext.AddUserAccount(u);
return u;
}
#Override
public User GetUserFromUid(String uid) {
User user = dbContext.GetUserFromFirebase(uid);
return user;
}
My User model:
public class User {
public String userId;
public String name;
public String email;
public String account;
//constructor required for calls to DataSnapshot.getValue(User.class)
public User(){
}
public User(String userId, String name, String email, String account) {
this.userId = userId;
this.name = name;
this.email = email;
this.account = account;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
My activity where I want to display the users' details:
public class DetailsActivity extends AppCompatActivity {
//tag
private static final String TAG = DetailsActivity.class.getSimpleName();
//firebase auth
private FirebaseAuth mAuth;
//variables
private TextView inputName, inputEmail;
private DatabaseReference mFirebaseDatabase;
private String userId;
public String currentUserAccount;
public String teacherAccountNav = "Teacher";
public User userDetails;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
inputName = findViewById(R.id.nameTextView);
inputEmail = findViewById(R.id.emailTextView);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
assert user != null;
userId = user.getUid();
getUserDetails(userId);
inputName.setText(userDetails.name);
inputEmail.setText(userDetails.email);
}
public User getUserDetails(String uid){
DbService dbService = new DbService(this);
userDetails = dbService.GetUserFromUid(uid);
return userDetails;
}
EDITS BELOW
My callback:
public interface Callback {
void myResponseCallback(User user);
}
My EDITED DbContext:
public class DbContext implements IDbContext {
User user = null;
Context context;
DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference("users");
public DbContext(Context context) {
this.context = context;
}
#Override
public void AddUserAccount(User user1) {
databaseUsers.child(user1.userId).setValue(user1);
}
#Override
public void GetUserFromFirebase(String uid, final Callback callback) {
databaseUsers.child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
callback.myResponseCallback(user);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
My EDITED DbService:
public class DbService implements IDbService {
//instance of DbContext for firebase handling
public DbContext dbContext;
public DbService(Context context){
super();
dbContext = new DbContext(context);
}
#Override
public User SaveUserProfile(User u) {
dbContext.AddUserAccount(u);
return u;
}
#Override
public User GetUserFromUid(String uid) {
final User[] user1 = {new User()};
dbContext.GetUserFromFirebase(uid, new Callback() {
#Override
public void myResponseCallback(User user) {
user1[0] = user;
}
});
return user1[0];
}
My EDITED Activity:
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
inputName = findViewById(R.id.nameTextView);
inputEmail = findViewById(R.id.emailTextView);
FirebaseDatabase mFirebaseInstance = FirebaseDatabase.getInstance();
//reference to 'users' node
mFirebaseDatabase = mFirebaseInstance.getReference("users");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
assert user != null;
userId = user.getUid();
getUserFromFirebase(userId);
}
public void getUserFromFirebase(String uid){
userDetails = (new DbService(this)).GetUserFromUid(uid);
inputEmail.setText(userDetails.email);
inputName.setText(userDetails.name);
}
Debug BEFORE edits:
Debug AFTER edits:
As you can see from the debug, before the callback interface, userDetails was null. After the interface implementation, userDetails is not null but all of the object values are null. I don't know why this is as they are filled in the database. Any ideas?

Get values From ViewModel MutableLiveData and display them on textfields

I am trying to get a hang of the Android Architecture Library and i have been trying to display texts from retrofit via a ViewModel using Mutable LiveData on my Main Activity but i cant seem to do it, i would really appreciate some assistance.
Here is my Model Class
public class User {
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("phone")
#Expose
private String phone;
public User() {
}
public String getUserName() {
return name;
}
public void setUserName(String name) {
this.name = name;
}
public String getUserEmail() {
return email;
}
public void setUserEmail(String email) {
this.email = email;
}
public String getUserPhone() {
return phone;
}
public void setUserPhone(String phone) {
this.phone = phone;
}
}
My View model
public class UserViewModel extends AndroidViewModel {
private NodeAuthService api;
private SharedPreferences pref;
private static MutableLiveData<List<User>> userDetails = new
MutableLiveData<>();
private Call<List<User>> call;
public UserViewModel(#NonNull Application application) {
super(application);
api = AuthRetrofitClient.getInstance().create(NodeAuthService.class);
}
private String email = pref.getString("email", "");
public void loadUser(){
call = api.getUser(email);
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>>
response) {
List<User> users = response.body();
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.d("USER",t.getMessage());
}
});
}
public MutableLiveData<List<User>> getUserDetails(){
return userDetails;
}
}
Simplified version of my MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView navName = (TextView) findViewById(R.id.navigation_name);
TextView navEmail = (TextView) findViewById(R.id.navigation_email);
}
Kindly assist
In your viewModel
public void loadUser(){
call = api.getUser(email);
call.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>>
response) {
userDetails.postValue(response.body())
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Log.d("USER",t.getMessage());
}
});
}
And in your Activity observe the changes
yourVm.getUserDetails().observe(this, models -> {
if (models != null) {
for(int = 0; i<models.size();i++){
/*you will get your list here now iterate through list and get
your email_id here.*/
}
}
});
instead of this
List<User> users = response.body();
use this
userDetails.postValue(response.body())
also, remove static before livedata
inside activity oncreate() init your viewModel instance.
then viewModel.getUserDEtails().obsever(this, data-> // your stuff);

How to send 2 parameters in body with retrofit?

Good night everybody.
I need to do a POST request and I'm using Retrofit 2 to do this.
But the Api I'm consuming does not give me these parameters in the API response, just in the body.
Api Response
I already searched in some places but I did not find anything that could help me.
My interface Class
public interface LoginApi {
#POST("api/login")
Call<UserAccount> doLogin(#Body Login login);
}
My Model Class
public class Login {
public String user;
public String password;
}
My API response class
public class UserAccount {
#SerializedName("userId")
#Expose
private Integer userId;
#SerializedName("name")
#Expose
private String name;
#SerializedName("bankAccount")
#Expose
private String bankAccount;
#SerializedName("agency")
#Expose
private String agency;
#SerializedName("balance")
#Expose
private Double balance;
}
My call class
public class LoginPresenter {
private LoginView loginView;
private ServiceConfig serviceConfig;
public LoginPresenter() {
this.loginView = loginView;
if (this.serviceConfig == null) {
this.serviceConfig = new ServiceConfig();
}
}
public void doLogin(Login login) {
serviceConfig
.login()
.doLogin(login)
.enqueue(new Callback<UserAccount>() {
#Override
public void onResponse(Call<UserAccount> call, Response<UserAccount> response) {
UserAccount userAccount = response.body();
assert userAccount != null;
Log.e("Agency:",userAccount.getAgency());
Log.e("BankAccount:", userAccount.getBankAccount());
Log.e("Name:", userAccount.getName());
}
#Override
public void onFailure(Call<UserAccount> call, Throwable t) {
Log.d("Erro", t.getMessage());
}
});
}
}
My Activity
public class LoginActivity extends Activity implements LoginView {
private EditText edtUser, edtPassword;
private Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
}
private void init() {
edtUser = findViewById(R.id.edt_user);
edtPassword = findViewById(R.id.edt_password);
btnLogin = findViewById(R.id.btn_login);
final LoginPresenter loginPresenter = new LoginPresenter();
final Login login = new Login();
login.user = edtUser.getText().toString();
login.password = edtPassword.getText().toString();
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginPresenter.doLogin(login);
}
});
}
#Override
public void userAccount(List<UserAccount> userAccount) {
}
}
I hope I have made my problem clear and that someone who has been through it can help me.
Appreciate.
Pass #Body JsonObject body instead of #Body Login login
Here is full code:
Your interface will be:
public interface LoginApi {
#POST("api/login")
Call<UserAccount> doLogin(#Body JsonObject body);
}
How to Create JsonObject :
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("user", userValue);
jsonObject.addProperty("password", passwordValue);
Pass it from your activity to presenter.
Hope it will works for you.
Thank you.
Pass Like This:-
You Interface
public interface ApiInterface {
String URL_BASE = "Base Url";
#Headers("Content-Type: application/json")
#POST("login")
Call<User> getUser(#Body String body);
}
Activity
public class SampleActivity extends AppCompatActivity implements Callback<User> {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
// prepare call in Retrofit 2.0
try {
JSONObject paramObject = new JSONObject();
paramObject.put("email", "sample#gmail.com");
paramObject.put("pass", "4384984938943");
Call<User> userCall = apiInterface.getUser(paramObject.toString());
userCall.enqueue(this);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onResponse(Call<User> call, Response<User> response) {
}
#Override
public void onFailure(Call<User> call, Throwable t) {
}
}

Creating link between Firebase real-time database and authenticated users

So far I have successfully implemented Firebase within my Android application, where I can add users to the Authentication portal through a SignUpActivity, and also add maintenance issues to the real-time database through a MaintenanceActivity.
However, at present, none of the database data is linked to specific users, which is what I want to achieve. So essentially at the moment when I log in as an arbitrary user, the same data will always come up.
Presumably, and having read several other threads on this, the User UID will be required here and will need to be present for every maintenance record.
I'm not sure, however, how I can implement this. Possibly a layer of authentication needs implemented into the MainActivity?
Finding it hard to get my head around this, so any help on this would be much appreciated.
SignUpActivity
mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
final DatabaseReference[] ref = new DatabaseReference[1];
final FirebaseUser[] mCurrentUser = new FirebaseUser[1];
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
if (task.isSuccessful()) {
mCurrentUser[0] = task.getResult().getUser();
ref[0] =mDatabase.child(mCurrentUser[0].getUid());
ref[0].child("email").setValue(email);
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
});
You can implement it like this:
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
DatabaseReference ref;
FirebaseUser mCurrentUser;
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
if (task.isSuccessful()) {
mCurrentUser= task.getResult().getUser();
ref=mDatabase.child(mCurrentUser.getUid());
ref.child("email").setValue(email);
ref.child("name").setValue(name);
}
});
You can implement it like the above, then in your db you will have:
Users
userid
name: userx
email: userx#gmail.com
After you authenticate the user using createUserWithEmailAndPassword(email, password), you can then retrieve the email and name, and whatever extra data was written and send it to the database.
This mCurrentUser.getUid() will give you the userid, that you can use in the database.
After adding your project to the firebase
U can also try this.
public class RegisterActivity extends AppCompatActivity implements
View.OnClickListener {
private static final String TAG = "MAGIC";
Firebase mref =null;
private User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Firebase.setAndroidContext(this);
mAuth = FirebaseAuth.getInstance();
}
#Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_new_email);
password = (EditText) findViewById(R.id.edit_text_new_password);
}
#Override
public void onStop() {
super.onStop();
}
//This method sets up a new User by fetching the user entered details.
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString().trim());
user.setPassword(password.getText().toString().trim());
}
#Override
public void onClick(View v) {
//paste your firebase database link address here.
mref = new Firebase("https://citypride-97902.firebaseio.com/");
createNewAccount(email.getText().toString(),
password.getText().toString());
}
private void createNewAccount(String email, String password) {
Log.d(TAG, "createNewAccount:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "Register Successfully " + task.isSuccessful());
hideProgressDialog();
if (!task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Registration failed.",
Toast.LENGTH_SHORT).show();
hideProgressDialog();
} else {
onAuthenticationSuccess(task.getResult().getUser());
Toast.makeText(RegisterActivity.this, "Register Successful.",
Toast.LENGTH_SHORT).show();
} hideProgressDialog();
}
});
}
private void onAuthenticationSuccess(FirebaseUser mUser) {
// Write new user
saveNewUser(mUser.getUid(), user.getEmail(), user.getPassword());
signOut();
// Go to LoginActivity
Intent i =new Intent(LoginActivity.this, YourActivity.class);
startActivity(i);
}
private void saveNewUser(String userId,
String email, String password) {
User user = new User(userId,email,password);
mref.child("Users").child(name).setValue(user);
}
private void signOut() {
mAuth.signOut();
}
//This method, validates email address and password
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
Toast.makeText(getApplicationContext(),"please enter valid
email",Toast.LENGTH_LONG).show();
}
if (userEmail.isEmpty() && userPassword.isEmpty()){
Toast.makeText(getApplicationContext(),"all fields are
mandatory",Toast.LENGTH_LONG).show();
}
return valid;
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
Below is User class
class User {
private String id;
private String email;
private String password;
public User() {
}
public User(String id,String email, String password) {
this.id = id;
this.email = email;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
this will show email and password field in your firebase database.

Categories

Resources