This is example Kotlin code for AndroidSDK to LogIn to the ParticleCloud. This assumes you have set up your build.gradle files in AndroidStudio for the correct libraries and have a LoginActivity with EditText email and password widgets and login_button widget. The heavy lifting in this example comes from Anko and Kotlinx coroutines. This hands off to a ValueActivity where you could get your ParticleDevice list and display info, see events, log off, etc. I hope to have a complete app example on GitHub in the future. Remember: the debug console in AndroidStudio and the use of Log.e(), Log.i() and e.printStackTrace() are your friends! I hope this saves you some time . . .
package com.YourCompany.particlemonitor
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import io.particle.android.sdk.cloud.ParticleCloudSDK
import io.particle.android.sdk.cloud.exceptions.ParticleCloudException
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import org.jetbrains.anko.longToast
import org.jetbrains.anko.startActivity
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
ParticleCloudSDK.init(this)
// Pre-populate with text for testing
email.setText ("MyEmail@gmail.com")
password.setText("MyPassWord")
login_button.setOnClickListener { startLogin() } // Bind login_button handler
}
// called from login button
// Kotlin Coroutines version
fun startLogin() {
val myEmail: String = email.text.toString() // Not correct if just email.text
val myPassword: String = password.text.toString()
runBlocking { // Encapsulate in Main (UI) thread
// Deferred Boolean to assess logIn success
var loginSuccess = GlobalScope.async {
// launch new coroutine in background and continue (Non-Blocking)
try {
ParticleCloudSDK.getCloud().logIn(myEmail, myPassword)
Log.i("ParticleCloud", "Successful logIN!")
true
} catch (e: ParticleCloudException) {
Log.e("ParticleCloud", e.bestMessage)
// Don't use any Toast() in WorkerThread, it will crash
e.printStackTrace()
false
}
}
if (loginSuccess.await()) { // Wait for deferred var, continue if logged in
longToast("Logged In!")
// Anko version Hand off to next activity with status
startActivity<ValueActivity>("LoggedIn" to "Yes!")
} else longToast("WRONG! Try again . . .")
}
}
}
Also, this would be an example of handler code for your logOutButton in your ValueActivity:
fun logOut() { // Not a WorkerThread, does not need Async!
ParticleCloudSDK.getCloud().logOut()
Log.i("ParticleCloud", "Logging out . . .")
longToast("Logging Out!")
startActivity<LoginActivity>("LoggedIn" to "No")
}