Skip to content
This repository was archived by the owner on Jul 2, 2025. It is now read-only.

Commit 9fd9d17

Browse files
move login in check to ViewModel
1 parent 55e0185 commit 9fd9d17

File tree

6 files changed

+133
-144
lines changed

6 files changed

+133
-144
lines changed

android/canonical/app/build.gradle

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,15 @@ android {
2929
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
3030
}
3131
}
32+
33+
compileOptions {
34+
sourceCompatibility JavaVersion.VERSION_1_8
35+
targetCompatibility JavaVersion.VERSION_1_8
36+
}
37+
38+
kotlinOptions {
39+
jvmTarget = JavaVersion.VERSION_1_8.toString()
40+
}
3241
}
3342

3443
dependencies {

android/canonical/app/src/main/java/com/google/samples/quickstart/canonical/LoginFragment.kt

Lines changed: 16 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,12 @@ import androidx.fragment.app.Fragment
77
import android.view.LayoutInflater
88
import android.view.View
99
import android.view.ViewGroup
10-
import androidx.lifecycle.ViewModelProviders
11-
import com.google.android.gms.auth.api.signin.GoogleSignIn
10+
import androidx.fragment.app.activityViewModels
1211
import com.google.android.gms.common.SignInButton
13-
import com.google.android.gms.common.api.ApiException
14-
import com.google.firebase.auth.GoogleAuthProvider
1512

16-
// TODO: Rename parameter arguments, choose names that match
17-
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
18-
private const val ARG_PARAM1 = "param1"
19-
private const val ARG_PARAM2 = "param2"
20-
21-
/**
22-
* A simple [Fragment] subclass.
23-
* Use the [LoginFragment.newInstance] factory method to
24-
* create an instance of this fragment.
25-
*/
2613
class LoginFragment : Fragment() {
27-
// TODO: Rename and change types of parameters
28-
private var param1: String? = null
29-
private var param2: String? = null
30-
private lateinit var signInVM : SignInViewModel
14+
15+
private val signInVM: SignInViewModel by activityViewModels()
3116

3217
private fun signIn() {
3318
val signInIntent = signInVM.getGoogleSignInClient().signInIntent
@@ -39,59 +24,21 @@ class LoginFragment : Fragment() {
3924

4025
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
4126
if (requestCode == RC_SIGN_IN) {
42-
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
43-
if (task.isSuccessful) {
44-
try {
45-
// Google Sign In was successful, authenticate with Firebase
46-
val account = task.getResult(ApiException::class.java)!!
47-
Log.d(TAG, "Google Sign In was successful:" + account.id)
48-
firebaseAuthWithGoogle(account.idToken!!)
49-
val intent = Intent(context, MainActivity::class.java)
50-
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
51-
startActivity(intent)
52-
} catch (e: ApiException) {
53-
// Google Sign In failed
54-
Log.w(TAG, "Google sign in failed", e)
27+
when (signInVM.firebaseAuth(data)) {
28+
FIREBASE_AUTH_WITH_GOOGLE_SUCCESSFUL -> {
29+
Log.i(LOGIN_FRAGMENT_TAG, "Google sign in successful")
5530
}
56-
} else {
57-
Log.w(TAG, "Google sign in unsuccessful")
58-
}
59-
60-
}
61-
// No other requestCode, ignore it.
62-
}
6331

32+
FIREBASE_AUTH_WITH_GOOGLE_FAIL -> {
33+
Log.w(LOGIN_FRAGMENT_TAG, "Google sign in failed")
34+
}
6435

65-
private fun firebaseAuthWithGoogle(idToken: String) {
66-
Log.d(TAG, "firebaseAuthWithGoogle start")
67-
val credential = GoogleAuthProvider.getCredential(idToken, null)
68-
Log.d(TAG, "firebaseAuthWithGoogle credential:$credential")
69-
signInVM.getFirebaseAuth().signInWithCredential(credential)
70-
.addOnCompleteListener { task ->
71-
Log.d(TAG, "firebase firebaseAuthWithGoogle:task check")
72-
if (task.isSuccessful) {
73-
// Firebase Sign in success, update UI with the signed-in user's information
74-
Log.d(TAG, "firebase signInWithCredential:success")
75-
val user = signInVM.getFirebaseAuth().currentUser
76-
Log.d(TAG, "firebase signed-in user's Email:" + user!!.email)
77-
} else {
78-
// If sign in fails, log a message to the user.
79-
Log.w(TAG, "signInWithCredential:failure", task.exception)
36+
GOOGLE_SIGN_IN_UNSUCCESSFUL -> {
37+
Log.w(LOGIN_FRAGMENT_TAG, "Google sign in unsuccessful")
8038
}
8139
}
82-
}
83-
84-
override fun onCreate(savedInstanceState: Bundle?) {
85-
super.onCreate(savedInstanceState)
86-
arguments?.let {
87-
param1 = it.getString(ARG_PARAM1)
88-
param2 = it.getString(ARG_PARAM2)
8940
}
90-
91-
signInVM = activity?.run {
92-
ViewModelProviders.of(this)[SignInViewModel::class.java]
93-
} ?: throw Exception("Null Activity")
94-
41+
// No other requestCode, ignore it.
9542
}
9643

9744
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
@@ -108,23 +55,10 @@ class LoginFragment : Fragment() {
10855
}
10956

11057
companion object {
111-
/**
112-
* Use this factory method to create a new instance of
113-
* this fragment using the provided parameters.
114-
*
115-
* @param param1 Parameter 1.
116-
* @param param2 Parameter 2.
117-
* @return A new instance of fragment LoginFragment.
118-
*/
11958
const val RC_SIGN_IN = 0
120-
const val TAG = "Login fragment"
121-
// TODO: Rename and change types and number of parameters
122-
@JvmStatic fun newInstance(param1: String, param2: String) =
123-
LoginFragment().apply {
124-
arguments = Bundle().apply {
125-
putString(ARG_PARAM1, param1)
126-
putString(ARG_PARAM2, param2)
127-
}
128-
}
59+
const val GOOGLE_SIGN_IN_UNSUCCESSFUL = 1
60+
const val FIREBASE_AUTH_WITH_GOOGLE_SUCCESSFUL = 2
61+
const val FIREBASE_AUTH_WITH_GOOGLE_FAIL = 3
62+
const val LOGIN_FRAGMENT_TAG = "Login fragment"
12963
}
13064
}

android/canonical/app/src/main/java/com/google/samples/quickstart/canonical/MainActivity.kt

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import android.util.Log
66
import androidx.constraintlayout.widget.ConstraintLayout
77
import androidx.fragment.app.FragmentTransaction
88
import androidx.lifecycle.ViewModelProviders
9-
import com.google.android.gms.auth.api.signin.GoogleSignIn
109
import com.google.android.material.bottomnavigation.BottomNavigationView
1110

1211
class MainActivity : AppCompatActivity() {
@@ -70,24 +69,27 @@ class MainActivity : AppCompatActivity() {
7069
override fun onStart() {
7170
super.onStart()
7271

73-
val account = GoogleSignIn.getLastSignedInAccount(this)
74-
account?.let {
75-
Log.d(TAG, "Already login")
76-
} ?: run {
77-
Log.d(TAG, "No login. Update UI")
78-
findViewById<ConstraintLayout>(R.id.main_activity_view).removeAllViews()
79-
80-
supportFragmentManager
81-
.beginTransaction()
82-
.replace(R.id.main_activity_view, LoginFragment())
83-
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
84-
.commit()
72+
when (signInVM.isLogIn()) {
73+
true -> {
74+
Log.d(MAIN_ACTIVITY_TAG, "Already login")
75+
}
76+
77+
false -> {
78+
Log.d(MAIN_ACTIVITY_TAG, "No login. Update UI")
79+
findViewById<ConstraintLayout>(R.id.main_activity_view).removeAllViews()
80+
81+
supportFragmentManager
82+
.beginTransaction()
83+
.replace(R.id.main_activity_view, LoginFragment())
84+
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
85+
.commit()
86+
}
8587
}
8688
}
8789

8890

8991
companion object {
90-
private const val TAG = "MainActivity"
92+
const val MAIN_ACTIVITY_TAG = "MainActivity"
9193
}
9294

9395
}

android/canonical/app/src/main/java/com/google/samples/quickstart/canonical/MapsFragment.kt

Lines changed: 34 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,7 @@ class MapsFragment : Fragment() {
4444
private lateinit var autocompleteFragment : AutocompleteSupportFragment
4545
private var currentLatLng : LatLng? = null
4646
private var targetMarker : Marker? = null
47-
48-
companion object {
49-
private const val LOCATION_PERMISSION_REQUEST_CODE = 1
50-
private const val ZOOM_VALUE = 14f
51-
private const val PADDING_RATIO = 1.5
52-
private const val FRAGMENT_TAG = "Mapfragment"
53-
}
47+
5448

5549
override fun onRequestPermissionsResult(requestCode: Int,
5650
permissions: Array<String>, grantResults: IntArray) {
@@ -99,27 +93,33 @@ class MapsFragment : Fragment() {
9993
map.isMyLocationEnabled = true
10094
map.setPadding(0, (PADDING_RATIO * autocompleteLayout.height).toInt(),0,0)
10195

102-
fusedLocationClient.lastLocation.addOnSuccessListener(this.activity as Activity) { location ->
96+
fusedLocationClient.lastLocation
97+
.addOnSuccessListener { location ->
10398
// Got last known location. In some rare situations this can be null.
104-
location?.let {
105-
lastLocation = location
106-
currentLatLng = LatLng(location.latitude, location.longitude)
107-
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
108-
currentLatLng,
109-
ZOOM_VALUE
110-
))
111-
map.addMarker(MarkerOptions()
112-
.position(currentLatLng!!)
113-
.title(getString(R.string.my_location_title)))
114-
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
115-
currentLatLng,
116-
ZOOM_VALUE
117-
))
118-
setPlacesSearchBias()
119-
} ?: run{
120-
Toast.makeText(context, getString(R.string.cannot_access_location), Toast.LENGTH_SHORT)
99+
location?.let {
100+
Log.d(MAP_FRAGMENT_TAG, "Locating Success ${location.latitude}, ${location.longitude}")
101+
lastLocation = location
102+
currentLatLng = LatLng(location.latitude, location.longitude)
103+
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
104+
currentLatLng,
105+
ZOOM_VALUE
106+
))
107+
map.addMarker(MarkerOptions()
108+
.position(currentLatLng!!)
109+
.title(getString(R.string.my_location_title)))
110+
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
111+
currentLatLng,
112+
ZOOM_VALUE
113+
))
114+
setPlacesSearchBias()
115+
} ?: run{
116+
Log.d(MAP_FRAGMENT_TAG, "Locating Failed")
117+
Toast.makeText(context, getString(R.string.cannot_access_location), Toast.LENGTH_SHORT)
118+
}
119+
}
120+
.addOnFailureListener {
121+
Log.d(MAP_FRAGMENT_TAG, "fusedLocationClient.lastLocation Failed")
121122
}
122-
}
123123
}
124124

125125
private fun setUpAutocomplete(autocompleteFragment : AutocompleteSupportFragment, mapFragment : SupportMapFragment) {
@@ -132,7 +132,7 @@ class MapsFragment : Fragment() {
132132
}
133133

134134
override fun onError(status: Status) {
135-
Log.e(FRAGMENT_TAG, "An error occurred: $status")
135+
Log.e(MAP_FRAGMENT_TAG, "An error occurred: $status")
136136
}
137137
})
138138
}
@@ -185,4 +185,11 @@ class MapsFragment : Fragment() {
185185

186186
setUpAutocomplete(autocompleteFragment, mapFragment)
187187
}
188+
189+
companion object {
190+
private const val LOCATION_PERMISSION_REQUEST_CODE = 1
191+
private const val ZOOM_VALUE = 14f
192+
private const val PADDING_RATIO = 1.5
193+
private const val MAP_FRAGMENT_TAG = "Mapfragment"
194+
}
188195
}

android/canonical/app/src/main/java/com/google/samples/quickstart/canonical/MeFragment.kt

Lines changed: 2 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import android.view.View
99
import android.view.ViewGroup
1010
import android.widget.Button
1111
import android.widget.TextView
12-
import androidx.lifecycle.ViewModelProviders
12+
import androidx.fragment.app.activityViewModels
1313

1414
private const val ARG_PARAM1 = "param1"
1515
private const val ARG_PARAM2 = "param2"
@@ -20,24 +20,8 @@ private const val ARG_PARAM2 = "param2"
2020
* create an instance of this fragment.
2121
*/
2222
class MeFragment : Fragment() {
23-
// TODO: Rename and change types of parameters
24-
private var param1: String? = null
25-
private var param2: String? = null
26-
private lateinit var signInVM : SignInViewModel
27-
28-
override fun onCreate(savedInstanceState: Bundle?) {
29-
super.onCreate(savedInstanceState)
30-
arguments?.let {
31-
param1 = it.getString(ARG_PARAM1)
32-
param2 = it.getString(ARG_PARAM2)
33-
}
34-
35-
signInVM = activity?.run {
36-
ViewModelProviders.of(this)[SignInViewModel::class.java]
37-
} ?: throw Exception("Null Activity")
38-
39-
}
4023

24+
private val signInVM: SignInViewModel by activityViewModels()
4125

4226
override fun onCreateView(
4327
inflater: LayoutInflater, container: ViewGroup?,

0 commit comments

Comments
 (0)