Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package app.connectplus.com.co;
- import android.app.ProgressDialog;
- import android.content.Intent;
- import android.graphics.Typeface;
- import android.net.Uri;
- import android.os.Bundle;
- import android.support.annotation.NonNull;
- import android.support.design.widget.Snackbar;
- import android.support.v7.app.AppCompatActivity;
- import android.text.TextUtils;
- import android.util.Log;
- import android.view.MotionEvent;
- import android.view.View;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ScrollView;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.bumptech.glide.Glide;
- import com.bumptech.glide.load.engine.DiskCacheStrategy;
- import com.google.android.gms.auth.api.Auth;
- import com.google.android.gms.auth.api.signin.GoogleSignIn;
- import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
- import com.google.android.gms.auth.api.signin.GoogleSignInClient;
- import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
- import com.google.android.gms.auth.api.signin.GoogleSignInResult;
- import com.google.android.gms.common.SignInButton;
- import com.google.android.gms.common.api.ApiException;
- import com.google.android.gms.tasks.OnCompleteListener;
- import com.google.android.gms.tasks.Task;
- import com.google.firebase.auth.AuthCredential;
- import com.google.firebase.auth.AuthResult;
- import com.google.firebase.auth.FirebaseAuth;
- import com.google.firebase.auth.FirebaseUser;
- import com.google.firebase.auth.GoogleAuthProvider;
- import com.google.firebase.database.DataSnapshot;
- import com.google.firebase.database.DatabaseError;
- import com.google.firebase.database.DatabaseReference;
- import com.google.firebase.database.FirebaseDatabase;
- import com.google.firebase.database.MutableData;
- import com.google.firebase.database.Transaction;
- import com.google.firebase.database.ValueEventListener;
- import java.util.HashMap;
- import java.util.Map;
- import app.connectplus.com.co.model.model.Community;
- import app.connectplus.com.co.model.model.CommunityMembers;
- import app.connectplus.com.co.model.model.User;
- public class Signup extends AppCompatActivity {
- public ProgressDialog dialog;
- public Boolean isDeepLinkThere = false;
- String output;
- String Communitykey;
- Uri deepLink = null;
- String communityId;
- ProgressDialog loginProgress;
- String username,email,password, communityKey;
- private EditText inputEmail, inputPassword, Name;
- private TextView btnSignIn;
- private Button btnSignUp;
- private FirebaseAuth auth;
- private DatabaseReference mDatabase;
- ScrollView scroll;
- private DatabaseReference nameCloudEndPoint;
- SignInButton button;
- FirebaseAuth mAuth;
- FirebaseAuth.AuthStateListener mAuthListener;
- private GoogleSignInClient mGoogleSignInClient;
- private static final String TAG = "GoogleActivity";
- private static final int RC_SIGN_IN = 9001;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_signup);
- //........................................
- mAuthListener = new FirebaseAuth.AuthStateListener() {
- @Override
- public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
- if(firebaseAuth.getCurrentUser()!=null)
- {
- startActivity(new Intent(Signup.this,WaitingLounge.class));
- }
- }
- };
- // button = (SignInButton) findViewById(R.id.googleBtn);
- // button.setOnClickListener(new View.OnClickListener() {
- // @Override
- // public void onClick(View view) {
- //
- // signIn();
- //
- //
- // }
- // });
- // Configure sign-in to request the user's ID, email address, and basic
- GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
- .requestIdToken(getString(R.string.default_web_client_id))
- .requestEmail()
- .build();
- mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
- mAuth = FirebaseAuth.getInstance();
- //............................................................
- dialog = new ProgressDialog(Signup.this);
- dialog.setMessage("Creating your account...");
- Communitykey = getIntent().getStringExtra("communitykey");
- if (!Communitykey.equals("0")){
- isDeepLinkThere = true;
- Toast.makeText(this,"2",Toast.LENGTH_LONG).show();
- }
- TextView myTextView = findViewById(R.id.headtitle);
- Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Righteous-Regular.ttf");
- myTextView.setTypeface(typeface);
- auth = FirebaseAuth.getInstance();
- mDatabase = FirebaseDatabase.getInstance().getReference();
- //login user if he has already logged in
- // loginProgress = ProgressDialog.show(this, null, "Please wait...", true);
- // loginProgress.setCancelable(false);
- // FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent())
- // .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
- // @Override
- // public void onSuccess(final PendingDynamicLinkData data) {
- // if (data == null) {
- // Log.d("DynamicLink", "getInvitation: no data");
- // if (auth.getCurrentUser() != null && SharedPreferencesUtils.getCommunityId(Signup.this) != null) {
- // loginProgress.dismiss();
- // startActivity(new Intent(Signup.this, Home.class));
- // finish();
- // }
- // else if (auth.getCurrentUser() != null && SharedPreferencesUtils.getCommunityId(Signup.this) == null) {
- // loginProgress.dismiss();
- // startActivity(new Intent(Signup.this, WaitingLounge.class));
- // finish();
- // }
- // else {
- // loginProgress.dismiss();
- // }
- // return;
- // }
- //
- // // Get the deep link
- // deepLink = data.getLink();
- //
- // communityKey = deepLink.getLastPathSegment();
- // communityId = SharedPreferencesUtils.getCommunityId(Signup.this);
- //
- // if (auth.getCurrentUser() != null && (communityId == null || !communityId.equals(communityKey))) {
- // DatabaseReference communityReference = FirebaseDatabase.getInstance().getReference().child("communities").child(communityKey);
- // communityReference.addListenerForSingleValueEvent(new ValueEventListener() {
- // @Override
- // public void onDataChange(DataSnapshot dataSnapshot) {
- // Community community = dataSnapshot.getValue(Community.class);
- // SharedPreferencesUtils.setCommunityData(Signup.this, communityKey, community.getName(), community.getAdmin(), community.getUrl());
- //
- // addCommunityToUser(communityKey, community.getName());
- // updateCommunityMembers(communityKey);
- //
- // loginProgress.dismiss();
- // startActivity(new Intent(Signup.this, Home.class));
- // finish();
- // }
- //
- // @Override
- // public void onCancelled(DatabaseError databaseError) {
- //
- // }
- // });
- // }
- // else if (auth.getCurrentUser() == null) {
- // loginProgress.dismiss();
- // }
- // else if (communityId.equals(communityKey)) {
- // loginProgress.dismiss();
- // startActivity(new Intent(Signup.this, Home.class));
- // finish();
- // }
- // }
- // })
- // .addOnFailureListener(this, new OnFailureListener() {
- // @Override
- // public void onFailure(@NonNull Exception e) {
- // Log.w("DynamicLink", "getDynamicLink:onFailure", e);
- // }
- // });
- //
- btnSignIn = findViewById(R.id.sign_in_button);
- btnSignUp = findViewById(R.id.sign_up_button);
- inputEmail = findViewById(R.id.email);
- inputPassword = findViewById(R.id.password);
- Name = findViewById(R.id.name);
- scroll = findViewById(R.id.scrollview);
- Name.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View view, MotionEvent motionEvent) {
- scroll.postDelayed(new Runnable() {
- @Override
- public void run() {
- View lastChild = scroll.getChildAt(scroll.getChildCount() - 1);
- int bottom = lastChild.getBottom() + scroll.getPaddingBottom();
- int sy = scroll.getScrollY();
- int sh = scroll.getHeight();
- int delta = bottom - (sy + sh);
- scroll.smoothScrollBy(0, delta);
- }
- }, 200);
- return false;
- }
- });
- Name.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- scroll.postDelayed(new Runnable() {
- @Override
- public void run() {
- View lastChild = scroll.getChildAt(scroll.getChildCount() - 1);
- int bottom = lastChild.getBottom() + scroll.getPaddingBottom();
- int sy = scroll.getScrollY();
- int sh = scroll.getHeight();
- int delta = bottom - (sy + sh);
- scroll.smoothScrollBy(0, delta);
- }
- }, 200);
- }
- });
- inputEmail.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View view, MotionEvent motionEvent) {
- scroll.postDelayed(new Runnable() {
- @Override
- public void run() {
- View lastChild = scroll.getChildAt(scroll.getChildCount() - 1);
- int bottom = lastChild.getBottom() + scroll.getPaddingBottom();
- int sy = scroll.getScrollY();
- int sh = scroll.getHeight();
- int delta = bottom - (sy + sh);
- scroll.smoothScrollBy(0, delta);
- }
- }, 200);
- return false;
- }
- });
- inputEmail.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- scroll.postDelayed(new Runnable() {
- @Override
- public void run() {
- View lastChild = scroll.getChildAt(scroll.getChildCount() - 1);
- int bottom = lastChild.getBottom() + scroll.getPaddingBottom();
- int sy = scroll.getScrollY();
- int sh = scroll.getHeight();
- int delta = bottom - (sy + sh);
- scroll.smoothScrollBy(0, delta);
- }
- }, 200);
- }
- });
- btnSignUp.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- dialog.show();
- email = inputEmail.getText().toString().trim();
- password = inputPassword.getText().toString().trim();
- username = Name.getText().toString().trim();
- if (TextUtils.isEmpty(username)) {
- Toast.makeText(getApplicationContext(), "Enter your Username!", Toast.LENGTH_SHORT).show();
- dialog.dismiss();
- return;
- }
- if (TextUtils.isEmpty(email)) {
- dialog.dismiss();
- Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
- return;
- }
- if (TextUtils.isEmpty(password)) {
- dialog.dismiss();
- Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
- return;
- }
- if (password.length() < 6) {
- dialog.dismiss();
- Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
- return;
- }
- //create user tv.setText(text); // tv is null
- loginProgress = ProgressDialog.show(Signup.this, null, "Please wait...", true);
- loginProgress.setCancelable(false);
- auth.createUserWithEmailAndPassword(email, password)
- .addOnCompleteListener(Signup.this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull Task<AuthResult> task) {
- if (!task.isSuccessful()) {
- dialog.dismiss();
- Toast.makeText(Signup.this, "Authentication failed. Try again after some time", Toast.LENGTH_SHORT).show();
- } else {
- auth.signInWithEmailAndPassword(email, password)
- .addOnCompleteListener(Signup.this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull Task<AuthResult> task) {
- DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("user_details");
- mDatabase.child(auth.getUid());
- User user = new User(username, email,"0",1, null,null);
- mDatabase.child(auth.getUid()).setValue(user);
- if (isDeepLinkThere)
- {
- DatabaseReference communityReference = FirebaseDatabase.getInstance().getReference().child("communities").child(Communitykey);
- communityReference.addListenerForSingleValueEvent(new ValueEventListener() {
- @Override
- public void onDataChange(DataSnapshot dataSnapshot) {
- Community community = dataSnapshot.getValue(Community.class);
- SharedPreferencesUtils.setCommunityData(Signup.this, Communitykey, community.getName(), community.getAdmin(), community.getUrl());
- addCommunityToUser(Communitykey, community.getName());
- updateCommunityMembers(Communitykey);
- dialog.dismiss();
- startActivity(new Intent(Signup.this, Home.class));
- finish();
- }
- @Override
- public void onCancelled(DatabaseError databaseError) {
- dialog.dismiss();
- }
- });
- }
- else
- {
- dialog.dismiss();
- startActivity(new Intent(Signup.this, WaitingLounge.class));
- finish();
- }
- }
- });
- }
- }
- });
- }
- });
- }
- @Override
- public void onStart() {
- super.onStart();
- // Check if user is signed in (non-null) and update UI accordingly.
- FirebaseUser currentUser = mAuth.getCurrentUser();
- mAuth.addAuthStateListener(mAuthListener);
- // updateUI(currentUser);
- }
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
- if (requestCode == RC_SIGN_IN) {
- GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
- handleSignInResult(result);
- Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
- try {
- // Google Sign In was successful, authenticate with Firebase
- GoogleSignInAccount account = task.getResult(ApiException.class);
- firebaseAuthWithGoogle(account);
- } catch (ApiException e) {
- // Google Sign In failed, update UI appropriately
- Log.w(TAG, "Google sign in failed", e);
- // [START_EXCLUDE]
- // updateUI(null);
- // [END_EXCLUDE]
- }
- }
- }
- private void handleSignInResult(GoogleSignInResult result) {
- Log.d(TAG, "handleSignInResult:" + result.isSuccess());
- if (result.isSuccess()) {
- // Signed in successfully, show authenticated UI.
- GoogleSignInAccount acct = result.getSignInAccount();
- Log.e(TAG, "display name: " + acct.getDisplayName());
- String personName = acct.getDisplayName();
- String personPhotoUrl = acct.getPhotoUrl().toString();
- String email = acct.getEmail();
- String uid = acct.getId();
- Log.e(TAG, "Name: " + personName + ", email: " + email
- + ", Image: " + personPhotoUrl);
- } else {
- // Signed out, show unauthenticated UI.
- Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
- }
- }
- private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
- Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
- // [START_EXCLUDE silent]
- showDialog(0);
- // [END_EXCLUDE]
- AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
- mAuth.signInWithCredential(credential)
- .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull Task<AuthResult> task) {
- if (task.isSuccessful()) {
- // Sign in success, update UI with the signed-in user's information
- Log.d(TAG, "signInWithCredential:success");
- FirebaseUser user = mAuth.getCurrentUser();
- // updateUI(user);
- } else {
- // If sign in fails, display a message to the user.
- Log.w(TAG, "signInWithCredential:failure", task.getException());
- Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
- // updateUI(null);
- }
- // [START_EXCLUDE]
- removeDialog(0);
- // [END_EXCLUDE]
- }
- });
- }
- private void signIn() {
- Intent signInIntent = mGoogleSignInClient.getSignInIntent();
- startActivityForResult(signInIntent, RC_SIGN_IN);
- }
- // private void signOut() {
- // // Firebase sign out
- // mAuth.signOut();
- //
- // // Google sign out
- // mGoogleSignInClient.signOut().addOnCompleteListener(this,
- // new OnCompleteListener<Void>() {
- // @Override
- // public void onComplete(@NonNull Task<Void> task) {
- // updateUI(null);
- // }
- // });
- // }
- private void updateUI(FirebaseUser user) {
- removeDialog(0);
- if (user != null) {
- findViewById(R.id.sign_in_button).setVisibility(View.GONE);
- } else {
- findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
- }
- }
- public void signin(View view) {
- Intent i = new Intent(Signup.this, Login.class);
- startActivity(i);
- finish();
- }
- private void addCommunityToUser (String Communitykey, String communityName) {
- DatabaseReference userReference = FirebaseDatabase.getInstance().getReference().child("user_details").child(auth.getUid()).child("communities");
- Map<String, Object> communityList = new HashMap<>();
- communityList.put(Communitykey, communityName);
- userReference.updateChildren(communityList);
- }
- private void updateCommunityMembers (String Communitykey) {
- final DatabaseReference membersReference = FirebaseDatabase.getInstance().getReference().child("communityMembers").child(Communitykey);
- membersReference.addListenerForSingleValueEvent(new ValueEventListener() {
- @Override
- public void onDataChange(DataSnapshot dataSnapshot) {
- CommunityMembers members = dataSnapshot.getValue(CommunityMembers.class);
- if (members.getMemberList() != null) {
- Map<String, Boolean> memberList = members.getMemberList();
- if (!memberList.containsKey(auth.getUid())) {
- membersReference.child("totalMembers").runTransaction(new Transaction.Handler() {
- @Override
- public Transaction.Result doTransaction(MutableData mutableData) {
- Integer currentValue = mutableData.getValue(Integer.class);
- if (currentValue == null) {
- mutableData.setValue(1);
- }
- else {
- mutableData.setValue(currentValue + 1);
- }
- return Transaction.success(mutableData);
- }
- @Override
- public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
- Map<String, Object> memberList = new HashMap<>();
- memberList.put(auth.getUid(), Boolean.TRUE);
- membersReference.child("memberList").updateChildren(memberList);
- }
- });
- }
- }
- else {
- membersReference.child("totalMembers").runTransaction(new Transaction.Handler() {
- @Override
- public Transaction.Result doTransaction(MutableData mutableData) {
- Integer currentValue = mutableData.getValue(Integer.class);
- if (currentValue == null || currentValue == 0) {
- mutableData.setValue(1);
- }
- else {
- mutableData.setValue(currentValue + 1);
- }
- return Transaction.success(mutableData);
- }
- @Override
- public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
- Map<String, Object> memberList = new HashMap<>();
- memberList.put(auth.getUid(), Boolean.TRUE);
- membersReference.child("memberList").updateChildren(memberList);
- }
- });
- }
- }
- @Override
- public void onCancelled(DatabaseError databaseError) {
- }
- });
- }
- }
Add Comment
Please, Sign In to add comment