Guest User

Untitled

a guest
May 19th, 2018
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 25.54 KB | None | 0 0
  1. package app.connectplus.com.co;
  2.  
  3. import android.app.ProgressDialog;
  4. import android.content.Intent;
  5. import android.graphics.Typeface;
  6. import android.net.Uri;
  7. import android.os.Bundle;
  8. import android.support.annotation.NonNull;
  9. import android.support.design.widget.Snackbar;
  10. import android.support.v7.app.AppCompatActivity;
  11. import android.text.TextUtils;
  12. import android.util.Log;
  13. import android.view.MotionEvent;
  14. import android.view.View;
  15. import android.widget.Button;
  16. import android.widget.EditText;
  17. import android.widget.ScrollView;
  18. import android.widget.TextView;
  19. import android.widget.Toast;
  20.  
  21. import com.bumptech.glide.Glide;
  22. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  23. import com.google.android.gms.auth.api.Auth;
  24. import com.google.android.gms.auth.api.signin.GoogleSignIn;
  25. import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
  26. import com.google.android.gms.auth.api.signin.GoogleSignInClient;
  27. import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
  28. import com.google.android.gms.auth.api.signin.GoogleSignInResult;
  29. import com.google.android.gms.common.SignInButton;
  30.  
  31. import com.google.android.gms.common.api.ApiException;
  32. import com.google.android.gms.tasks.OnCompleteListener;
  33. import com.google.android.gms.tasks.Task;
  34. import com.google.firebase.auth.AuthCredential;
  35. import com.google.firebase.auth.AuthResult;
  36. import com.google.firebase.auth.FirebaseAuth;
  37. import com.google.firebase.auth.FirebaseUser;
  38. import com.google.firebase.auth.GoogleAuthProvider;
  39. import com.google.firebase.database.DataSnapshot;
  40. import com.google.firebase.database.DatabaseError;
  41. import com.google.firebase.database.DatabaseReference;
  42. import com.google.firebase.database.FirebaseDatabase;
  43. import com.google.firebase.database.MutableData;
  44. import com.google.firebase.database.Transaction;
  45. import com.google.firebase.database.ValueEventListener;
  46.  
  47. import java.util.HashMap;
  48. import java.util.Map;
  49.  
  50. import app.connectplus.com.co.model.model.Community;
  51. import app.connectplus.com.co.model.model.CommunityMembers;
  52. import app.connectplus.com.co.model.model.User;
  53.  
  54. public class Signup extends AppCompatActivity {
  55. public ProgressDialog dialog;
  56. public Boolean isDeepLinkThere = false;
  57. String output;
  58. String Communitykey;
  59. Uri deepLink = null;
  60. String communityId;
  61. ProgressDialog loginProgress;
  62. String username,email,password, communityKey;
  63. private EditText inputEmail, inputPassword, Name;
  64. private TextView btnSignIn;
  65. private Button btnSignUp;
  66. private FirebaseAuth auth;
  67. private DatabaseReference mDatabase;
  68. ScrollView scroll;
  69. private DatabaseReference nameCloudEndPoint;
  70. SignInButton button;
  71. FirebaseAuth mAuth;
  72. FirebaseAuth.AuthStateListener mAuthListener;
  73.  
  74.  
  75. private GoogleSignInClient mGoogleSignInClient;
  76. private static final String TAG = "GoogleActivity";
  77. private static final int RC_SIGN_IN = 9001;
  78.  
  79. @Override
  80. protected void onCreate(Bundle savedInstanceState) {
  81. super.onCreate(savedInstanceState);
  82. setContentView(R.layout.activity_signup);
  83.  
  84. //........................................
  85.  
  86.  
  87. mAuthListener = new FirebaseAuth.AuthStateListener() {
  88. @Override
  89. public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
  90. if(firebaseAuth.getCurrentUser()!=null)
  91. {
  92. startActivity(new Intent(Signup.this,WaitingLounge.class));
  93.  
  94. }
  95. }
  96. };
  97.  
  98. // button = (SignInButton) findViewById(R.id.googleBtn);
  99. // button.setOnClickListener(new View.OnClickListener() {
  100. // @Override
  101. // public void onClick(View view) {
  102. //
  103. // signIn();
  104. //
  105. //
  106. // }
  107. // });
  108. // Configure sign-in to request the user's ID, email address, and basic
  109.  
  110. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  111. .requestIdToken(getString(R.string.default_web_client_id))
  112. .requestEmail()
  113. .build();
  114.  
  115. mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
  116.  
  117. mAuth = FirebaseAuth.getInstance();
  118.  
  119. //............................................................
  120. dialog = new ProgressDialog(Signup.this);
  121. dialog.setMessage("Creating your account...");
  122. Communitykey = getIntent().getStringExtra("communitykey");
  123.  
  124. if (!Communitykey.equals("0")){
  125. isDeepLinkThere = true;
  126. Toast.makeText(this,"2",Toast.LENGTH_LONG).show();
  127. }
  128.  
  129. TextView myTextView = findViewById(R.id.headtitle);
  130. Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Righteous-Regular.ttf");
  131. myTextView.setTypeface(typeface);
  132. auth = FirebaseAuth.getInstance();
  133. mDatabase = FirebaseDatabase.getInstance().getReference();
  134. //login user if he has already logged in
  135. // loginProgress = ProgressDialog.show(this, null, "Please wait...", true);
  136. // loginProgress.setCancelable(false);
  137. // FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent())
  138. // .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
  139. // @Override
  140. // public void onSuccess(final PendingDynamicLinkData data) {
  141. // if (data == null) {
  142. // Log.d("DynamicLink", "getInvitation: no data");
  143. // if (auth.getCurrentUser() != null && SharedPreferencesUtils.getCommunityId(Signup.this) != null) {
  144. // loginProgress.dismiss();
  145. // startActivity(new Intent(Signup.this, Home.class));
  146. // finish();
  147. // }
  148. // else if (auth.getCurrentUser() != null && SharedPreferencesUtils.getCommunityId(Signup.this) == null) {
  149. // loginProgress.dismiss();
  150. // startActivity(new Intent(Signup.this, WaitingLounge.class));
  151. // finish();
  152. // }
  153. // else {
  154. // loginProgress.dismiss();
  155. // }
  156. // return;
  157. // }
  158. //
  159. // // Get the deep link
  160. // deepLink = data.getLink();
  161. //
  162. // communityKey = deepLink.getLastPathSegment();
  163. // communityId = SharedPreferencesUtils.getCommunityId(Signup.this);
  164. //
  165. // if (auth.getCurrentUser() != null && (communityId == null || !communityId.equals(communityKey))) {
  166. // DatabaseReference communityReference = FirebaseDatabase.getInstance().getReference().child("communities").child(communityKey);
  167. // communityReference.addListenerForSingleValueEvent(new ValueEventListener() {
  168. // @Override
  169. // public void onDataChange(DataSnapshot dataSnapshot) {
  170. // Community community = dataSnapshot.getValue(Community.class);
  171. // SharedPreferencesUtils.setCommunityData(Signup.this, communityKey, community.getName(), community.getAdmin(), community.getUrl());
  172. //
  173. // addCommunityToUser(communityKey, community.getName());
  174. // updateCommunityMembers(communityKey);
  175. //
  176. // loginProgress.dismiss();
  177. // startActivity(new Intent(Signup.this, Home.class));
  178. // finish();
  179. // }
  180. //
  181. // @Override
  182. // public void onCancelled(DatabaseError databaseError) {
  183. //
  184. // }
  185. // });
  186. // }
  187. // else if (auth.getCurrentUser() == null) {
  188. // loginProgress.dismiss();
  189. // }
  190. // else if (communityId.equals(communityKey)) {
  191. // loginProgress.dismiss();
  192. // startActivity(new Intent(Signup.this, Home.class));
  193. // finish();
  194. // }
  195. // }
  196. // })
  197. // .addOnFailureListener(this, new OnFailureListener() {
  198. // @Override
  199. // public void onFailure(@NonNull Exception e) {
  200. // Log.w("DynamicLink", "getDynamicLink:onFailure", e);
  201. // }
  202. // });
  203. //
  204. btnSignIn = findViewById(R.id.sign_in_button);
  205. btnSignUp = findViewById(R.id.sign_up_button);
  206. inputEmail = findViewById(R.id.email);
  207. inputPassword = findViewById(R.id.password);
  208. Name = findViewById(R.id.name);
  209. scroll = findViewById(R.id.scrollview);
  210. Name.setOnTouchListener(new View.OnTouchListener() {
  211. @Override
  212. public boolean onTouch(View view, MotionEvent motionEvent) {
  213. scroll.postDelayed(new Runnable() {
  214. @Override
  215. public void run() {
  216. View lastChild = scroll.getChildAt(scroll.getChildCount() - 1);
  217. int bottom = lastChild.getBottom() + scroll.getPaddingBottom();
  218. int sy = scroll.getScrollY();
  219. int sh = scroll.getHeight();
  220. int delta = bottom - (sy + sh);
  221. scroll.smoothScrollBy(0, delta);
  222. }
  223. }, 200);
  224.  
  225. return false;
  226. }
  227. });
  228. Name.setOnClickListener(new View.OnClickListener() {
  229. @Override
  230. public void onClick(View view) {
  231. scroll.postDelayed(new Runnable() {
  232. @Override
  233. public void run() {
  234. View lastChild = scroll.getChildAt(scroll.getChildCount() - 1);
  235. int bottom = lastChild.getBottom() + scroll.getPaddingBottom();
  236. int sy = scroll.getScrollY();
  237. int sh = scroll.getHeight();
  238. int delta = bottom - (sy + sh);
  239. scroll.smoothScrollBy(0, delta);
  240. }
  241. }, 200);
  242.  
  243. }
  244. });
  245.  
  246. inputEmail.setOnTouchListener(new View.OnTouchListener() {
  247. @Override
  248. public boolean onTouch(View view, MotionEvent motionEvent) {
  249. scroll.postDelayed(new Runnable() {
  250. @Override
  251. public void run() {
  252. View lastChild = scroll.getChildAt(scroll.getChildCount() - 1);
  253. int bottom = lastChild.getBottom() + scroll.getPaddingBottom();
  254. int sy = scroll.getScrollY();
  255. int sh = scroll.getHeight();
  256. int delta = bottom - (sy + sh);
  257. scroll.smoothScrollBy(0, delta);
  258. }
  259. }, 200);
  260.  
  261. return false;
  262. }
  263. });
  264. inputEmail.setOnClickListener(new View.OnClickListener() {
  265. @Override
  266. public void onClick(View view) {
  267. scroll.postDelayed(new Runnable() {
  268. @Override
  269. public void run() {
  270. View lastChild = scroll.getChildAt(scroll.getChildCount() - 1);
  271. int bottom = lastChild.getBottom() + scroll.getPaddingBottom();
  272. int sy = scroll.getScrollY();
  273. int sh = scroll.getHeight();
  274. int delta = bottom - (sy + sh);
  275. scroll.smoothScrollBy(0, delta);
  276. }
  277. }, 200);
  278.  
  279. }
  280. });
  281.  
  282. btnSignUp.setOnClickListener(new View.OnClickListener() {
  283. @Override
  284. public void onClick(View v) {
  285. dialog.show();
  286. email = inputEmail.getText().toString().trim();
  287. password = inputPassword.getText().toString().trim();
  288. username = Name.getText().toString().trim();
  289.  
  290. if (TextUtils.isEmpty(username)) {
  291. Toast.makeText(getApplicationContext(), "Enter your Username!", Toast.LENGTH_SHORT).show();
  292. dialog.dismiss();
  293. return;
  294. }
  295.  
  296. if (TextUtils.isEmpty(email)) {
  297. dialog.dismiss();
  298. Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
  299. return;
  300. }
  301.  
  302. if (TextUtils.isEmpty(password)) {
  303. dialog.dismiss();
  304. Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
  305. return;
  306. }
  307.  
  308. if (password.length() < 6) {
  309. dialog.dismiss();
  310. Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
  311. return;
  312. }
  313.  
  314. //create user tv.setText(text); // tv is null
  315.  
  316. loginProgress = ProgressDialog.show(Signup.this, null, "Please wait...", true);
  317. loginProgress.setCancelable(false);
  318.  
  319.  
  320. auth.createUserWithEmailAndPassword(email, password)
  321. .addOnCompleteListener(Signup.this, new OnCompleteListener<AuthResult>() {
  322.  
  323.  
  324. @Override
  325. public void onComplete(@NonNull Task<AuthResult> task) {
  326.  
  327. if (!task.isSuccessful()) {
  328. dialog.dismiss();
  329. Toast.makeText(Signup.this, "Authentication failed. Try again after some time", Toast.LENGTH_SHORT).show();
  330.  
  331. } else {
  332.  
  333. auth.signInWithEmailAndPassword(email, password)
  334. .addOnCompleteListener(Signup.this, new OnCompleteListener<AuthResult>() {
  335. @Override
  336. public void onComplete(@NonNull Task<AuthResult> task) {
  337. DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("user_details");
  338. mDatabase.child(auth.getUid());
  339.  
  340. User user = new User(username, email,"0",1, null,null);
  341. mDatabase.child(auth.getUid()).setValue(user);
  342.  
  343. if (isDeepLinkThere)
  344. {
  345. DatabaseReference communityReference = FirebaseDatabase.getInstance().getReference().child("communities").child(Communitykey);
  346. communityReference.addListenerForSingleValueEvent(new ValueEventListener() {
  347. @Override
  348. public void onDataChange(DataSnapshot dataSnapshot) {
  349. Community community = dataSnapshot.getValue(Community.class);
  350. SharedPreferencesUtils.setCommunityData(Signup.this, Communitykey, community.getName(), community.getAdmin(), community.getUrl());
  351.  
  352. addCommunityToUser(Communitykey, community.getName());
  353. updateCommunityMembers(Communitykey);
  354. dialog.dismiss();
  355.  
  356. startActivity(new Intent(Signup.this, Home.class));
  357. finish();
  358. }
  359.  
  360. @Override
  361. public void onCancelled(DatabaseError databaseError) {
  362. dialog.dismiss();
  363. }
  364. });
  365. }
  366. else
  367. {
  368. dialog.dismiss();
  369. startActivity(new Intent(Signup.this, WaitingLounge.class));
  370. finish();
  371. }
  372. }
  373. });
  374.  
  375.  
  376. }
  377. }
  378. });
  379.  
  380. }
  381. });
  382. }
  383.  
  384.  
  385. @Override
  386. public void onStart() {
  387. super.onStart();
  388. // Check if user is signed in (non-null) and update UI accordingly.
  389. FirebaseUser currentUser = mAuth.getCurrentUser();
  390. mAuth.addAuthStateListener(mAuthListener);
  391. // updateUI(currentUser);
  392. }
  393.  
  394. @Override
  395. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  396. super.onActivityResult(requestCode, resultCode, data);
  397.  
  398. // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
  399. if (requestCode == RC_SIGN_IN) {
  400.  
  401. GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
  402. handleSignInResult(result);
  403. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
  404. try {
  405. // Google Sign In was successful, authenticate with Firebase
  406. GoogleSignInAccount account = task.getResult(ApiException.class);
  407. firebaseAuthWithGoogle(account);
  408. } catch (ApiException e) {
  409. // Google Sign In failed, update UI appropriately
  410. Log.w(TAG, "Google sign in failed", e);
  411. // [START_EXCLUDE]
  412. // updateUI(null);
  413. // [END_EXCLUDE]
  414. }
  415. }
  416. }
  417. private void handleSignInResult(GoogleSignInResult result) {
  418. Log.d(TAG, "handleSignInResult:" + result.isSuccess());
  419. if (result.isSuccess()) {
  420. // Signed in successfully, show authenticated UI.
  421. GoogleSignInAccount acct = result.getSignInAccount();
  422.  
  423. Log.e(TAG, "display name: " + acct.getDisplayName());
  424.  
  425. String personName = acct.getDisplayName();
  426. String personPhotoUrl = acct.getPhotoUrl().toString();
  427. String email = acct.getEmail();
  428. String uid = acct.getId();
  429.  
  430.  
  431. Log.e(TAG, "Name: " + personName + ", email: " + email
  432. + ", Image: " + personPhotoUrl);
  433.  
  434.  
  435. } else {
  436. // Signed out, show unauthenticated UI.
  437. Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_SHORT).show();
  438. }
  439. }
  440. private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
  441. Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
  442. // [START_EXCLUDE silent]
  443. showDialog(0);
  444. // [END_EXCLUDE]
  445.  
  446. AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
  447. mAuth.signInWithCredential(credential)
  448. .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
  449. @Override
  450. public void onComplete(@NonNull Task<AuthResult> task) {
  451. if (task.isSuccessful()) {
  452. // Sign in success, update UI with the signed-in user's information
  453. Log.d(TAG, "signInWithCredential:success");
  454. FirebaseUser user = mAuth.getCurrentUser();
  455. // updateUI(user);
  456. } else {
  457. // If sign in fails, display a message to the user.
  458. Log.w(TAG, "signInWithCredential:failure", task.getException());
  459. Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
  460. // updateUI(null);
  461. }
  462.  
  463. // [START_EXCLUDE]
  464. removeDialog(0);
  465. // [END_EXCLUDE]
  466. }
  467. });
  468. }
  469.  
  470. private void signIn() {
  471. Intent signInIntent = mGoogleSignInClient.getSignInIntent();
  472. startActivityForResult(signInIntent, RC_SIGN_IN);
  473. }
  474.  
  475. // private void signOut() {
  476. // // Firebase sign out
  477. // mAuth.signOut();
  478. //
  479. // // Google sign out
  480. // mGoogleSignInClient.signOut().addOnCompleteListener(this,
  481. // new OnCompleteListener<Void>() {
  482. // @Override
  483. // public void onComplete(@NonNull Task<Void> task) {
  484. // updateUI(null);
  485. // }
  486. // });
  487. // }
  488.  
  489.  
  490.  
  491.  
  492.  
  493. private void updateUI(FirebaseUser user) {
  494. removeDialog(0);
  495. if (user != null) {
  496.  
  497. findViewById(R.id.sign_in_button).setVisibility(View.GONE);
  498.  
  499. } else {
  500.  
  501. findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
  502. }
  503. }
  504.  
  505.  
  506. public void signin(View view) {
  507.  
  508. Intent i = new Intent(Signup.this, Login.class);
  509. startActivity(i);
  510. finish();
  511.  
  512. }
  513.  
  514. private void addCommunityToUser (String Communitykey, String communityName) {
  515. DatabaseReference userReference = FirebaseDatabase.getInstance().getReference().child("user_details").child(auth.getUid()).child("communities");
  516. Map<String, Object> communityList = new HashMap<>();
  517. communityList.put(Communitykey, communityName);
  518. userReference.updateChildren(communityList);
  519. }
  520.  
  521. private void updateCommunityMembers (String Communitykey) {
  522. final DatabaseReference membersReference = FirebaseDatabase.getInstance().getReference().child("communityMembers").child(Communitykey);
  523. membersReference.addListenerForSingleValueEvent(new ValueEventListener() {
  524. @Override
  525. public void onDataChange(DataSnapshot dataSnapshot) {
  526. CommunityMembers members = dataSnapshot.getValue(CommunityMembers.class);
  527. if (members.getMemberList() != null) {
  528. Map<String, Boolean> memberList = members.getMemberList();
  529. if (!memberList.containsKey(auth.getUid())) {
  530. membersReference.child("totalMembers").runTransaction(new Transaction.Handler() {
  531. @Override
  532. public Transaction.Result doTransaction(MutableData mutableData) {
  533. Integer currentValue = mutableData.getValue(Integer.class);
  534. if (currentValue == null) {
  535. mutableData.setValue(1);
  536. }
  537. else {
  538. mutableData.setValue(currentValue + 1);
  539. }
  540. return Transaction.success(mutableData);
  541. }
  542.  
  543. @Override
  544. public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
  545. Map<String, Object> memberList = new HashMap<>();
  546. memberList.put(auth.getUid(), Boolean.TRUE);
  547. membersReference.child("memberList").updateChildren(memberList);
  548. }
  549. });
  550. }
  551.  
  552. }
  553. else {
  554. membersReference.child("totalMembers").runTransaction(new Transaction.Handler() {
  555. @Override
  556. public Transaction.Result doTransaction(MutableData mutableData) {
  557. Integer currentValue = mutableData.getValue(Integer.class);
  558. if (currentValue == null || currentValue == 0) {
  559. mutableData.setValue(1);
  560. }
  561. else {
  562. mutableData.setValue(currentValue + 1);
  563. }
  564. return Transaction.success(mutableData);
  565. }
  566.  
  567. @Override
  568. public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
  569. Map<String, Object> memberList = new HashMap<>();
  570. memberList.put(auth.getUid(), Boolean.TRUE);
  571. membersReference.child("memberList").updateChildren(memberList);
  572. }
  573. });
  574. }
  575. }
  576.  
  577. @Override
  578. public void onCancelled(DatabaseError databaseError) {
  579.  
  580. }
  581. });
  582. }
  583. }
Add Comment
Please, Sign In to add comment