Advertisement
Guest User

Fragme

a guest
Sep 29th, 2017
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.68 KB | None | 0 0
  1. package com.example.hp.heartful;
  2.  
  3. import android.app.ProgressDialog;
  4. import android.content.Intent;
  5. import android.net.Uri;
  6. import android.os.Build;
  7. import android.os.Bundle;
  8. import android.support.annotation.NonNull;
  9. import android.support.annotation.RequiresApi;
  10. import android.support.v4.app.Fragment;
  11. import android.support.v4.app.FragmentManager;
  12. import android.text.TextUtils;
  13. import android.util.Log;
  14. import android.view.LayoutInflater;
  15. import android.view.View;
  16. import android.view.ViewGroup;
  17. import android.widget.Button;
  18. import android.widget.EditText;
  19. import android.widget.ImageView;
  20. import android.widget.TextView;
  21. import android.widget.Toast;
  22.  
  23. import com.bumptech.glide.Glide;
  24. import com.bumptech.glide.load.engine.DiskCacheStrategy;
  25. import com.facebook.AccessToken;
  26. import com.facebook.CallbackManager;
  27. import com.facebook.FacebookCallback;
  28. import com.facebook.FacebookException;
  29. import com.facebook.FacebookSdk;
  30. import com.facebook.appevents.AppEventsLogger;
  31. import com.facebook.login.LoginManager;
  32. import com.facebook.login.LoginResult;
  33. import com.facebook.login.widget.LoginButton;
  34. import com.google.android.gms.auth.api.Auth;
  35. import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
  36. import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
  37. import com.google.android.gms.auth.api.signin.GoogleSignInResult;
  38. import com.google.android.gms.common.ConnectionResult;
  39. import com.google.android.gms.common.SignInButton;
  40. import com.google.android.gms.common.api.GoogleApiClient;
  41. import com.google.android.gms.tasks.OnCompleteListener;
  42. import com.google.android.gms.tasks.Task;
  43. import com.google.firebase.auth.AuthCredential;
  44. import com.google.firebase.auth.AuthResult;
  45. import com.google.firebase.auth.FacebookAuthProvider;
  46. import com.google.firebase.auth.FirebaseAuth;
  47. import com.google.firebase.auth.FirebaseUser;
  48. import com.google.firebase.auth.GoogleAuthProvider;
  49. import com.google.firebase.database.DataSnapshot;
  50. import com.google.firebase.database.DatabaseError;
  51. import com.google.firebase.database.DatabaseReference;
  52. import com.google.firebase.database.FirebaseDatabase;
  53. import com.google.firebase.database.ValueEventListener;
  54.  
  55. import de.hdodenhof.circleimageview.CircleImageView;
  56.  
  57. import static com.facebook.FacebookSdk.getApplicationContext;
  58.  
  59. /**
  60.  * Created by HP INDIA on 08-Apr-17.
  61.  */
  62. public class FragmentThree extends Fragment implements View.OnClickListener{
  63.  
  64.     private boolean shouldRefreshOnResume = false;
  65.     private boolean justRefreshed = false;
  66.     private boolean usingSignIn = false;
  67.     private EditText email_Id;
  68.     private EditText password;
  69.     private SignInButton mgoogleSign;
  70.     private FirebaseAuth mAuth;
  71.     private static final int RC_SIGN_IN=1;
  72.     private GoogleApiClient mGoogleApiClient;
  73.     private EditText User_Name;
  74.     private Button Sign_Up;
  75.     private FirebaseUser firebaseUser;
  76.     private DatabaseReference forUsers;
  77.     private TextView login_Text;
  78.     private FirebaseAuth.AuthStateListener mAuthStateListener;
  79.     private ProgressDialog progress;
  80.     private ProgressDialog fbProgress;
  81.     private static String TAG="FragmentThree";
  82.     private LoginButton mFbLogin;
  83.     private ImageView edit;
  84.     private String profilePicLink;
  85.     private String profileName;
  86.     private TextView userName;
  87.     private CircleImageView profilePic;
  88.     private DatabaseReference userInfo;
  89.     private CallbackManager callbackManager;
  90.     View view;
  91.     View view_pro;
  92.     private ProgressDialog progressDialog;
  93.  
  94.  
  95.     @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
  96.  
  97.     @Override
  98.     public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
  99.         view = inflater.inflate(R.layout.sign_up_page,container, false);
  100.         view_pro = inflater.inflate(R.layout.profile_layout,container, false);
  101.         fbProgress= new ProgressDialog(getActivity());
  102.         userInfo=FirebaseDatabase.getInstance().getReference().child("Users");
  103.         profilePic=(CircleImageView) view_pro.findViewById(R.id.profile_pic);
  104.         userName=(TextView)view_pro.findViewById(R.id.user_name);
  105.         edit=(ImageView)view_pro.findViewById(R.id.edit);
  106.         fbProgress.setMessage("Connecting to Facebook Account, Please wait...");
  107.         mAuth=FirebaseAuth.getInstance();
  108.         forUsers= FirebaseDatabase.getInstance().getReference().child("Users");
  109.         FacebookSdk.sdkInitialize(getApplicationContext());
  110.         AppEventsLogger.activateApp(getActivity());
  111.         callbackManager= CallbackManager.Factory.create();
  112.         progressDialog=new ProgressDialog(getActivity());
  113.         progress=new ProgressDialog(getActivity());
  114.         email_Id=(EditText)view.findViewById(R.id.email_id);
  115.         progress.setMessage("Connecting to Google Account, please wait...");
  116.         password=(EditText)view.findViewById(R.id.password);
  117.         User_Name=(EditText)view.findViewById(R.id.User_name);
  118.         Sign_Up=(Button)view.findViewById(R.id.sign_up);
  119.         login_Text=(TextView)view.findViewById(R.id.login_text);
  120.         Sign_Up.setOnClickListener(this);
  121.         edit.setOnClickListener(this);
  122.         mgoogleSign=(SignInButton)view.findViewById(R.id.google_login);
  123.         login_Text.setOnClickListener(this);
  124.         mFbLogin=(LoginButton)view.findViewById(R.id.fb_login);
  125.  
  126.         if(mAuth.getCurrentUser()!=null) {
  127.             mAuth=FirebaseAuth.getInstance();
  128.             firebaseUser=mAuth.getCurrentUser();
  129.             forUsers.child(firebaseUser.getUid()).addValueEventListener(new ValueEventListener() {
  130.                 @Override
  131.                 public void onDataChange(DataSnapshot dataSnapshot) {
  132.                     Users user = dataSnapshot.getValue(Users.class);
  133.                     profilePicLink = user.getProfilePicLink();
  134.                     profileName = user.getUserName();
  135.                     Glide
  136.                             .with(getActivity())
  137.                             .load(profilePicLink)
  138.                             .dontAnimate()
  139.                             .diskCacheStrategy(DiskCacheStrategy.ALL)
  140.                             .into(profilePic);
  141.                     userName.setText(profileName);
  142.                 }
  143.  
  144.                 @Override
  145.                 public void onCancelled(DatabaseError databaseError) {
  146.  
  147.                 }
  148.             });
  149.         }
  150.  
  151.         mAuthStateListener= new FirebaseAuth.AuthStateListener() {
  152.             @Override
  153.             public void onAuthStateChanged(@NonNull final FirebaseAuth firebaseAuth) {
  154.  
  155.                 justRefreshed = false;
  156.                 if(usingSignIn)
  157.                 shouldRefreshOnResume = true;
  158.  
  159.             }
  160.  
  161.         };
  162.  
  163.         GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
  164.                 .requestIdToken(getString(R.string.default_web_client_id))
  165.                 .requestEmail()
  166.                 .build();
  167.         if(mGoogleApiClient == null || !mGoogleApiClient.isConnected()){
  168.             try {
  169.                 mGoogleApiClient=new GoogleApiClient.Builder(getApplicationContext())
  170.                         .enableAutoManage(getActivity(),new GoogleApiClient.OnConnectionFailedListener() {
  171.                             @Override
  172.                             public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  173.                                 Toast.makeText(getActivity(),"You get an error", Toast.LENGTH_SHORT).show();
  174.                             }
  175.                         })
  176.                         .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
  177.                         .build();
  178.             } catch (Exception e) {
  179.                 e.printStackTrace();
  180.             }
  181.         }
  182.         mgoogleSign.setOnClickListener(new View.OnClickListener() {
  183.             @Override
  184.             public void onClick(View v) {
  185.                 progress.show();
  186.                 signIn();
  187.             }
  188.         });
  189.  
  190.  
  191.         mFbLogin.setFragment(FragmentThree.this);
  192.         mFbLogin.setReadPermissions("public_profile", "email", "user_friends");
  193.         try {
  194.             mFbLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
  195.                 @Override
  196.                 public void onSuccess(LoginResult loginResult) {
  197.                     Log.v(" FragmentFacebook", "Dekhte hai chal rha hai ki nhi");
  198.                     fbProgress.show();
  199.                     handleFacebookAccessToken(loginResult.getAccessToken());
  200.  
  201.                     // App code
  202.                     //userProfile();
  203.  
  204.                 }
  205.  
  206.                 @Override
  207.                 public void onCancel() {
  208.                     Log.v("FragmentThree 2", "Dekhte hai chal rha hai ki nhi");
  209.                     // App code
  210.                     Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
  211.                 }
  212.  
  213.                 @Override
  214.                 public void onError(FacebookException exception) {
  215.                     Log.v("FragmentThree 3", "Dekhte hai chal rha hai ki nhi");
  216.                     Log.v("Exception", String.valueOf(exception));
  217.                     // App code
  218.                 }
  219.             });
  220.         }
  221.         catch (Exception e){
  222.             Log.v("FACEBOOK", "Error in the loginButton facebook");
  223.             e.printStackTrace();
  224.         }
  225.         //                }
  226.  
  227.         if(mAuth.getCurrentUser()==null) {
  228.             Log.v("Sign up run hoga", String.valueOf(mAuth.getCurrentUser()));
  229.             Log.v("main hu"," sign up view");
  230.             return view;
  231.         }
  232.         else {
  233.             Log.v("profile run hoga",String.valueOf(mAuth.getCurrentUser()));
  234.             Log.v("main hu"," profile view");
  235.             return view_pro;
  236.         }
  237.     }
  238.  
  239.  
  240.  
  241.     @Override
  242.     public void onStart() {
  243.         super.onStart();
  244.  
  245.         mAuth.addAuthStateListener(mAuthStateListener);
  246.     }
  247. //    @Override
  248. //    public void onDestroy() {
  249. //        super.onDestroy();
  250. //        mGoogleApiClient.stopAutoManage(getActivity());
  251. //        mGoogleApiClient.disconnect();
  252. //    }
  253.  
  254.     private void signIn() {
  255.         Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
  256.         startActivityForResult(signInIntent, RC_SIGN_IN);
  257.     }
  258.  
  259.     @Override
  260.     public void onActivityResult(int requestCode, int resultCode, Intent data) {
  261.         super.onActivityResult(requestCode, resultCode, data);
  262.         callbackManager.onActivityResult(requestCode, resultCode, data);
  263.         if (requestCode == RC_SIGN_IN) {
  264.             GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
  265.             if (result.isSuccess()) {
  266.                 // Google Sign In was successful, authenticate with Firebase
  267.                 GoogleSignInAccount account = result.getSignInAccount();
  268.                 firebaseAuthWithGoogle(account);
  269.                 //progress.dismiss();
  270.             }
  271.  
  272.         }
  273.  
  274.     }
  275.  
  276.     @Override
  277.     public void setMenuVisibility(final boolean visible) {
  278.         mAuth = FirebaseAuth.getInstance();
  279.         if (mAuth.getCurrentUser()==null) {
  280.             if (visible) {
  281.  
  282.                 FragmentManager fm = getFragmentManager();
  283.                 login_dialogbox dialogFragment = new login_dialogbox();
  284.                 dialogFragment.show(fm, "LoginPopup");
  285.  
  286.             }
  287.  
  288.             super.setMenuVisibility(visible);
  289.         }
  290.     }
  291.  
  292.  
  293.     @Override
  294.     public void onClick(View view) {
  295.         if(view==Sign_Up){
  296.             // user will register here
  297.  
  298.             registerUser();
  299.         }
  300.         if(view==login_Text){
  301.             //    login user
  302.             usingSignIn = true;
  303.             login();
  304. //            shouldRefreshOnResume=true;
  305.  
  306.  
  307.         }
  308.         if(mAuth.getCurrentUser()!=null) {
  309.             if (view == edit) {
  310.                 startActivity(new Intent(getActivity(), Preferences.class));
  311.             }
  312.         }
  313.     }
  314.     //
  315.     private void login(){
  316.  
  317.         try{
  318.             startActivity(new Intent(getActivity(), loginActivity.class));
  319.         }catch (Exception e) {
  320.             Log.e(TAG,Log.getStackTraceString(e));
  321.         }
  322.  
  323.     }
  324.  
  325.     private  void registerUser(){
  326.         String email=email_Id.getText().toString().trim();
  327.         String pass_word=password.getText().toString().trim();
  328.         final   String user_name=User_Name.getText().toString();
  329.         if(TextUtils.isEmpty(user_name)){
  330.             // email is empty
  331.             Toast.makeText(getActivity(),"please select a name",Toast.LENGTH_SHORT).show();
  332.             return;// to stop the function from executation.
  333.         }
  334.  
  335.  
  336.         if(TextUtils.isEmpty(email)){
  337.             // email is empty
  338.             Toast.makeText(getActivity(),"please enter email",Toast.LENGTH_SHORT).show();
  339.             return;
  340.             // to stop the function from executation.
  341.         }
  342.         if(TextUtils.isEmpty(pass_word)){
  343.             // email is empty
  344.             Toast.makeText(getActivity(),"please enter password",Toast.LENGTH_SHORT).show();
  345.             return;
  346.         }
  347.         // here if everything ok the user will be register
  348.         progressDialog.setMessage("Registering User,please wait...");
  349.         progressDialog.show();
  350.         mAuth.createUserWithEmailAndPassword(email,pass_word)
  351.                 .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>(){
  352.                     @Override
  353.                     public void onComplete(@NonNull Task<AuthResult> task) {
  354.                         if (task.isSuccessful()){
  355.                             //show user profile
  356.                             Toast.makeText(getActivity(),"Registerd successfully",Toast.LENGTH_SHORT).show();
  357.                             String userId= mAuth.getCurrentUser().getUid();
  358.                             DatabaseReference database=userInfo.child(userId);
  359.                             database.child("userName").setValue(user_name);
  360.                             database.child("profilePicLink").setValue("https://imgur.com/a/uVX5M");
  361.                             justRefreshed = false;
  362.                             reLoad();
  363.                             progressDialog.dismiss();
  364.                             //  startActivity(new Intent(getActivity(),userProfileActivity.class));
  365. //                            intent = new Intent(getApplicationContext(),userProfileActivity.class);
  366. //                            intent.putExtra("EdiTtEXTvALUE", User_Name.getText().toString());
  367. //                            startActivity(intent);
  368.                         }else {
  369.                             Toast.makeText(getActivity(),"could not register, pls try again Error is"+ task.getException(),Toast.LENGTH_LONG).show();
  370.                             progressDialog.dismiss();
  371.                         }
  372.                     }
  373.                 });
  374.  
  375.  
  376.     }
  377.  
  378.     private void handleFacebookAccessToken(AccessToken token) {
  379.         shouldRefreshOnResume = false;
  380.         AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
  381.         Log.v("Facebook","Calling");
  382.         mAuth.signInWithCredential(credential)
  383.                 .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
  384.                     @Override
  385.                     public void onComplete(@NonNull Task<AuthResult> task) {
  386.                         if (task.isSuccessful()) {
  387.                             // Sign in success, update UI with the signed-in user's information
  388.                             //   userProfile();
  389.                             firebaseUser=mAuth.getCurrentUser();
  390.                             String personName = firebaseUser.getDisplayName();
  391.                             Uri personPhoto = firebaseUser.getPhotoUrl();
  392.                             DatabaseReference userData = forUsers.child(firebaseUser.getUid());
  393. //                            userData.child("userName").setValue(personName);
  394. //                            userData.child("profilePicLink").setValue(personPhoto.toString());
  395.                             Users user =new Users(personName,personPhoto.toString());
  396.                             userData.setValue(user);
  397.                             Log.i(TAG, "Display Name: " + personName);
  398.                             Log.i(TAG, "given  Name: " + personName);
  399.                             Log.i(TAG, "uri: " + personPhoto);
  400.                             Log.v(TAG, "signInWithCredential:success");
  401.                             Log.v(TAG, "signInWithCredential:success");
  402.                             justRefreshed = false;
  403.                             reLoad();
  404.                             fbProgress.dismiss();
  405.  
  406.                         } else {
  407.                             // If sign in fails, display a message to the user.
  408.                             Log.v("Facebookcheking","Dekhte hai ");
  409.                             Log.w(TAG, "signInWithCredential:failure", task.getException());
  410.                             Toast.makeText(getActivity(), "Authentication failed.",Toast.LENGTH_SHORT).show();
  411.                             LoginManager.getInstance().logOut();
  412.                             fbProgress.dismiss();
  413.  
  414.                         }
  415.  
  416.                         // ...
  417.                     }
  418.                 });
  419.  
  420.     }
  421.  
  422.     private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
  423.         shouldRefreshOnResume = false;
  424.         AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
  425.  
  426.         mAuth.signInWithCredential(credential)
  427.                 .addOnCompleteListener(getActivity(), new OnCompleteListener<AuthResult>() {
  428.                     @Override
  429.                     public void onComplete(@NonNull Task<AuthResult> task) {
  430.                         if (task.isSuccessful()) {
  431.                             // Sign in success, update UI with the signed-in user's information
  432.                             //      userProfile();
  433.                             firebaseUser=mAuth.getCurrentUser();
  434.                             String personName = firebaseUser.getDisplayName();
  435.                             Uri personPhoto = firebaseUser.getPhotoUrl();
  436.                             DatabaseReference userData = forUsers.child(firebaseUser.getUid());
  437. //                            userData.child("userName").setValue(personName);
  438. //                            userData.child("profilePicLink").setValue(personPhoto.toString());
  439.                             Users user =new Users(personName,personPhoto.toString());
  440.                             userData.setValue(user);
  441.                             Log.i(TAG, "Display Name: " + personName);
  442.                             Log.i(TAG, "given  Name: " + personName);
  443.                             Log.i(TAG, "uri: " + personPhoto);
  444.                             Log.v(TAG, "signInWithCredential:success");
  445.                             justRefreshed = false;
  446.                             reLoad();
  447.                             progress.dismiss();
  448.  
  449.  
  450.                         } else {
  451.                             // If sign in fails, display a message to the user.
  452.                             Log.w(TAG, "signInWithCredential:failure", task.getException());
  453.                             Log.v("googlecheking","Dekhte hai ");
  454.                             Toast.makeText(getActivity(), "Authentication failed.",Toast.LENGTH_SHORT).show();
  455.                             progress.dismiss();
  456.  
  457.                         }
  458.  
  459.                         // ...
  460.                     }
  461.                 });
  462.     }
  463.     public void reLoad(){
  464.  
  465.         if(!justRefreshed) {
  466.             FragmentThree fragment = (FragmentThree)
  467.                     getFragmentManager().getFragments().get(2);
  468.             getFragmentManager().beginTransaction()
  469.                     .detach(fragment)
  470.                     .attach(fragment)
  471.                     .commit();
  472.             shouldRefreshOnResume = false;
  473.         }
  474.  
  475.         justRefreshed = true;
  476.         Log.v("reload done", "value of should refresh"+String.valueOf(shouldRefreshOnResume));
  477.  
  478.     }
  479.  
  480.     @Override
  481.     public void onStop() {
  482.         super.onStop();
  483.         Log.v("reload", "onStop");
  484.  
  485.         if(mAuth.getCurrentUser()!=null)
  486.             shouldRefreshOnResume = true;
  487.         else
  488.             shouldRefreshOnResume = false;
  489.         Log.v("value of should refresh", String.valueOf(shouldRefreshOnResume));
  490. //        Log.v("reload", "onStop");
  491.  
  492.     }
  493.  
  494.     @Override
  495.     public void onResume() {
  496.         super.onResume();
  497.         // Check should we need to refresh the fragment
  498.         Log.v("reload ing through", "onresume");
  499.         Log.v(String.valueOf(shouldRefreshOnResume), "onresume");
  500.  
  501.         if(shouldRefreshOnResume){
  502.             // refresh fragment
  503.             Log.v("value of should refresh", String.valueOf(shouldRefreshOnResume));
  504. //            Log.v("reload ing through", "onresume");
  505.             reLoad();
  506.         }
  507.     }
  508.  
  509. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement