Write in a database with Android - android

I am trying to write in a database with the library Volley using Kotlin and when I try nothing happened. I used Postman to see if there is a problem from the server and all is okay. According to me the problem comes from this part of my code:
val stringRequest = object : StringRequest(Request.Method.POST, "myURL",
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("name", name)
params.put("genre", genre)
return params
}
}
VolleySingleton.instance?.addToRequestQueue(stringRequest)
Thank you a lot to try to solve my problem !!!

Related

Empty ArrayList after using Volley in Kotlin

I'm working on a simple app where I add elements in a ListView dynamically, for this I'm using Volley to read JSON and then add all the information inside a data class, as I saw in other questions Volley is asynchronous so when I try to get the size of my list it return 0 because it was executed before Volley.
I can't figure out how to wait for volley to finish before continuing with the code in Kotlin, this is the code where I get the data:
private fun getUsers() {
val url = ""
val requestQueue = Volley.newRequestQueue(this)
val request = JsonObjectRequest(Request.Method.GET, url, null, {
response ->try {
val jsonArray = response.getJSONArray("" + "data")
for (i in 0 until jsonArray.length()) {
val distr = jsonArray.getJSONObject(i)
val getUser = distr.getString("Utilizador").toString()
val getCargo = distr.getString("Cargo").toString()
val getEstado = distr.getString("Estado").toString().toInt()
listUtilizadores.add(Utilizadores(getUser, getCargo, getEstado))
}
} catch (e: JSONException) {
e.printStackTrace()
}
}, { error -> error.printStackTrace() })
requestQueue.add(request)
}
And how I call it inside onCreate()
getUsers()
Log.i("Testing", "Value: " + listUtilizadores.size)
Thank you
Can you try with JsonArrayRequest.
val request =JsonArrayRequest(
url,
Response.Listener { response ->
if (response != null) {
for (i in 0 until response.length()) {
try {
val distr = response.getJSONObject(i)
val getUser = distr.getString("Utilizador").toString()
val getCargo = distr.getString("Cargo").toString()
val getEstado = distr.getString("Estado").toString().toInt()
listUtilizadores.add(Utilizadores(getUser, getCargo, getEstado))
}
} catch (e: JSONException) {
e.printStackTrace()
}
}, { error -> error.printStackTrace() })
requestQueue.add(request)
}

put parameter in request volley android with Kotlin

I need make request with Volley and kotlin my cod is
val stringReq = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
var strResp = response.toString()
val jsonObj: JSONObject = JSONObject(strResp)
val jsonArray: JSONArray = jsonObj.getJSONArray("curso")
for (i in 0 until jsonArray.length()) {
var jsonInner: JSONObject = jsonArray.getJSONObject(i)
listGeral.add(jsonInner.get("interpret").toString());
listGeral2.add(jsonInner.get("titel").toString());
listGeral3.add(jsonInner.get("id").toString());
}
},
Response.ErrorListener {
})
queue.add(stringReq)
Now I need send 3 parameters for php. How do I put instruction for send parameter?
you can write the below code after Response.ErrorListener
val sr: StringRequest = object : StringRequest(Method.POST, "url",
Response.Listener { response ->
//your response
},
Response.ErrorListener { error ->
//your error
}) {
override fun getParams(): Map<String, String> {
val params: MutableMap<String, String> = HashMap()
params["user"] = "YOUR USERNAME"
params["pass"] = "YOUR PASSWORD"
return params
}
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val params: MutableMap<String, String> = HashMap()
params["Content-Type"] = "application/x-www-form-urlencoded"
return params
}
}
queue.add(sr)

Volley - JsonObjectRequest - parseNetworkResponse() is not being called

I would like to save response code from volley calls to db, but it seems like parseNetworkResponse() is not being called. Any idea why does it behave like this?
All of my calls are GET, some has code 500 and some has code 200 with json response, so I think it should be called.
private fun createCall(url: String, type: Int, data: JSONObject, callback: Int, request: DbRequestEntity) {
val jsonRequest = object : JsonObjectRequest(type, url, data,
Response.Listener { response ->
Log.d(tag, "Response $response")
try {
callback(response, data, callback, request)
} catch (e: Exception) {
request.responseCode = 999
request.responseMessage = e.message
db.requestMoodel().update(request)
Log.d(tag, "API callback error $e ${e.localizedMessage} ${e.stackTrace}")
}
},
Response.ErrorListener { error ->
Log.d(tag, "API error $error")
errorCallback(error, callback)
}
) {
val tag = "JsonObjectRequest"
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers[ConstantsStorage.API_HEADER_CLIENT_ID] = ConstantsStorage.API_HEADER_CLIENT_ID_VALUE
headers[ConstantsStorage.API_HEADER_CLIENT_CONTENT_TYPE] = ConstantsStorage.API_HEADER_CLIENT_CONTENT_TYPE_VALUE
return headers
}
override fun parseNetworkResponse(response: NetworkResponse): Response<JSONObject> {
Log.d(tag, "Response code = ${response.statusCode}") //not getting this message to Logcat
return super.parseNetworkResponse(response)
}
}
queue.add(jsonRequest)
}
Replace your parseNetworkResponse function with below code
override fun parseNetworkResponse(response: NetworkResponse): Response<JSONObject> {
try {
if (response.data.length == 0) {
byte[] responseData = "{}".getBytes("UTF8");
response = new NetworkResponse(response.statusCode, responseData, response.headers, response.notModified);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return super.parseNetworkResponse(response)
}

How to add a custom header in a Volley request with Kotlin

I have some code. In Volley code:
val queue = Volley.newRequestQueue(context)
val stringRequest = StringRequest(
Request.Method.GET,
linkTrang,
Response.Listener<String> { response ->
mTextView.text = "Response is: " + response.substring(0, 500));
},
Response.ErrorListener { })
{
}
queue.add(stringRequest)
How do I set a header called Authorization in this?
I was able to do it in Kotlin using:
val linkTrang = "YOUR URL"
val queue = Volley.newRequestQueue(this)
val stringRequest = object: StringRequest(Request.Method.GET, linkTrang,
Response.Listener<String> { response ->
Log.d("A", "Response is: " + response.substring(0,500))
},
Response.ErrorListener { })
{
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["Authorization"] = "Basic <<YOUR BASE64 USER:PASS>>"
return headers
}
}
queue.add(stringRequest)
It is important to use the object keyword before the construction of the request in order to be able to override the getHeaders() method.

I am getting a token back from my API and can print it in Logcat I need to save that response and I'm not having any luck. I'm new to kotlin

1.I'm getting the correct response back and can view it in logcat, but I need to save that response and store it for later. I'm trying to save it in the var token, but when looking in memory token remains empty even after correctly getting the response. Any suggestions would be appreciated.
class Login : AppCompatActivity() {
var token = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
//POST data
log_login.setOnClickListener {
// "http://localhost:1842/token"
var url = "https://elimination.azurewebsites.net/token"
val que = Volley.newRequestQueue(this#Login)
val stringRequest = object : StringRequest(Request.Method.POST, url,
Response.Listener { response -> Toast.makeText(this#Login, response, Toast.LENGTH_LONG).show()
Log.e("Test", response)
//trying to set token to response
token = response},
Response.ErrorListener { error -> Toast.makeText(this#Login, error.toString(), Toast.LENGTH_LONG).show()
Log.e("Wrong", error.toString())}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("grant_type", "password")
params.put("Username", input_email.toString())
params.put("Password", input_password.toString())
return params
}
}
que.add(stringRequest)
val intent = Intent(this, Profile::class.java)
intent.putExtra("token", token) //passing token to profile intent
startActivity(intent)
}
}
}
Try moving the intent initialization to when you receive the correct response:
log_login.setOnClickListener {
// "http://localhost:1842/token"
var url = "https://elimination.azurewebsites.net/token"
val que = Volley.newRequestQueue(this#Login)
val stringRequest = object : StringRequest(Request.Method.POST, url,
Response.Listener { response -> Toast.makeText(this#Login, response, Toast.LENGTH_LONG).show()
Log.e("Test", response)
//trying to set token to response
token = response
val intent = Intent(this, Profile::class.java)
intent.putExtra("token", token)
startActivity(intent)
},
Response.ErrorListener { error -> Toast.makeText(this#Login, error.toString(), Toast.LENGTH_LONG).show()
Log.e("Wrong", error.toString())}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("grant_type", "password")
params.put("Username", input_email.toString())
params.put("Password", input_password.toString())
return params
}
}
que.add(stringRequest)
}
Or calling a method when you receive the result:
log_login.setOnClickListener {
// "http://localhost:1842/token"
var url = "https://elimination.azurewebsites.net/token"
val que = Volley.newRequestQueue(this#Login)
val stringRequest = object : StringRequest(Request.Method.POST, url,
Response.Listener { response -> Toast.makeText(this#Login, response, Toast.LENGTH_LONG).show()
Log.e("Test", response)
//trying to set token to response
token = response
openNextActivity(token);
},
Response.ErrorListener { error -> Toast.makeText(this#Login, error.toString(), Toast.LENGTH_LONG).show()
Log.e("Wrong", error.toString())}) {
override fun getParams(): Map<String, String> {
val params = HashMap<String, String>()
params.put("grant_type", "password")
params.put("Username", input_email.toString())
params.put("Password", input_password.toString())
return params
}
}
que.add(stringRequest)
}
fun openActivity(token: String){
val intent = Intent(this, Profile::class.java)
intent.putExtra("token", token)
startActivity(intent)
}
The important thing is you were trying to execute the intent initialization syncronously, but you receive the token async so you token variable was not filled when the intent was executed.

Categories

Resources