Handling a onreponse error in a Kotlin program - kotlin

I am trying to work out what's wrong with this code ? I'm new to this. I'm having a response error,
val stringRequest = object : StringRequest(Request.Method.POST, EndPoints.URL_ADD_ARTIST,
Response.Listener<String> { response ->
try {
val obj = JSONObject(response)
Toast.makeText(applicationContext, obj.getString("message"), Toast.LENGTH_LONG).show()
} catch (e: JSONException) {
e.printStackTrace()
}
},
object : Response.ErrorListener {
override fun onErrorResponse(volleyError: VolleyError) {
Toast.makeText(applicationContext, volleyError.message, Toast.LENGTH_LONG).show()
}
}) {
#Throws(AuthFailureError::class)
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("user", user)
params.put("password", password)
params.put("email", email)
return params
}
}
VolleySingleton.instance?.addToRequestQueue(stringRequest)
}
These lines are causing the error.
val stringRequest = object : StringRequest(Request.Method.POST, EndPoints.URL_ADD_ARTIST,
Response.Listener<String> { response ->
val obj = JSONObject(response)

Related

Chain validation failed

I'm having the below Okhttp code:
val client = OkHttpClient()
val mediaType = MediaType.parse("application/x-www-form-urlencoded")
val body = RequestBody.create(mediaType, "tenant_id=xxxx&client_id=xxxx&client_secret=xxxx&resource=xxxx&grant_type=client_credentials")
val request = Request.Builder()
.url("https://sxxx.com/axxx/oauth2/token")
.post(body)
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.build()
val response = client.newCall(request).execute()
And want to convert it usint ktor, so I wrote the below:
class Greeting {
private val httpClient = HttpClient {
}
#Throws(Exception::class)
suspend fun greeting(): String {
val response = httpClient.request {
method = HttpMethod.Post
url {
protocol = URLProtocol.HTTPS
host = "sxxx.com"
path("axxx/oauth2/token")
// encodedParameters
trailingQuery = true
parameters.append("tenant_id", "xxxx")
parameters.append("client_id", "xxxx")
parameters.append("client_secret", "xxxx")
parameters.append("resource", "xxxx")
parameters.append("grant_type", "client_credentials")
}
headers {
append(HttpHeaders.ContentType, "application/x-www-form-urlencoded")
}
}
return response.bodyAsText()
}
}
And calling my new code as:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
val scope = rememberCoroutineScope()
var text by remember {
mutableStateOf("Loading")
}
LaunchedEffect(true){
scope.launch {
text = try {
Greeting().greeting()
} catch (e: Exception) {
e.localizedMessage ?: "error"
}
}
}
Greeting(text)
}
}
}
}
}
#Composable
fun Greeting(text: String) {
Text(text = text)
}
But instead of getting the required token, I'm getting the response: Chain validation failed
Make sure that:
Your server certificate is valid.
Your android system datetime is correct.

How to serialize with retrofit and kotlin

Iam trying to serialize a response into Session class with Retrofit and Kotlin but i have an error. I am using inheritance here and maybe that is the problem i don't know :
"java.lang.IllegalArgumentException: Unable to create call adapter for retrofit2.Response<com.mobile.myapplication.Session> "
open class BaseUser {
var id:Int=0
var correo:String=""
var nombre:String=""
var apellido:String=""
var direccion:String=""
var telefono:String=""
var imagen:String=""
}
class Permiso {
var id:Int=0
var aplicacionId:Int=0
var aplicacionName:String=""
var lectura:Boolean=false
var escritura:Boolean=false
}
class Session: BaseUser() {
var token:String=""
var permiso:List<Permiso> = emptyList()
}
class LocalViewModel(private val retro:Retro= Retro()):ViewModel(){
private val _result = MutableStateFlow("")
val result:StateFlow<String> = _result
init {
viewModelScope.launch {
val jsonObject= JSONObject()
jsonObject.put("correo", "xxxxxx.com")
jsonObject.put("password", "xxxxx")
Log.d("payload",jsonObject.toString())
retro.token(jsonObject.toString())
}
}
}
#Composable
fun main(vm: LocalViewModel= viewModel()){
Text(text = "Hello world")
}
interface APIService {
#POST("api/Auth/SignIn")
fun requestToken(#Body requestBody: RequestBody): Response<Session>
}
class Retro{
fun getinstance(): APIService? {
var service:APIService?=null
try {
// Create Retrofit
val retrofit = Retrofit.Builder()
.baseUrl("xxxxxxxxx")
.addConverterFactory(GsonConverterFactory.create())
.build()
// Create Service
service = retrofit.create(APIService::class.java)
}catch (err:Error){
Log.e("RETROFIT_ERROR", err.toString())
}
return service
}
fun token(payload:String){
val instance=getinstance()
val requestBody = payload.toRequestBody("application/json".toMediaTypeOrNull())
val response = instance?.requestToken(requestBody)
Log.d("response",response.toString())
}
}
API response is like this :
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJOb21icmUiOiJSaWNoYXJkIiwiQXBlbGxpZG8iOiJWw61xdWV6IiwiQ29ycmVvIjoiUnZpcXVlekBzb2Zub21pYy5jb20iLCJEaXJlY2Npb24iOiJIZXJlZGlhIiwiVGVsZWZvbm8iOiJQw6lyZXoiLCJuYmYiOjE2NTc3MjQzOTksImV4cCI6MTY1Nzc0OTU5OSwiaXNzIjoiaHR0cHM6Ly9zb2Zub21pY2FwaS5henVyZXdlYnNpdGVzLm5ldC8ifQ.HtBEe1XlqyU0YBVyGJ1fs-EUiJn8vbWKqvNci2tOboU",
"id": 26,
"correo": "xxxxx.com",
"nombre": "xx",
"apellido": "xx",
"direccion": "xxx",
"telefono": "xx",
"imagen": null,
"permiso": []
}
What is the problem ???
I don't know why but with Response does not work only with Call instead Response!:
interface APIService {
#POST("api/Auth/SignIn")
fun requestToken(#Body requestBody: RequestBody): Call<Session>
}
fun token(payload:String):Session?{
val instance=getinstance()
val requestBody = payload.toRequestBody("application/json".toMediaTypeOrNull())
var session: Session?=null
val response = instance?.requestToken(requestBody) ?: return null
response.enqueue(object : Callback<Session?> {
override fun onResponse(call: Call<Session?>?, response: Response<Session?>) {
val statusCode = response.code()
if (statusCode!=200){
return
}
session = response.body()
}
override fun onFailure(call: Call<Session?>?, t: Throwable?) {
return
}
})
return session
}

Debug is working but release not - Kotlin receives data via Bluetooth

I am working on Bluetooth receiving and sending data. I can send data via Bluetooth but it doesn't work the receive data. I want to get string data and split it. And the split data will show the list view. Since data import is not working, I created string data and called the split method, but it didn't work here either in a release. Can you help me?
Here are my Activity codes;
var mUUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
var mBluetoothSocket: BluetoothSocket? = null
lateinit var mProgress: ProgressDialog
lateinit var mBluetoothAdapter: BluetoothAdapter
var mIsConnected: Boolean = false
lateinit var mAddress: String
lateinit var inputStream: InputStream
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityListBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
mAddress = intent.getStringExtra(MainActivity.EXTRA_ADDRESS).toString()
ConnectToDevice(this).execute()
run()
binding.deneme.setOnClickListener {
sendCommand("denemebeyza")
Log.d("mesajBT", "onCreate: mesaj gonderildi")
}
val string2: String = "deneme, deneme02K, deneme90,klm08B,bitti."
splitList(string2)
}
private fun sendCommand(input: String) {
if (mBluetoothSocket != null) {
try {
mBluetoothSocket!!.outputStream.write(input.toByteArray())
} catch (e: IOException) {
e.printStackTrace()
}
}
}
fun run() {
val LOGTAG: String ="ReadListString"
Log.i(LOGTAG, Thread.currentThread().name)
val buffer = ByteArray(8)
var bytes: Int
val text1: TextView = binding.text2
var readText : String
Log.d("mesajBt", "mesaj metodu")
//Loop to listen for received bluetooth messages
if (mBluetoothSocket != null) {
while (true) {
bytes = try {
bytes = inputStream.read(buffer) ?:0
readText = String(buffer, 0, bytes)
Log.e("Arduino Message", readText)
} catch (e: IOException) {
e.printStackTrace()
Log.d("Else", "message alinamadi.")
break
}
text1.text =readText
}
}
}
fun splitList(output: String) {
val listView : ListView= binding.list1
val textView: TextView= binding.text1
if (mBluetoothSocket != null) {
try {
val list: List<String> = output.split(",").toList()
var arrayAdapter: ArrayAdapter<*>
for (it in list) {
Log.e("TAG", "splitList: $list ")
val list2: ArrayList<String> = ArrayList(list)
textView.text = list2.toString()
}
arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list)
listView.adapter=arrayAdapter
} catch (e: IOException) {
e.printStackTrace()
}
// [A, B, C, D]
}
}
private class ConnectToDevice(c: Context) : AsyncTask<Void, Void, String>() {
private var connectSuccess: Boolean = true
#SuppressLint("StaticFieldLeak")
val context: Context = c
#Deprecated("Deprecated in Java")
override fun onPreExecute() {
super.onPreExecute()
mProgress = ProgressDialog.show(
context,
context.getString(R.string.connecting),
context.getString(R.string.connecting)
)
}
#SuppressLint("MissingPermission")
override fun doInBackground(vararg p0: Void?): String? {
try {
if (mBluetoothSocket == null || !mIsConnected) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
val device: BluetoothDevice = mBluetoothAdapter.getRemoteDevice(mAddress)
mBluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(mUUID)
BluetoothAdapter.getDefaultAdapter().cancelDiscovery()
mBluetoothSocket!!.connect()
inputStream = mBluetoothSocket!!.inputStream
}
}catch (e: IOException) {
connectSuccess = false
e.printStackTrace()
}
return null
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
if (!connectSuccess) {
Log.i("data", "couldn't connect")
} else {
mIsConnected = true
}
mProgress.dismiss()
}
}
}
Here is debugged console log.e output
Thanks, advance :)
I/ReadList-run: main
E/mesajBt: mesaj metodu
W/BluetoothAdapter:getBluetoothService() called with no BluetoothManagerCallback
W/libEGL: EGLNativeWindowType 0xc9a7d808 disconnect failed
W/libEGL:EGLNativeWindowType 0xc95be008 disconnect failed
I/InputMethodManager: startInputInner mService.startInputOrWindowGainedFocus E/ViewRootImpl:sendUserActionEvent() returned.
I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
Since there will be commas between words in data coming from Bluetooth, I used a comma as a separator in the split method. After some research, I corrected a few mistakes. You can change the value of the bytes as 8-16-32-64 according to the incoming data type and size.
Receive method is here
private fun run() {
//Loop to listen for received bluetooth messages
if (mBluetoothSocket != null) {
val TAG: String = "ReadList-run"
Log.i(TAG, Thread.currentThread().name)
val buffer = ByteArray(1024)
var bytes: Int
var readText: String
Log.e("mesajBt", "mesaj metodu")
while (true) {
try {
bytes = inputStream.read(buffer)
readText = String(buffer, 0, bytes)
Log.e("Arduino Message", readText)
splitlist(readText)
break
} catch (e: IOException) {
e.printStackTrace()
Log.d("Else", "message alinamadi.")
break
}
}
}
}
Here is my split method
fun splitList(output: String) {
if (mBluetoothSocket != null) {
try {
val list: List<String> = output.split(",").toList()
for (it in list) {
Log.e("TAG", "splitList: $list ")
}
} catch (e: IOException) {
e.printStackTrace()
}
// [A, B, C, D]
}
}

Get response from server in JWT

I have the following code, where I validate the JWT token (with volley):
private fun validateToken(token: String) {
var queue = Volley.newRequestQueue(this)
val yourUrl = "https://mysite/wp-json/jwt-auth/v1/token/validate"
val parameters = JSONObject()
try {
parameters.put("username", "abc#test.com")
parameters.put("password", "12345678")
} catch (e: java.lang.Exception) {
}
val request: JsonObjectRequest =
object : JsonObjectRequest(
Method.POST, yourUrl, parameters,
Response.Listener { response -> Log.i("onResponse", response.toString()) },
Response.ErrorListener { error -> Log.e("onErrorResponse", error.toString()) }) {
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers: MutableMap<String, String> = HashMap()
// Basic Authentication
//String auth = "Basic " + Base64.encodeToString(CONSUMER_KEY_AND_SECRET.getBytes(), Base64.NO_WRAP);
headers["Authorization"] = "Bearer $token"
return headers
}
}
queue.add(request)
}
It works for me and I get the correct response from the server (in Log.i):
{"code":"jwt_auth_valid_token","data":{"status":200}}
My question is how in my code I do to be able to save the status: 200 in a variable so then it applies an ʻif status == 200` and if it is 200 then send it to another activity.
Add implementation 'com.google.code.gson:gson:2.8.6' to build.gradle(app)
Create Model.tk with:
data class dataServer (
#SerializedName("code") val code : String,
#SerializedName("data") val data : Data
)
data class Data (
#SerializedName("status") val status : Int
)
3. Update code:
private fun validateToken(token: String) {
var queue = Volley.newRequestQueue(this)
val yourUrl = "https://myweb/wp-json/jwt-auth/v1/token/validate"
val parameters = JSONObject()
try {
parameters.put("username", "abc#test.com")
parameters.put("password", "12345678")
} catch (e: java.lang.Exception) {
}
val request: JsonObjectRequest =
object : JsonObjectRequest(
Method.POST, yourUrl, parameters,
Response.Listener {
response ->
Log.i("onResponse", response.toString())
val gson = Gson()
val dataToken = gson.fromJson(response.toString(), dataServer::class.java)
val status = dataToken.data.status
println(status)
// use here if then
},
Response.ErrorListener { error -> Log.e("onErrorResponse", error.toString()) }) {
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers: MutableMap<String, String> = HashMap()
// Basic Authentication
//String auth = "Basic " + Base64.encodeToString(CONSUMER_KEY_AND_SECRET.getBytes(), Base64.NO_WRAP);
headers["Authorization"] = "Bearer $token"
return headers
}
}
queue.add(request)
}

Problems adding values to ArrayList

I'm trying to add url values (imgURL variable) taken from JSON into an ArrayList with Kotlin, but somehow when in the scope of the for loop it doesn't seem to work regardless of having my newArrayURLs array declared as a function variable. Any ideas why is this?
private fun getJsonObjectImg(Url: String): ArrayList<String>{
var paths: ArrayList<String> =ArrayList()
val params = HashMap<String, String>()
var newArrayURLs = ArrayList<String>()
val stringRequest = object : StringRequest(Request.Method.POST, Url, Response.Listener { s ->
try {
val array = JSONObject(s)
var imagesArray = array.getJSONArray("images")
for(i in 0..imagesArray.length() -1 ){
var imgURL = imagesArray.getJSONObject(i).getString("fileName")
newArrayURLs.add(imgURL)
paths.add(imgURL)
}
Log.d("pathsin TRY", paths.count().toString())
} catch(e:JSONException){
Log.d("ERROR------", e.toString())
null
}
}, Response.ErrorListener {
error: VolleyError? ->
try {
Log.d("ERROR======","V")
} catch (e: JSONException){
e.printStackTrace()
}
}) {
override fun getParams(): Map<String, String> = mapOf("uploadedBy" to id)
}
val requestQueue = Volley.newRequestQueue(this)
requestQueue.add<String>(stringRequest)
return newArrayURLs
}