У меня есть приложение для Android, над которым я работаю, в котором я делаю запрос API с помощью Volley, после вызова API я получаю кучу объектов JSON.Теперь я сохранил значения в значения по умолчанию.после сохранения я теперь попытался отобразить значения в элементах пользовательского интерфейса, но все пусто и значения не отображаются.Мои коды выделены ниже
fun loginUser(context: Context, email: String, password: String, completion: (Boolean) -> Unit): Unit {
val jsonBody = JSONObject()
jsonBody.put("email", email)
jsonBody.put("password", password)
val requestBody = jsonBody.toString()
val loginRequest = object : JsonObjectRequest(Method.POST, URL_LOGIN, null, Response.Listener {response ->
try {
userEmail = response.getString("user")
authToken = response.getString("token")
isLoggedIn = true
completion(true)
} catch (e: JSONException) {
Log.d("JSON", "EXC:" + e.localizedMessage)
completion(false)
}
}, Response.ErrorListener { error ->
Log.d("ERROR", "Could not login user: $error")
completion(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getBody(): ByteArray {
return requestBody.toByteArray()
}
}
Volley.newRequestQueue(context).add(loginRequest)
}
fun findUserByEmail(context: Context, completion: (Boolean) -> Unit): Unit {
val finUserByEmailRequest = object : JsonObjectRequest(Method.GET, "$URL_GET_USER$userEmail", null, Response.Listener {response ->
try {
UserDataService.name = response.getString("name")
UserDataService.email = response.getString("email")
UserDataService.avatarName = response.getString("avatarName")
UserDataService.avatarColor = response.getString("avatarColor")
UserDataService.id = response.getString("_id")
val userDataChanaged = Intent(BROADCAST_USER_DATA_CHANGED)
LocalBroadcastManager.getInstance(context).sendBroadcast(userDataChanaged)
completion(true)
} catch (e: JSONException) {
Log.d("JSON", "EXC:" + e.localizedMessage)
completion(false)
}
}, Response.ErrorListener { error ->
Log.d("ERROR", "Could not find user: $error")
completion(false)
}) {
override fun getBodyContentType(): String {
return "application/json; charset=utf-8"
}
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["Authorization"] = "Bearer $authToken"
return headers
}
}
Volley.newRequestQueue(context).add(finUserByEmailRequest)
}
my MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
LocalBroadcastManager.getInstance(this).registerReceiver(userDataChangeReceiver, IntentFilter(BROADCAST_USER_DATA_CHANGED))
}
private val userDataChangeReceiver = object : BroadcastReceiver() {
override fun onReceive(contect: Context?, intent: Intent?) {
if (AuthService.isLoggedIn) {
userNameNavHeader.text = UserDataService.name
userEmailNavHeader.text = UserDataService.email
val resourceId = resources.getIdentifier(UserDataService.avatarName, "drawable", packageName)
userImageNavHeader.setImageResource(resourceId)
userImageNavHeader.setBackgroundColor(UserDataService.returnAvatarColor(UserDataService.avatarColor))
loginBtnNavHeader.text = "Logout"
}
}
}
Где вызывается метод loginUser
fun loginLoginBtnClicked(view: View): Unit {
val email = loginEmailTxt.text.toString()
val password = loginPasswordTxt.text.toString()
AuthService.loginUser(this, email, password) {success ->
if (success) {
AuthService.findUserByEmail(this) {fsuccess ->
if (fsuccess) {
finish()
}
}
}
}
}