⑤【Kotlin】LoginActivity.kt
package com.example.application0210
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import org.json.JSONObject
class LoginActivity : AppCompatActivity() {
private lateinit var prefs: PrefsManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_login)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.login)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
val etName = findViewById<EditText>(R.id.etName)
val etPass = findViewById<EditText>(R.id.etPass)
val btnLogin = findViewById<Button>(R.id.btnLogin)
prefs = PrefsManager(this)
btnLogin.setOnClickListener {
val name = etName.text.toString().trim()
val pass = etPass.text.toString().trim()
if (name.isEmpty() || pass.isEmpty()) {
Toast.makeText(this, "ユーザー名もしくはパスワードが入力されていません", Toast.LENGTH_LONG).show()
return@setOnClickListener
}
loginUser(name, pass, this) { success, userId ->
if (success) {
Toast.makeText(this, "ログイン成功", Toast.LENGTH_LONG).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(this, "ログイン失敗", Toast.LENGTH_LONG).show()
}
}
}
}
private fun loginUser(username: String, password: String, context: Context, onComplete: (Boolean, String?) -> Unit) {
val url = "https://azurlane.work/wp-json/custom-api/v1/login"
val request = object : StringRequest(
Request.Method.POST, url,
Response.Listener { response ->
val json = JSONObject(response)
if (json.getString("status") == "success") {
val userId = json.getString("user_id")
prefs.saveUserId(userId)
onComplete(true, userId)
} else {
onComplete(false, null)
}
},
Response.ErrorListener {
onComplete(false, null)
}
) {
override fun getParams(): MutableMap<String, String> = HashMap<String, String>().apply {
put("username", username)
put("password", password)
}
}
Volley.newRequestQueue(context).add(request)
}
}解説1
val url = "https://azurlane.work/wp-json/custom-api/v1/login"
val request = object : StringRequest(
Request.Method.POST, url,
Response.Listener { response ->
val json = JSONObject(response)
if (json.getString("status") == "success") {
val userId = json.getString("user_id")
val userName = if (json.has("user_name")) json.getString("user_name") else "Unknown"// functions.phpの返り値名
prefs.saveUserId(userId)
prefs.saveUserName(userName)
onComplete(true, userId)
} else {
onComplete(false, null)
}
},
Response.ErrorListener {
onComplete(false, null)
}
)val json = JSONObject(response)にはWordPressのfunctions.phpに書いた
return rest_ensure_response(array(
'status' => 'success',
'user_id' => $user->ID,
'user_name' => $user->user_login
));の値が格納されています
解説2
val request = object : StringRequest(
... 省略 ...
) {
override fun getParams(): MutableMap<String, String> = HashMap<String, String>().apply {
put("username", username)
put("password", password)
}
}VolleyのStringRequestクラスにはgetParams()というメソッドがあります
リクエストをWordPressにPOSTする(送る)ときのParameterをOverrideします
MutableMap<String, String>はキー(String)と値(String)のペアを持つ可変マップです
ここではHashMap<String, String>()を使って空のHashMapを作成します
作成したHashMapオブジェクトに値を設定するために.apply{}します
put(“username”, username)でキー”username”に対してusernameの値をセットし、
put(“password”, password)でキー”password”に対してpasswordの値をセットします
このコードが実行されると、
username=testuser
password=textpasswordのようなフォームデータがWordPressに送信されます
それをWordPressの
function login_user(WP_REST_Request $request) {
// sanitize
$username = sanitize_text_field($request->get_param('username'));
$password = sanitize_text_field($request->get_param('password'));の部分で受け取ります
BACK