app/app/src/main/java/com/danilafe/fencelessgrazing/MainActivity.kt

60 lines
2.0 KiB
Kotlin

package com.danilafe.fencelessgrazing
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.android.volley.Response
import com.android.volley.toolbox.Volley
import com.danilafe.fencelessgrazing.requests.LoginRequest
/**
* First activity in the app. Prompts the user for their
* login information, and attempts authentication to the API.
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// If we've already logged in, no need to do it again.
val prefs = getSharedPreferences("FencelessGrazing", 0)
if(prefs.contains("token")) startCollarActivity()
}
/**
* Send the authentication request to the API.
*/
fun attemptLogin(view: View) {
val usernameField: TextView = findViewById(R.id.username)
val passwordField: TextView = findViewById(R.id.password)
val requestQueue = Volley.newRequestQueue(this)
val loginRequest =
LoginRequest(getString(R.string.apiUrl),
usernameField.text.toString(), passwordField.text.toString(),
Response.Listener {
val editor = getSharedPreferences("FencelessGrazing", 0).edit()
editor.putString("token", it.token)
editor.apply()
startCollarActivity()
},
Response.ErrorListener {
Toast.makeText(this, "Failed to log in! $it", Toast.LENGTH_LONG).show()
})
requestQueue.add(loginRequest)
}
/**
* Once authentication is complete, moves on to the list of collars.
*/
private fun startCollarActivity() {
val newIntent = Intent(this, CollarListActivity::class.java)
startActivity(newIntent)
}
}