Android Studio, My Activities are going to the wrong activity - java

so I am a fresh face to android development, and I encountered a problem which I have been going loops for.
I have three activities here, they are for registration, I don't want to implement scrollview because it isn't that good looking so I made it to three form activities,
The first activity gathers all info from the XML's and passes the values as via intent to the second activity,
then the second activity gathers all info from it's own XML, and then passes it together with the Extra of the first activity to the third activity, and the third activity together with the first and seconds Extras PLUS it's own values from it's own XML's, finally, saves the values to firebase.
Yes the values get's saved, but my problem is the third activity doesn't go to the Welcome class which is supposedly written on its intent. I tried rebuilding and cleaning but it did not work. I couldn't find the bug to my work, can anyone help me out? any help is appreciated. Thanks
Here are my three java classes, and I will also put in the welcome class incase you might want to ask for it:
Profile.java
public class Profile extends Activity {
//DECLARE FIELDS
EditText name,username, phone, age, birth;
Button saveBtn;
//FIREBASE REF
DatabaseReference userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//FIREBASE DATABASE REF
userRef = FirebaseDatabase.getInstance().getReference("Users");
//ASSIGN ID's
saveBtn = (Button) findViewById(R.id.profileBtn);
name = (EditText) findViewById(R.id.profileName);
username = (EditText) findViewById(R.id.profileUsername);
age = (EditText) findViewById(R.id.profileAge);
phone = (EditText) findViewById(R.id.profilePhone);
birth = (EditText) findViewById(R.id.profileBirth);
// SAVE BUTTON LOGIC
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addUser();
}
});
}
private void addUser(){
String userNameString = name.getText().toString();
String userPhoneString = phone.getText().toString();
String userAgeString = age.getText().toString();
String userBirthString = birth.getText().toString();
String userUserNameString = username.getText().toString();
//GET USER KEY FROM INTENT
String userKey = getIntent().getStringExtra("USER_KEY");
String userEmail = getIntent().getStringExtra("USER_EMAIL");
String userPass = getIntent().getStringExtra("USER_PASS");
String userID = getIntent().getStringExtra("USER_ID");
if (!TextUtils.isEmpty(userNameString) && !TextUtils.isEmpty(userPhoneString) && !TextUtils.isEmpty(userAgeString) && !TextUtils.isEmpty(userBirthString) && !TextUtils.isEmpty(userUserNameString)) {
Toast.makeText(Profile.this, "Next!", Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Profile.this, Profile2.class);
myIntent.putExtra("USER_KEY", userKey);
myIntent.putExtra("USER_NAME", userNameString);
myIntent.putExtra("USER_PHONE", userPhoneString);
myIntent.putExtra("USER_AGE", userAgeString);
myIntent.putExtra("USER_BIRTH", userBirthString);
myIntent.putExtra("USER_USERNAME", userUserNameString);
myIntent.putExtra("USER_EMAIL", userEmail);
myIntent.putExtra("USER_PASS", userPass);
myIntent.putExtra("USER_ID", userID);
startActivity(myIntent);
} else {
Toast.makeText(Profile.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile.this, Profile.class));
}
}
}
Profile2.java
public class Profile2 extends Activity {
//DECLARE FIELDS
EditText Address, FSN, bType, Height, Weight;
Button saveBtn;
//FIREBASE REF
DatabaseReference userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile2);
//FIREBASE DATABASE REF
userRef = FirebaseDatabase.getInstance().getReference("Users");
//ASSIGN ID's
saveBtn = (Button) findViewById(R.id.profileBtn);
Address = (EditText) findViewById(R.id.Address);
FSN = (EditText) findViewById(R.id.FSN);
bType = (EditText) findViewById(R.id.bType);
Height = (EditText) findViewById(R.id.Height);
Weight = (EditText) findViewById(R.id.Weight);
//MOVE TO LOGIN
// SAVE BUTTON LOGIC
saveBtn.setOnClickListener(new View.OnClickListener() {
// #RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View view) {
addUser();
}
});
}
private void addUser(){
String AddressString = Address.getText().toString();
String FSNString = FSN.getText().toString();
String WeightString = Weight.getText().toString();
String bTypeString = bType.getText().toString();
String HeightString = Height.getText().toString();
//GET USER KEY FROM INTENT
String userKey = getIntent().getStringExtra("USER_KEY");
String userNameString = getIntent().getStringExtra("USER_NAME");
String userPhoneString = getIntent().getStringExtra("USER_PHONE");
String userAgeString = getIntent().getStringExtra("USER_AGE");
String userBirthString = getIntent().getStringExtra("USER_BIRTH");
String userUserNameString = getIntent().getStringExtra("USER_USERNAME");
String userPass = getIntent().getStringExtra("USER_PASS");
String userID = getIntent().getStringExtra("USER_ID");
String userEmail = getIntent().getStringExtra("USER_EMAIL");
if (!TextUtils.isEmpty(AddressString) && !TextUtils.isEmpty(FSNString) && !TextUtils.isEmpty(WeightString) && !TextUtils.isEmpty(bTypeString) && !TextUtils.isEmpty(HeightString)) {
Toast.makeText(Profile2.this, "Go mamshie!", Toast.LENGTH_LONG).show();
Intent myIntent2 = new Intent(Profile2.this, Profile3.class);
myIntent2.putExtra("USER_KEY", userKey);
myIntent2.putExtra("USER_NAME", userNameString);
myIntent2.putExtra("USER_PHONE", userPhoneString);
myIntent2.putExtra("USER_AGE", userAgeString);
myIntent2.putExtra("USER_BIRTH", userBirthString);
myIntent2.putExtra("USER_USERNAME", userUserNameString);
myIntent2.putExtra("USER_ADDRESS", AddressString);
myIntent2.putExtra("USER_FSN", FSNString);
myIntent2.putExtra("USER_BTYPE", bTypeString);
myIntent2.putExtra("USER_HEIGHT", HeightString);
myIntent2.putExtra("USER_WEIGHT", WeightString);
myIntent2.putExtra("USER_PASS", userPass);
myIntent2.putExtra("USER_ID", userID);
myIntent2.putExtra("USER_EMAIL", userEmail);
startActivity(myIntent2);
} else {
Toast.makeText(Profile2.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile2.this, Profile2.class));
}
}
}
Profile3.java
public class Profile3 extends Activity {
//DECLARE FIELDS
EditText NPP, PCS, MC, SB, PPH;
Button saveBtn;
//FIREBASE REF
DatabaseReference mDataRef, userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile3);
//FIREBASE DATABASE REF
userRef = FirebaseDatabase.getInstance().getReference("Users");
//ASSIGN ID's
saveBtn = (Button) findViewById(R.id.profileBtn);
NPP = (EditText) findViewById(R.id.previous);
PCS = (EditText) findViewById(R.id.previouscs);
MC = (EditText) findViewById(R.id.miscar);
SB = (EditText) findViewById(R.id.stillbirth);
PPH = (EditText) findViewById(R.id.post);
//MOVE TO LOGIN
// SAVE BUTTON LOGIC
saveBtn.setOnClickListener(new View.OnClickListener() {
// #RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View view) {
addUser();
}
});
}
private void addUser(){
String NoPrevPregnancies = NPP.getText().toString();
String PreviousCS = PCS.getText().toString();
String Miscarriages = MC.getText().toString();
String Stillbirth = SB.getText().toString();
String PostPartumHem = PPH.getText().toString();
//GET USER KEY FROM INTENT
String userKey = getIntent().getStringExtra("USER_KEY");
String userEmail = getIntent().getStringExtra("USER_EMAIL");
String userPass = getIntent().getStringExtra("USER_PASSWORD");
String userID = getIntent().getStringExtra("USER_ID");
String userNameString = getIntent().getStringExtra("USER_NAME");
String userPhoneString = getIntent().getStringExtra("USER_PHONE");
String userAgeString = getIntent().getStringExtra("USER_AGE");
String userBirthString = getIntent().getStringExtra("USER_BIRTH");
String userUserNameString = getIntent().getStringExtra("USER_USERNAME");
String AddressString = getIntent().getStringExtra("USER_ADDRESS");
String FSNString = getIntent().getStringExtra("USER_FSN");
String bTypeString = getIntent().getStringExtra("USER_BTYPE");
String HeightString = getIntent().getStringExtra("USER_HEIGHT");
String WeightString = getIntent().getStringExtra("USER_WEIGHT");
mDataRef = userRef.child(userNameString);
if (!TextUtils.isEmpty(PreviousCS) && !TextUtils.isEmpty(NoPrevPregnancies) && !TextUtils.isEmpty(PostPartumHem) && !TextUtils.isEmpty(Miscarriages) && !TextUtils.isEmpty(Stillbirth)) {
User3 user = new User3(PreviousCS, NoPrevPregnancies, PostPartumHem, Miscarriages, Stillbirth);
userRef.child(userNameString).setValue(user);
mDataRef.child("USER_KEY").setValue(userKey);
mDataRef.child("USER_PASS").setValue(userPass);//
mDataRef.child("USER_ID").setValue(userID);//
mDataRef.child("USER_NAME").setValue(userNameString);//
mDataRef.child("USER_PHONE").setValue(userPhoneString);
mDataRef.child("USER_AGE").setValue(userAgeString);
mDataRef.child("USER_BIRTH").setValue(userBirthString);
mDataRef.child("USER_USERNAME").setValue(userUserNameString);//
mDataRef.child("USER_ADDRESS").setValue(AddressString);
mDataRef.child("USER_FSN").setValue(FSNString);
mDataRef.child("USER_BTYPE").setValue(bTypeString);
mDataRef.child("USER_HEIGHT").setValue(HeightString);
mDataRef.child("USER_WEIGHT").setValue(WeightString);
mDataRef.child("USER_EMAIL").setValue(userEmail);//
Toast.makeText(Profile3.this, "User Details Completed and Saved!", Toast.LENGTH_LONG).show();
Intent myIntent1 = new Intent(Profile3.this, Welcome.class);
myIntent1.putExtra("USER_KEY", userKey);
myIntent1.putExtra("USER_EMAIL", userEmail);
myIntent1.putExtra("USER_PHONE", userPhoneString);
myIntent1.putExtra("USER_BIRTH", userBirthString);
myIntent1.putExtra("USER_USERNAME", userUserNameString);
myIntent1.putExtra("USER_NAME", userNameString);
myIntent1.putExtra("USER_AGE", userAgeString);
myIntent1.putExtra("USER_ID", userID);
startActivity(myIntent1);
} else {
Toast.makeText(Profile3.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile3.this, Profile3.class));
}
}
}
My welcome activity which gets some data and shows it
public class Welcome extends AppCompatActivity {
private static final String TAG = "ViewDatabase";
//ADD FIREBASE STUFF
//DECLARE FIELDS
Button outBtn;
TextView welcome;
private DatabaseReference myRef, mDataRef, userRef;
private FirebaseDatabase mFirebaseDatabase;
private String userIDPassed;
private String userID;
private String userKey;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private ListView mListView;
//FIREBASE AUTH FIELDS
private FirebaseAuth nAuth;
private FirebaseAuth.AuthStateListener nAuthlistener;
//GET USER KEY FROM INTENT
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
//DRAWER LAYOUT
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
//ASSIGN IDS
outBtn = (Button) findViewById(R.id.logoutBtn);
welcome = (TextView) findViewById(R.id.WelcomeName);
mListView = (ListView) findViewById(R.id.listview);
//ASSIGN INSTANCE
myRef = FirebaseDatabase.getInstance().getReference().child("Users");
nAuth = FirebaseAuth.getInstance();
userRef = FirebaseDatabase.getInstance().getReference("Users");
FirebaseUser User = nAuth.getCurrentUser();
userID = User.getUid();
//navigation Drawer
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView mNavigationView = (NavigationView) findViewById(R.id.nav_menu);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){
#Override public boolean onNavigationItemSelected(MenuItem menuItem)
{ switch (menuItem.getItemId())
{
case(R.id.nav_account): Intent accountActivity = new Intent(getApplicationContext(), Welcome.class);
startActivity(accountActivity);
break;
case(R.id.nav_exercises): Intent accountActivity1 = new Intent(getApplicationContext(), Video.class);
startActivity(accountActivity1);
break;
case(R.id.nav_tips): Intent accountActivity2 = new Intent(getApplicationContext(), Image.class);
startActivity(accountActivity2);
break;
case(R.id.nav_scheduler): Intent accountActivity3 = new Intent(getApplicationContext(), CalendarActivity.class);
startActivity(accountActivity3);
break;
case(R.id.nav_logout): Intent accountActivity4 = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(accountActivity4);
finish();
break;
case(R.id.nav_settings): Intent accountActivity5 = new Intent(getApplicationContext(), Profile.class);
startActivity(accountActivity5);
break;
case(R.id.nav_info): Intent accountActivity6 = new Intent(getApplicationContext(), Info.class);
startActivity(accountActivity6);
break;
}
return true;
} });
//Navigation Drawer
nAuthlistener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser User = firebaseAuth.getCurrentUser();
if (User != null){
Log.d(TAG, "onAuthStateChanged:signed_in:" + User.getUid());
Toast.makeText(Welcome.this, "Successfully signed in with: " + User.getEmail(), Toast.LENGTH_LONG).show();
}else{
Log.d(TAG, "onAuthStateChanged:signed_out" + userID);
Toast.makeText(Welcome.this, "Successfully signed out.", Toast.LENGTH_LONG).show();
}
}
};
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot){
showData(dataSnapshot);
}
#Override
public void onCancelled (DatabaseError databaseError){
}
});
outBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
nAuth.signOut();
finish();
startActivity(new Intent(Welcome.this, MainActivity.class));
}
});
}
private void showData(DataSnapshot dataSnapshot) {
//GET USER KEY FROM INTENT
String userKey = getIntent().getStringExtra("USER_KEY");
String userEmail = getIntent().getStringExtra("USER_EMAIL");
String userPhone = getIntent().getStringExtra("USER_PHONE");
String userBirth = getIntent().getStringExtra("USER_BIRTH");
String userUserName = getIntent().getStringExtra("USER_USERNAME");
String userName = getIntent().getStringExtra("USER_NAME");
String userAge = getIntent().getStringExtra("USER_AGE");
String userID = getIntent().getStringExtra("USER_ID");
mDataRef = userRef.child(userName);
if (!TextUtils.isEmpty(userKey) && !TextUtils.isEmpty(userEmail) && !TextUtils.isEmpty(userID) && !TextUtils.isEmpty(userBirth) && !TextUtils.isEmpty(userUserName)) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
Log.d(TAG, "showData: snapshot: " + ds);
Log.d(TAG, "showData: snapshot: " + ds.child("Users"));
//display all info taken
Log.d(TAG, "showData: USER_NAME: " + userName);
Log.d(TAG, "showData: USER_AGE: " + userAge);
Log.d(TAG, "showData: USER_BIRTH: " + userBirth);
Log.d(TAG, "showData: USER_PHONE: " + userPhone);
Log.d(TAG, "showData: USER_USERNAME: " + userUserName);
ArrayList<String> array = new ArrayList<>();
array.add(userName);
array.add(userAge);
array.add(userBirth);
array.add(userPhone);
array.add(userUserName);
ArrayAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);
}
} else {
}
}
#Override
protected void onStart() {
super.onStart();
nAuth.addAuthStateListener(nAuthlistener);
}
#Override
protected void onStop() {
super.onStop();
nAuth.removeAuthStateListener(nAuthlistener);
}
//FOR NAVIGATION DRAWER
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
//Navigation Drawer End
}
What did I do wrong? Thinking of it as flowing water, I think the values flowed well until the last activity?

in your profile1, change the intent to profiles, profile2 eg
Toast.makeText(Profile.this, "Please Enter Correct Profile Details!", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile.this, Profile2.class));
and do same for profile 2 and profile 3.

Try debugging by removing your else statements and maybe add them all to the last activity

Related

How to add auto uid field in Firebase Firestore

I want to add an auto uid field in the firebase firestore when a user register their account. How to implement that in my codes to add uid which is generated by the firebase?
Here is my register.java codes:
public class Register extends AppCompatActivity {
//Variables
TextInputLayout username, email, PhoneNo, password;
RadioGroup radioGroup;
RadioButton selectedElderly, selectedGuardian;
Button regBtn, regToLoginBtn;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
//Hooks to all xml elements in activity_register.xml
username = findViewById(R.id.reg_username);
email = findViewById(R.id.reg_email);
PhoneNo = findViewById(R.id.reg_phoneNo);
password = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regToLoginBtn = findViewById(R.id.reg_login_btn);
radioGroup = findViewById(R.id.radio_type);
selectedGuardian = findViewById(R.id.radioGuardian);
selectedElderly = findViewById(R.id.radioElderly);
regToLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
}
});
regBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validateUsername() && validateEmail() && validatePhoneNo() && validateUserType() && validatePassword() == true) {
Intent intent = new Intent(Register.this, Login.class);
startActivity(intent);
} else {
validateUsername();
validateEmail();
validatePhoneNo();
validateUserType();
validatePassword();
}
fAuth.createUserWithEmailAndPassword(email.getEditText().getText().toString(), password.getEditText().getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
FirebaseUser user = fAuth.getCurrentUser();
Toast.makeText(Register.this, "Account Created", Toast.LENGTH_SHORT).show();
DocumentReference df = fStore.collection("Users").document(user.getUid());
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("Username", username.getEditText().getText().toString());
userInfo.put("Email", email.getEditText().getText().toString());
userInfo.put("phoneNo", PhoneNo.getEditText().getText().toString());
userInfo.put("Password",password.getEditText().getText().toString());
//specify the user is elderly
if (selectedElderly.isChecked()) {
userInfo.put("isElderly", "1");
}
if (selectedGuardian.isChecked()) {
userInfo.put("isGuardian", "1");
}
df.set(userInfo);
if (selectedElderly.isChecked()) {
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
if (selectedGuardian.isChecked()) {
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, "Failed to Create Account", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
My database structure is:
database structure
As in the image, how to add one more field that contains auto-generated uid by the firebase?
If you want to add a generated id to the document, then you can do:
String id = fStore.collection("Users").document().getId();
This will generate a random id, then you can do:
DocumentReference df = fStore.collection("Users").document(user.getUid());
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("Username", username.getEditText().getText().toString());
userInfo.put("Email", email.getEditText().getText().toString());
userInfo.put("phoneNo", PhoneNo.getEditText().getText().toString());
userInfo.put("Password",password.getEditText().getText().toString());
userInfo.put("id",id);
df.set(userInfo);

query with the realtime firebase in android studio

first i'm sorry of my bad english , i have a problem with my code , when i want to query and check if the user that sign in is in the database or not , and also check of his password and if he tourist or tour guide and when i debug the program , the first statement is passed and the second which is check of the password , he never passed and start the next page , it say that the password is wrong , how i fix this problem pleass :(
TextView show7, signup_btn_label;
ImageButton imagebuttonn1;
EditText tourg_email_address, tourg_password;
Button btnn_login;
private FirebaseAuth mAuth1;
private DatabaseReference jLoginDatabase;
private FirebaseDatabase fDatabase;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logintourguide);
//initialise mProgressDialog
mProgressDialog = new ProgressDialog(Logintourguide.this);
show7 = (TextView) findViewById(R.id.forgot_password);
show7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Forgetpassword.class);
startActivity(i);
}
});
imagebuttonn1 = findViewById(R.id.imagebuttonn);
imagebuttonn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
signup_btn_label = (TextView) findViewById(R.id.signup_btn_label);
signup_btn_label.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), activity_signup_tourguide.class);
startActivity(i);
}
});
tourg_email_address = (EditText) findViewById(R.id.tourg_email_address);
tourg_password = (EditText) findViewById(R.id.tourg_password);
btnn_login = (Button) findViewById(R.id.btnn_login);
mAuth1 = FirebaseAuth.getInstance();
btnn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
final String email = tourg_email_address.getText().toString().trim();
final String pass = tourg_password.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(Logintourguide.this, "Please enter your email", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(pass)) {
Toast.makeText(Logintourguide.this, "Please enter your password", Toast.LENGTH_LONG).show();
return;
}
if (tourg_password.length() < 8) {
Toast.makeText(Logintourguide.this, "password must be 8 or long", Toast.LENGTH_LONG).show();
return;
}
if (!email.matches(emailPattern)) {
Toast.makeText(Logintourguide.this, "invalid email address", Toast.LENGTH_LONG).show();
return;
}
//show dialog
mProgressDialog.show();
//set content view
mProgressDialog.setContentView(R.layout.progress_dialog);
//set transparent background
mProgressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
///FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
// DatabaseReference rootRef = FirebaseDatabase.getInstance()
final DatabaseReference uidRef = FirebaseDatabase.getInstance().getReference("Users");
final Query checkUser = uidRef.orderByChild("email").equalTo(email);
checkUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (pass.equals(dataSnapshot.child("password").getValue())) {
if (dataSnapshot.child("sign up as").getValue().equals("Tour Guide")) {
String passwordfromDB = (String) dataSnapshot.child("password").getValue(String.class);
String emailfromDB = (String) dataSnapshot.child("email").getValue(String.class);
String fullNamefromDB = (String) dataSnapshot.child("fullName").getValue(String.class);
String phoneNumberfromDB = (String) dataSnapshot.child("phoneNumber").getValue(String.class);
//put it iin that intent so we can pass it to tourguide class
Intent intent = new Intent(getApplicationContext(), TourGuide_Profile.class);
intent.putExtra("full name", fullNamefromDB);
intent.putExtra("email", emailfromDB);
intent.putExtra("phone No", phoneNumberfromDB);
intent.putExtra("password", passwordfromDB);
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "welcome back tour guide!",
Toast.LENGTH_SHORT).show();
startActivity(intent);
} else {
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "Sorry ! You are not authorized to access this application!",
Toast.LENGTH_SHORT).show();
}
} else {
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "wrong password",
Toast.LENGTH_SHORT).show();
}
} else {
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "no such user exist !",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("Tag", databaseError.getMessage());
}
});
// uidRef.addListenerForSingleValueEvent(valueEventListener);
// checkUser.addListenerForSingleValueEvent(valueEventListener);
}
});
}

How to get data from text view in first activity and post it from another activity?

I want the data of textview in the second activity to pass in the third but i dont want to display it in the third activity. I want to directly send the data from the second activity to Pass in my sql db after clicking the button in the final activity. Is is achievable?
This is my first activity.
public class MainActivity extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private ProgressBar loading;
private static String URL_LOGIN ="http://192.168.1.83/Attendance/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading= findViewById(R.id.loading);
email = findViewById(R.id.editTextUserEmail);
password = findViewById(R.id.editTextPassword);
btn_login = findViewById(R.id.buttonRegister);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = email.getText().toString().trim();
String mPassword = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPassword.isEmpty()) {
Login(mEmail, mPassword);
}else{
email.setError("Please Enter Email");
password.setError("Please Enter Password");
}
}
});
}
private void Login(final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("JSON", jsonObject.toString());
String success = jsonObject.getString("success");
JSONArray jsonArray =
jsonObject.getJSONArray("login");
if (success.equals("1"))
{
for (int i = 0; i<jsonArray.length(); i++){
JSONObject object =
jsonArray.getJSONObject(i);
String name =
object.getString("name").trim();
String email =
object.getString("email").trim();
// Toast.makeText(MainActivity.this,
"Success Login \nYour name: "+name+"\nYour Email: "+email,
// Toast.LENGTH_LONG).show();
Intent intent = new
Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("name",name);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Error"
+e.toString(),
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error"
+error.toString(),
Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
This is my second activity
public class HomeActivity extends AppCompatActivity {
private TextView name,email;
private TextView welcome;
private Button Send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
Send = findViewById(R.id.btn_send);
welcome = findViewById(R.id.welcome);
final Intent intent = getIntent();
String extraName = intent.getStringExtra("name");
String extraEmail = intent.getStringExtra("email");
name.setText(extraName);
email.setText(extraEmail);
Send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(HomeActivity.this,StatusActivity.class);
intent1.putExtra("wel", welcome.getText().toString());
intent1.putExtra("name1", name.getText().toString());
intent1.putExtra("email1", email.getText().toString());
startActivity(intent1);
}
});
}
And this is my final activity but Here i dont want to show the text view i just want to post it from here.
public class StatusActivity extends AppCompatActivity {
private TextView welcome, name, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
welcome = findViewById(R.id.abcd);
name = findViewById(R.id.name1);
email = findViewById(R.id.email1);
final Intent intent = getIntent();
String extraName1 = intent.getStringExtra("name1");
String extraEmail1 = intent.getStringExtra("email1");
String extraWelcome = intent.getStringExtra("wel");
name.setText(extraName1);
email.setText(extraEmail1);
welcome.setText(extraWelcome);
}
Your question is pretty clear until you put MySql to the topic. Why you want to pass the data from one activity to another through the database. Why involve database operations which take time and resources.
You may pass data from one activity to another through Intents (primitive values, Strings and Parcelables)!
All you have to do is:
Get the data (int your case from TextView).
Create the Intent to navigate to the next Activity.
Put the data to the Intent.
Start the Activity.
Retrieve the data from the Intent.
For example if will navigate to the next Activity via button click then in that button's onClick():
// 1.
String data = myTextView.getText();
// 2.
Intent intent = new Intent(yourContext,YourNextActivity.class);
// 3.
intent.putStringExtra("MY DATA KEY",data);
// 4.
yourContext.startActivity(intent);
// 5. Now in YourNextActivity's onCreate();
String retrievedData = YourNextActivity.this.getIntent().getStringExtra("MY DATA KEY");
// Done!

Firebase user display name won't show on activity after creating new Firebase email password user account?

I make an sign up activity to create new user on Firebase using Simple Email Password shown below
CreateAccountActivity
public class CreateAccountActivity extends AppCompatActivity {
private ProgressDialog mprogress;
private RelativeLayout signUpactivity;
FirebaseUser user;
private Button msignUp;
public EditText mName,mEmail,mPassword,mCon_Password,mschl_name;
Spinner gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creat_acc);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
mAuth = FirebaseAuth.getInstance();
mprogress = new ProgressDialog(this);
msignUp = (Button) findViewById(R.id.signUp);
signUpactivity = (RelativeLayout) findViewById(R.id.activity_signUp);
mName = (EditText) findViewById(R.id.namefield);
mEmail = (EditText) findViewById(R.id.emailField);
mPassword = (EditText) findViewById(R.id.passwordField);
mschl_name = (EditText) findViewById(R.id.sname);
String[] option = new String[]{
"Male", "Female"
};
gender = (Spinner) findViewById(R.id.gender);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, option);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
gender.setAdapter(arrayAdapter);
msignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isNetworkAvailable()){
mprogress.setMessage("Creating Account...");
mprogress.show();
mprogress.setCanceledOnTouchOutside(false);
mprogress.setCancelable(false);
createAccount();
}else{
Snackbar.make(signUpactivity, "Network UnAvailable", Snackbar.LENGTH_SHORT).show();
}
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
View focusview = null;
boolean cancel = false;
private void createAccount(){
final String name = mName.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
final String gendertxt = gender.getSelectedItem().toString();
final String schl_name = mschl_name.getText().toString();
String edu_email = email+"#edutree.com";
if (isNetworkAvailable()){
mAuth.createUserWithEmailAndPassword(edu_email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if(task.isSuccessful()){
user = FirebaseAuth.getInstance().getCurrentUser();
String user_email = user.getEmail();
String gendertxt = gender.getSelectedItem().toString();
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder().setDisplayName(name).build();
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if(task.isSuccessful()){
Log.d("Profile", "User Profile Updated successfully");
FirebaseCrash.log("Profile Updated");
}else {
Log.d("Error","error while updating profile");
FirebaseCrash.log("Error while updating profile");
}
}
});
mprogress.dismiss();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CreateAccountActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Toast.makeText(CreateAccountActivity.this, "Welcome "+ FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_LONG).show();
}
},500);
}else{
Snackbar.make(signUpactivity, "Error occurred" , Snackbar.LENGTH_SHORT).show();
mprogress.dismiss();
}
}
});
}else {
Snackbar.make(signUpactivity, "Network UnAvailable", Snackbar.LENGTH_SHORT).show();
mprogress.dismiss();
}
}
}
When user enters the information it start method CreateAccount() and then when task is successful it updates user profile and set the display name and Starts the MainActivity. but it starts the MainActivty its not showing the user name.
MainActivity
Can Anyone help me to fix this problem, and when user get sign out and sign in again then it shows the name otherwise it didn't show after Sign up.
Any Answers were highly appreciated
You need to move the code that starts MainActivity to inside the onComplete() method for the profile change. Right now your code starts the Firebase user profile change to store the display name, but it shows MainActivity before that user profile change is completed.
You can update this piece of your code, look at what I added at the end of the onComplete() method:
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if(task.isSuccessful()){
Log.d("Profile", "User Profile Updated successfully");
FirebaseCrash.log("Profile Updated");
}else {
Log.d("Error","error while updating profile");
FirebaseCrash.log("Error while updating profile");
}
mprogress.dismiss();
Intent intent = new Intent(CreateAccountActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Toast.makeText(CreateAccountActivity.this, "Welcome "+ FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_LONG).show();
}
});
Then, you can remove this code later in the function:
mprogress.dismiss();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CreateAccountActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Toast.makeText(CreateAccountActivity.this, "Welcome "+ FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_LONG).show();
}
},500);

null return Intent on android programming

I write a simple program in android studio and create an object from Intent.
but i don't know why it return null ??
in the MainActivity.java I send userName and password to ProfileActivity.java.but Log.i shows null!
but Token is not null
com.example.sayres.myapplication2.ProfileActivity: onCreate User Name:
null Password: null Token: 22546874569
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String INTENT_USER_NAME_KYE = "user_name_key";
public static final String INTENT_USER_PASSWORD_KYE = "password_key";
protected final String TAG = "====>";
private EditText editTextUserName, editTextPassword;
private Button buttonLogin, buttonExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnLogin:
getUserInfo();
break;
case R.id.btnExit:
finish();
break;
}
}
private void initView() {
editTextUserName = (EditText) findViewById(R.id.editUserName);
editTextPassword = (EditText) findViewById(R.id.editPassword);
buttonExit = (Button) findViewById(R.id.btnExit);
buttonLogin = (Button) findViewById(R.id.btnLogin);
buttonLogin.setOnClickListener(this);
buttonExit.setOnClickListener(this);
}
private void getUserInfo() {
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
editTextUserName.setText("");
editTextPassword.setText("");
String msg = "";
if (userName.isEmpty() || password.isEmpty()) {
msg = "Insert UserName And Password !!!";
} else {
msg = "Welcome " + userName;
// TODO: 1/7/2017 go to ProfileActivity !!!
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra("INTENT_USER_NAME_KYE", userName);
intent.putExtra("INTENT_USER_PASSWORD_KYE", password);
Bundle bundle = new Bundle();
bundle.putString("user_token", "22546874569");
intent.putExtras(bundle);
startActivity(intent);
finish();
}
Log.i(TAG, "UserName= " + userName + "\t" + "Password= " + password);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
}
ProfileActivity.java:
public class ProfileActivity extends AppCompatActivity {
private static final String TAG = ProfileActivity.class.getName();
private TextView textViewUserName, textViewPassword, textViewAge, textViewSex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
// initviews();
Intent intent = getIntent();
String userName = intent.getStringExtra(MainActivity.INTENT_USER_NAME_KYE);
String password = intent.getStringExtra(MainActivity.INTENT_USER_PASSWORD_KYE);
// System.out.println("User Name iS:"+userName);
Bundle extras = intent.getExtras();
String user_token = extras.getString("user_token");
Log.i(TAG, "onCreate " + "User Name: " + userName + " Password: " + password + " Token: " + user_token);
}
intent.putExtra("INTENT_USER_NAME_KYE", userName);
intent.putExtra("INTENT_USER_PASSWORD_KYE", password);
You're using a literal "INTENT_USER_NAME_KYE" as the intent key, not the value of the INTENT_USER_NAME_KYE field you're using for reading the extras:
String userName = intent.getStringExtra(MainActivity.INTENT_USER_NAME_KYE);
String password = intent.getStringExtra(MainActivity.INTENT_USER_PASSWORD_KYE);
Remove the ".
Bundle bundle = new Bundle();
bundle.putString("user_token", "22546874569");
intent.putExtras(bundle);
above code removing intent values(extra values) which you set in intent so you should always choose either intent or bundle to pass your data to another activity.
try with below code it should work
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra("INTENT_USER_NAME_KYE", userName);
intent.putExtra("INTENT_USER_PASSWORD_KYE", password);
intent.putExtra("user_token", "22546874569");
startActivity(intent);

Categories