Commit 757b3b59 by Paktalin

Moved vocabulary data extraction to util class

parent 6737ef4b
......@@ -25,7 +25,7 @@
</value>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">
......
......@@ -6,22 +6,20 @@ import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.firebase.auth.FirebaseAuth
import com.paktalin.vocabularynotebook.*
import com.paktalin.vocabularynotebook.utils.fieldsNotEmpty
import com.paktalin.vocabularynotebook.utils.shortToast
import com.paktalin.vocabularynotebook.utils.signUp
import com.paktalin.vocabularynotebook.utils.userLoggedIn
import kotlinx.android.synthetic.main.activity_log_in.*
class LogInActivity : AppCompatActivity() {
private var mAuth: FirebaseAuth? = null
private var email: String? = null
private var password: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_log_in)
mAuth = FirebaseAuth.getInstance()
btnLogIn!!.setOnClickListener { login() }
btnSignUp!!.setOnClickListener { signUp() }
btnRandomUser!!.setOnClickListener { createRandomUser() }
......@@ -29,7 +27,7 @@ class LogInActivity : AppCompatActivity() {
override fun onStart() {
super.onStart()
if (mAuth!!.currentUser != null) { startUserActivity() }
if (userLoggedIn()) { startUserActivity() }
}
fun login() {
......@@ -38,10 +36,10 @@ class LogInActivity : AppCompatActivity() {
{ removeProgressBar() },
{ startUserActivity() },
{ showToastFailure() },
mAuth, email!!, password!!)
email!!, password!!)
} }
private fun signUp() { processUser { com.paktalin.vocabularynotebook.utils.signUp(mAuth, this, email!!, password!!) } }
private fun signUp() { processUser { signUp(this, email!!, password!!) } }
private fun processUser(authAction: () -> Unit) {
email = etEmail!!.text.toString()
......@@ -67,15 +65,13 @@ class LogInActivity : AppCompatActivity() {
com.paktalin.vocabularynotebook.utils.removeProgressBar(supportFragmentManager)
}
private fun showToastFailure() {
shortToast(this@LogInActivity, getString(R.string.toast_auth_failed))
}
private fun showToastFailure() { shortToast(this@LogInActivity, getString(R.string.toast_auth_failed)) }
@SuppressLint("SetTextI18n")
private fun createRandomUser() {
etEmail.setText("random@gmail.com")
etPassword.setText("123456")
processUser { com.paktalin.vocabularynotebook.utils.signUp(mAuth, this@LogInActivity, email!!, password!!) }
processUser { com.paktalin.vocabularynotebook.utils.signUp(this@LogInActivity, email!!, password!!) }
}
companion object { private val TAG = "VN/" + LogInActivity::class.simpleName }
......
......@@ -5,7 +5,6 @@ import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentReference
import kotlinx.android.synthetic.main.activity_main.*
import android.view.WindowManager
......@@ -14,13 +13,12 @@ import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import com.paktalin.vocabularynotebook.appsetup.ConfiguredFirestore
import kotlinx.android.synthetic.main.fragment_vocabulary.*
import android.support.v7.widget.SearchView
import com.paktalin.vocabularynotebook.*
import com.paktalin.vocabularynotebook.firestoreitems.Vocabulary.Companion.VOCABULARIES
import com.paktalin.vocabularynotebook.ui.fragments.VocabularyFragment
import com.paktalin.vocabularynotebook.utils.addFragment
import com.paktalin.vocabularynotebook.utils.extractVocabularyData
import com.paktalin.vocabularynotebook.utils.shortToast
class MainActivity : AppCompatActivity() {
......@@ -59,36 +57,28 @@ class MainActivity : AppCompatActivity() {
private fun setUpNavigationView() {
navigationView.setNavigationItemSelectedListener { menuItem ->
menuItem.isChecked = true
if(menuItem.itemId == R.id.logOut) { logOut() }
if (menuItem.itemId == R.id.logOut) {
logOut()
}
drawerLayout!!.closeDrawers()
true
}
}
private fun extractVocabularyData() {
val userId = FirebaseAuth.getInstance()!!.currentUser!!.uid
val db = ConfiguredFirestore.instance
val userDocument = db.collection("users").document(userId)
addProgressBar()
userDocument.get()
.addOnSuccessListener { task ->
removeProgressBar()
//todo move Firestore logic and collections names to a separate class
if (task.get(VOCABULARIES) != null) {
val vocabularies: List<DocumentReference> = task.get(VOCABULARIES) as List<DocumentReference>
val vocabulary = db.collection(VOCABULARIES).document(vocabularies[0].id)
vocabularyId = vocabulary.id
// start VocabularyFragment
vocabularyFragment = VocabularyFragment()
val arguments = Bundle()
arguments.putString("vocabularyId", vocabularyId)
addFragment(supportFragmentManager, vocabularyFragment, R.id.container_vocabulary, arguments)
} else {
Log.w(TAG, "There's no collection \"vocabularies\"")
showToastNoWords() }
}
extractVocabularyData(
{ id-> addVocabularyFragment(id) },
{ showToastNoWords() },
{ removeProgressBar() })
}
private fun addVocabularyFragment(vocabularyId: String) {
this.vocabularyId = vocabularyId
vocabularyFragment = VocabularyFragment()
val arguments = Bundle()
arguments.putString("vocabularyId", vocabularyId)
addFragment(supportFragmentManager, vocabularyFragment, R.id.container_vocabulary, arguments)
}
private fun hideKeyboard() {
......@@ -98,7 +88,9 @@ class MainActivity : AppCompatActivity() {
fun hideKeyboardNotFromActivity(activity: Activity) {
val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
var view = activity.currentFocus
if (view == null) { view = View(activity) }
if (view == null) {
view = View(activity)
}
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
......@@ -119,5 +111,7 @@ class MainActivity : AppCompatActivity() {
hideKeyboard()
}
companion object { private val TAG = "VN/" + MainActivity::class.simpleName }
companion object {
private val TAG = "VN/" + MainActivity::class.simpleName
}
}
\ No newline at end of file
package com.paktalin.vocabularynotebook.utils
import android.util.Log
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.DocumentSnapshot
import com.google.firebase.firestore.FirebaseFirestore
import com.paktalin.vocabularynotebook.appsetup.ConfiguredFirestore
import com.paktalin.vocabularynotebook.firestoreitems.UserPojo
import com.paktalin.vocabularynotebook.firestoreitems.Vocabulary
import com.paktalin.vocabularynotebook.ui.activities.LogInActivity
import java.util.*
private const val USERS = "users"
private const val TAG = "VN/FirestoreManager"
fun extractVocabularyData(onSuccess: (vocabularyId: String) -> Unit,
showToastNoWords: () -> Unit, removeProgressBar: () -> Unit) {
val userId = FirebaseAuth.getInstance()!!.currentUser!!.uid
val db = ConfiguredFirestore.instance
val userDocument = db.collection(USERS).document(userId)
userDocument.get()
.addOnSuccessListener { task ->
removeProgressBar()
if (task.get(Vocabulary.VOCABULARIES) != null) {
val vocabularyId = retrieveVocabularyID(task, db)
onSuccess(vocabularyId)
} else {
Log.w(TAG, "There's no collection \"vocabularies\"")
showToastNoWords() } }
}
private fun retrieveVocabularyID(task: DocumentSnapshot, db: FirebaseFirestore): String {
val vocabularies: List<DocumentReference> = task.get(Vocabulary.VOCABULARIES) as List<DocumentReference>
val vocabulary = db.collection(Vocabulary.VOCABULARIES).document(vocabularies[0].id)
return vocabulary.id
}
fun addNewUserToDb(newUser: FirebaseUser, logInActivity: LogInActivity) {
//todo add condition to writing to the db in Firebase Console (request.auth.uid)
val db = ConfiguredFirestore.instance
val user = UserPojo(newUser.email)
db.collection(Vocabulary.VOCABULARIES).add(Vocabulary.Pojo(null))
.addOnSuccessListener { firstVocabularyRef ->
Log.d(TAG, "VocabularyPojo successfully created: " + firstVocabularyRef.path)
user.vocabularies = Collections.singletonList(firstVocabularyRef)
db.collection("users").document(newUser.uid).set(user)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.i(TAG, "Successfully added user to the collection")
logInActivity.startUserActivity()
} else Log.w(TAG, "addUser:failure", task.exception)
}
}
.addOnFailureListener {
Log.w(TAG, "Couldn't add user to the database", it.cause)
deleteUser(newUser)
}
}
......@@ -11,39 +11,16 @@ import com.paktalin.vocabularynotebook.firestoreitems.Vocabulary.Companion.VOCAB
import java.util.*
private const val TAG = "VN/UserManager"
private var mAuth: FirebaseAuth? = FirebaseAuth.getInstance()
private fun deleteUser(user: FirebaseUser) {
fun deleteUser(user: FirebaseUser) {
user.delete()
.addOnSuccessListener { Log.i(TAG, "UserPojo was successfully deleted") }
.addOnFailureListener { Log.i(TAG, "deleteUser:failure", it.cause)}
}
fun addNewUserToDb(newUser: FirebaseUser, logInActivity: LogInActivity) {
//todo add condition to writing to the db in Firebase Console (request.auth.uid)
val db = ConfiguredFirestore.instance
val user = UserPojo(newUser.email)
db.collection(VOCABULARIES).add(Vocabulary.Pojo(null))
.addOnSuccessListener { firstVocabularyRef ->
Log.d(TAG, "VocabularyPojo successfully created: " + firstVocabularyRef.path)
user.vocabularies = Collections.singletonList(firstVocabularyRef)
db.collection("users").document(newUser.uid).set(user)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.i(TAG, "Successfully added user to the collection")
logInActivity.startUserActivity()
} else Log.w(TAG, "addUser:failure", task.exception)
}
}
.addOnFailureListener {
Log.w(TAG, "Couldn't add user to the database", it.cause)
deleteUser(newUser)
}
}
fun login(onComplete: () -> Unit, onSuccess: () -> Unit, onFailure: () -> Unit,
mAuth: FirebaseAuth?, email: String, password: String) {
email: String, password: String) {
mAuth!!.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { onComplete() }
.addOnSuccessListener {
......@@ -56,16 +33,19 @@ fun login(onComplete: () -> Unit, onSuccess: () -> Unit, onFailure: () -> Unit,
}
}
fun signUp(mAuth: FirebaseAuth?, activity: LogInActivity, email: String, password: String) {
fun signUp(activity: LogInActivity, email: String, password: String) {
mAuth!!.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { removeProgressBar(activity.supportFragmentManager) }
.addOnSuccessListener {
Log.d(TAG, "Successfully signed up a new user")
addNewUserToDb(mAuth.currentUser!!, activity)
addNewUserToDb(mAuth!!.currentUser!!, activity)
activity.login()
}
.addOnFailureListener {
Log.d(TAG, "createUserWithEmail:failure", it.fillInStackTrace())
shortToast(activity, it.message!!)
}
}
} }
fun userLoggedIn(): Boolean {
return mAuth!!.currentUser != null
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment