I need to retrieve the data that i have stored in the Firebase database. But it shows that the UIDs are different in authentication part and database part.
UPDATE : Now i am facing problems while trying to fetch data from the firebase. I want to display it in a ListView. When i go from the Login Activity(after successful login) to the General Activity (where i put the ListView), it does not show up and the Activity switches from General to the Login one. I am attaching the code segments at the bottom under "UPDATE CODE" .
Help would be highly appreciated. Thanks!
Here is the code for registration
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
setUpUIviews();
firebaseAuth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance().getReference().child("users");
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()){
String user_email = REmail.getText().toString().trim();
String user_password = RPass.getText().toString().trim();
firebaseAuth.createUserWithEmailAndPassword(user_email,user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
updateData();
Toast.makeText(Registration.this,"Registration Successful! ",Toast.LENGTH_SHORT).show();
startActivity(new Intent(Registration.this,MainActivity.class));
}else {
Toast.makeText(Registration.this,"Registration Unsuccessful ",Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
And this is the update data part:
private void updateData(){
String uName = RName.getText().toString().trim();
String uEmail = REmail.getText().toString().trim();
String id = db.push().getKey();
ProfileUpdate profileUpdate = new ProfileUpdate(uName,uEmail);
db.child(id).setValue(profileUpdate);
Toast.makeText(this,"Added info",Toast.LENGTH_SHORT).show();
}
UPDATE CODE
Login Activity
public class LoginPage extends AppCompatActivity {
private TextView userRegistration;
private TextView Info;
private EditText LName;
private EditText LPass;
private Button LSignIn;
private int counter = 3;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loginpage);
userRegistration = (TextView)findViewById(R.id.tvRegister);
LName = (EditText)findViewById(R.id.btnName);
LPass = (EditText)findViewById(R.id.btnPass);
LSignIn = (Button) findViewById(R.id.btnSignIn);
Info = (TextView) findViewById(R.id.tvInfo);
Info.setText( " No of attempts remaining: 3 " );
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
FirebaseUser user= null;
if(user!=null){
finish();
startActivity(new Intent(LoginPage.this,General.class));
}
user = firebaseAuth.getCurrentUser();
LSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(LName.getText().toString(),LPass.getText().toString());
}
});
userRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginPage.this,Registration.class));
}
});
}
private void validate(String username, String password){
progressDialog.setMessage("Processing your request.... ");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(username,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
progressDialog.dismiss();
Toast.makeText(LoginPage.this,"Login successful!",Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginPage.this,General.class));
}else {
Info.setText("No of attempts remaining: " + String.valueOf(counter-1));
Toast.makeText(LoginPage.this,"Please enter corrent credentials",Toast.LENGTH_SHORT).show();
counter --;
progressDialog.dismiss();
if(counter<=0){
LSignIn.setEnabled(false);
}
}
}
});
}
}
General Activity
public class General extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private Button Logout;
ListView l1;
ArrayAdapter<String> adapter;
DatabaseReference databaseReference;
FirebaseUser user;
List<String> itemlist;
String uid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general);
firebaseAuth = FirebaseAuth.getInstance();
Logout = (Button) findViewById(R.id.btnLogout);
l1 = (ListView)findViewById(R.id.listView);
user = FirebaseAuth.getInstance().getCurrentUser();
uid = user.getUid();
itemlist = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
itemlist.clear();;
String user_name = dataSnapshot.child(uid).child("usrName").getValue(String.class);
String user_email = dataSnapshot.child(uid).child("ursEmail").getValue(String.class);
itemlist.add(user_name);
itemlist.add(user_email);
adapter = new ArrayAdapter<>(General.this,android.R.layout.simple_list_item_1,itemlist);
l1.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
finish();
startActivity(new Intent(General.this, MainActivity.class));
}
});
}
}
activity_general.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/myApp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".General">
<Button
android:id="#+id/btnLogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="LOGOUT"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.467"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/listView" />
<ListView
android:id="#+id/listView"
android:layout_width="368dp"
android:layout_height="270dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
The Design
enter image description here
This is the code of how you store the user data into the datbase:
String id = db.push().getKey();
ProfileUpdate profileUpdate = new ProfileUpdate(uName,uEmail);
db.child(id).setValue(profileUpdate);
In the first line you call push().getKey() to get a new unique ID from the database SDK. This ID is not related to the user profile.
If you want to store the users in the database under their UID, you will need to get the UID from the AuthResult just after you created the user. Something like:
String uid = task.getResult().getUser().getUid();
When you pass this uid to your updateData method, you then create the child node the database with:
db.child(uid).setValue(profileUpdate);
Related
I have been following a tutorial to create an app like Tinder for my project and I am learning databasing. I have set up the code as the tutorial said within the version of Android Studio I have, yet when I register users, they don't appear in the database despite the profiles passing authentication. I have set the rules to true and it still hasn't solved my problem. The only thing I can possibly think of is that my database is set to Belgium West Europe over the USA as all tutorials for Firebase show USA as the database location. If anyone has any suggestions please drop them in, thank you.
Ps: Here is the tutorial link https://www.youtube.com/watch?v=_thTn8SDjC8&list=PLxabZQCAe5fio9dm1Vd0peIY6HLfo5MCf&index=5
public class RegistrationActivity extends AppCompatActivity {
private Button mRegister;
private EditText mEmail, mPassword, mName;
private RadioGroup mRadioGroup;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user !=null) {
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mRegister = (Button) findViewById(R.id.register);
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mName = (EditText) findViewById(R.id.name);
mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selectId = mRadioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = (RadioButton) findViewById(selectId);
if(radioButton.getText() == null){
return;
}
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
final String name = mName.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
Toast.makeText(RegistrationActivity.this, "Error Signing In", Toast.LENGTH_SHORT).show();
}else{
String userId = mAuth.getCurrentUser().getUid();
DatabaseReference currentUserDb = FirebaseDatabase.getInstance().getReference().child(radioButton.getText().toString()).child(userId).child("name");
currentUserDb.setValue(name);
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthStateListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthStateListener);
}
}
I found out through experimentation that the database MUST be set to USA and not Belgium. It's still unclear as to exactly why this is but starting a new database with the USA location seemed to have worked with registering users to the database
I have a Problem in the login. Basically, I tell you my scenario.
I have two apps both are connected with a single firebase project.
One app contains driver login and other app contain customer login
When I open a customer app and register the new customer. The customer is successfully registered. And then I open the driver app and entered the customer credential means (Customer email & password) its login successfully and open the driver activity and vice-versa.
how to fix this issue I am using firebase.
customer login activity
public class CustomerLoginActivity extends AppCompatActivity {
private EditText mEmail, mPassword;
private Button mLogin, mRegistration;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_login);
mAuth = FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user!=null ){
Intent intent = new Intent(CustomerLoginActivity.this, CustomerMapActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.login);
mRegistration = (Button) findViewById(R.id.registration);
mRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(CustomerLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(CustomerLoginActivity.this, "sign up error", Toast.LENGTH_SHORT).show();
}else{
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Customers").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(CustomerLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(CustomerLoginActivity.this, "sign in error", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
}
driver login activity
public class DriverLoginActivity extends AppCompatActivity {
private EditText mEmail, mPassword;
private Button mLogin, mRegistration;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_login);
mAuth = FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
Intent intent = new Intent(DriverLoginActivity.this, DriverMapActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.login);
mRegistration = (Button) findViewById(R.id.registration);
mRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(DriverLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(DriverLoginActivity.this, "sign up error", Toast.LENGTH_SHORT).show();
}else{
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Drivers").child(user_id).child("name");
current_user_db.setValue(email);
}
}
});
}
});
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(DriverLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(DriverLoginActivity.this, "sign in error", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
}
My database rules
Firebase authentication doesn't differentiate between different "types" of users, like you're trying to do. You'll have to implement some custom logic of your own in your app(s) to handle these situations. The base signInWithEmailAndPassword() method will always work if you provide it correct credentials... so what you need to do is in your app code, BEFORE you call the signInWithEmailAndPassword() method, check to see if the provided username is "allowed" to use this version of the app...
So as soon as you get their username, before calling that signIn method, make a query to the database to determine whether that username belongs to a "customer" or a "driver". I assume you have something like a /users node in your database - if you don't, you'll need to create one, there's no way around it. If you're not sure how to query the database, use the addListenerForSingleValueEvent() method... check out the official docs for examples/syntax.
Once you've determined whether the username is for a customer vs a driver... you will need to implement logic to decide whether they are allowed to proceed to the signIn method.
If they are a "customer" and this is the "customer" app, then allow the code to proceed to the signIn method... but if the username comes back as a "driver" then stop the code and display an error to the user.
Similarly for the "driver" app, if the username comes back as being for a "driver" then allow the code to proceed to the signIn method... but if it comes back as a "customer" then stop the code and display an error to the user.
I seem to have altered something in my code and I can't figure out what it is I need to revert.
I'm building an app that will have a MainActivity that will lead to a loginActivity. However, when the login button is pressed the app is now skipping that and going to a MapActivity that should only be visible to logged in users.
I've checked my MainActivity code and I don't think the problem is there, I think it's the LoginActivity code:
public class ResponderLoginActivity extends AppCompatActivity {
private EditText mEmail, mPassword;
private Button mLogin, mRegistration;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_responder_login);
mAuth = FirebaseAuth.getInstance();
firebaseAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
Intent intent = new Intent(ResponderLoginActivity.this, ResponderMapActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mEmail = (EditText) findViewById(R.id.email);
mPassword = (EditText) findViewById(R.id.password);
mLogin = (Button) findViewById(R.id.login);
mRegistration = (Button) findViewById(R.id.registration);
mRegistration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(ResponderLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(ResponderLoginActivity.this, "sign up error", Toast.LENGTH_SHORT).show();
} else {
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Responders").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(ResponderLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(ResponderLoginActivity.this, "Sign in error", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthListener);
}
}
My Database in firebase is in this format
I need that if a user login then for that particular UID I need his associated department name. So How to take the department name as a String.I use this code to fetch department name
String u_id=auth.getCurrentUser().getUid();
mdatabase=FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
user=mdatabase.getKey();
By this i don't get the result.Please provide solution
public class LoginPage extends AppCompatActivity {
private Button btnLogin;
private TextView ForgetText;
private EditText userText,PassText;
private String UserEmail,UserPassword;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener mAuthlistener;
private ProgressBar progressBar;
private DatabaseReference mdatabase;
public String departmental;
//private Spinner dropdown;
Variables v=new Variables();
private String username,user;
private Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
auth=FirebaseAuth.getInstance();
btnLogin=(Button)findViewById(R.id.btn_login);
ForgetText=(TextView)findViewById(R.id.textView3);
userText=(EditText)findViewById(R.id.email2);
PassText=(EditText)findViewById(R.id.password2);
progressBar=(ProgressBar)findViewById(R.id.progressBar2);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SignIn();
}
});
ForgetText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginPage.this,ForgotPassword.class));
}
});
}
public void SignIn(){
UserEmail=userText.getText().toString().trim();
UserPassword=PassText.getText().toString().trim();
if (UserEmail.isEmpty()){
Toast.makeText(LoginPage.this,"Please Enter the Email
Id",Toast.LENGTH_LONG).show();
}
else if (UserPassword.isEmpty())
{
Toast.makeText(LoginPage.this,"Please enter Valid
Password",Toast.LENGTH_LONG).show();
}
else {
auth.signInWithEmailAndPassword(UserEmail, UserPassword)
.addOnCompleteListener(LoginPage.this, new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If
sign in succeeds
// the auth state listener will be notified and logic
to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
// there was an error
Toast.makeText(LoginPage.this,"Error in
logging!!",Toast.LENGTH_LONG).show();
} else
{
if(FirebaseAuth.getInstance().getCurrentUser().getEmail().equals(v.admin))
startActivity(new
Intent(LoginPage.this,AdminUser.class));
else {
String u_id =
auth.getInstance().getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String department = (String) dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mdatabase.addListenerForSingleValueEvent(eventListener);
Toast.makeText(LoginPage.this,u_id,Toast.LENGTH_LONG).show();
Toast.makeText(LoginPage.this,departmental,Toast.LENGTH_LONG).show();
/*i = new Intent(LoginPage.this, LoggedIn.class);
i.putExtra("hello_user",department);
startActivity(i);*/
}
Toast.makeText(LoginPage.this, "Logged In", Toast.LENGTH_LONG).show();
}
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
Please use this code:
String u_id = auth.getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String department = (String) dataSnapshot.getValue();
Log.d("TAG", department);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mdatabase.addListenerForSingleValueEvent(eventListener);
Hope it helps.
Does any one have any experience with creating unit-test for the On Create and OnClick method in java, using Android Studio? I use data from my Firebasedatabase.
I think I have to use Mock-object, but I don't knot where to start.
Under is the code from my class LoginActivity
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mfireBaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
mProgressDialog = new ProgressDialog(this);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonSignIn = (Button) findViewById(R.id.buttonSignIn);
textViewSignUp = (TextView) findViewById(R.id.textViewSignUp);
buttonSignIn.setOnClickListener(this);
textViewSignUp.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == buttonSignIn){
usersignin();
}
if(v==textViewSignUp){
startActivity(new Intent(this, RegisterActivity.class));
}
}
private void usersignin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter Email", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter password", Toast.LENGTH_SHORT).show();
return;
}
mProgressDialog.setMessage("Logging in. Please wait...");
mProgressDialog.show();
mfireBaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mProgressDialog.dismiss();
if(task.isSuccessful()){
getSignedInUserProfile();
}
}
});
}
private void getSignedInUserProfile() {
DatabaseReference reference = mDatabase;//.child("eduback-2feef");
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
userID = firebaseUser.getUid();
reference.child("Users").child(userID).child("User info").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if(user != null) {
// Save if the user is student or prof in shared prefs.
PreferenceHelper helper = new PreferenceHelper(getBaseContext());
helper.setIsStudent(user.isStudent);
checkStudentOrProfessor(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Ups vis error
}
});
}
private void checkStudentOrProfessor(User user) {
Intent i;
if (user.isStudent ) {
i = new Intent(this, MainActivityStudent.class);
} else {
i = new Intent(this, MainActivityProfessor.class);
}
startActivity(i);
}
}
The Mockito mocking framework for Java offers compatibility with Android unit testing.
You can configure mock objects to return some specific value when invoked.
You don't need to test Firebasedatabass.
But you have to make Firebasedatabase wrapper class for yours view
Wrapper class have to include variable(userID, user.isStudent)