Guest User

FragmentThree.java

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