I have created JSONRequest by using volley ussing this tutorial https://www.tutorialspoint.com/how-to-use-volley-library-to-parse-json-in-android-kotlin-app
Blynk APi returns this "1"
i have this error Caused by: org.json.JSONException: Value ["1"] of type org.json.JSONArray cannot be converted to JSONObject
private fun jsonParse() {
val url = "http://blynk-cloud.com/4ae3851817194e2596cf1b7103603ef8/get/D8"
val request = JsonObjectRequest(Request.Method.GET, url, null, { response ->
try {
val JSONObject = response.getJSONArray("test")
for (i in 0 until JSONObject.length()) {
val test = JSONObject.getJSONObject(i)
val status = test.getString("test1")
textView.append("$status")
}
} catch (e: JSONException) {
e.printStackTrace()
}
}, { error -> error.printStackTrace() })
requestQueue?.add(request)
}
Obviously, the response JSON string is not correct. I checked the JSON string with the Url on Firefox, it shows:
Use this style JSON to test is nonsense, I think. If you want to test parsing JSON with Volley lib, you can use public API to test it.
Related
Im trying to get the json data from below URL
https://newsapi.org/v2/everything?q=tesla&from=2021-05-07&sortBy=publishedAt&apiKey=c9e4ed47388d413c8af23fc46a330f8e
But when I run the app it shows
31029-31125 E/Volley: [228776] NetworkUtility.shouldRetryException: Unexpected response code 403 for https://newsapi.org/v2/everything?q=tesla&from=2021-02-23&sortBy=publishedAt&apiK 20ey=c9e4ed47388d413c8af23fc46a330f8e
31029-31125 E/Volley: [228776] NetworkUtility.shouldRetryException: Unexpected response code 403 for https://newsapi.org/v2/everything?q=tesla&from=2021-02-23&sortBy=publishedAt&apiK 20ey=c9e4ed47388d413c8af23fc46a330f8e
But when I enter the URL in chrome browser it shows the json data normally but I got getting the same thing in my app
here is my code in kotlin
fun getNews(context: Context){
var queue: RequestQueue = Volley.newRequestQueue(context)
val url = "https://newsapi.org/v2/everything?q=tesla&from=2021-05-07&sortBy=publishedAt&apiKey=c9e4ed47388d413c8af23fc46a330f8e"
val request = JsonObjectRequest(
Request.Method.GET, url, null,
{ response ->
var list: MutableList<newModel> = mutableListOf<newModel>()
try {
var rootArray: JSONArray = response.getJSONArray("articles")
for(i in 0 until response.length()){
var dataObject: JSONObject = rootArray.get(i) as JSONObject
list.add(newModel(dataObject.getString("urlToImage") , dataObject.getString("title") , dataObject.getString("description") , dataObject.getString("url")))
}
} catch (e: Exception) {
Toast.makeText(
context,
"error while parsing the jsonObject/array",
Toast.LENGTH_LONG
).show()
}
callBack.gotTheNewsData(list)
}) { error ->
Toast.makeText(context, "Error in responce", Toast.LENGTH_SHORT).show()
}
queue.add(request)
}
I was facing the same error and I solved it by passing a header "Mozilla/5.0" to the request.
This can be done in this way on your code.
fun getNews(context: Context){
var queue: RequestQueue = Volley.newRequestQueue(context)
val url = "Your URL here"
val request = object: JsonObjectRequest(
Request.Method.GET, url, null,
{ response ->
var list: MutableList<newModel> = mutableListOf<newModel>()
try {
var rootArray: JSONArray = response.getJSONArray("articles")
for(i in 0 until response.length()){
var dataObject: JSONObject = rootArray.get(i) as JSONObject
list.add(newModel(dataObject.getString("urlToImage") , dataObject.getString("title") , dataObject.getString("description") , dataObject.getString("url")))
}
} catch (e: Exception) {
Toast.makeText(
context,
"error while parsing the jsonObject/array",
Toast.LENGTH_LONG
).show()
}
callBack.gotTheNewsData(list)
}) { error ->
Toast.makeText(context, "Error in responce", Toast.LENGTH_SHORT).show()
}
// overriding function to add Headers.
{
override fun getHeaders(): MutableMap<String, String> {
val headers = HashMap<String, String>()
headers["User-Agent"]="Mozilla/5.0"
return headers
}
}
queue.add(request)
}
It is important to use the object keyword before the construction of the request in order to be able to override the getHeaders() method.
This answer helped me in adding a custom header in Volley request with kotlin.
Override header ["User-Agent"]="Mozilla/5.0"
Or You can use this NewsApi which dont require apikey
https://github.com/SauravKanchan/NewsAPI
This is my first time using the retrofit in android (Java) and i don't know how to do post api
in postman i use Request Body as raw JSON
{
"description": "aaaaaa",
"reportedpriority_description": "Elevé",
"reportedby": "zz",
"assetnum": "111",
"affectedperson": "ahmed"
}
someone can help me with example of code? it return empty response body
void requestcall(){
try
{
HashMap respMap = new HashMap<>();
respMap.put("Key1", "Value1");
respMap.put("Key2", "Value2");
respMap.put("Key3", "Value3");
String resultString = convertToJson(respMap);
sendToServer(resultString);
}
catch (Exception e)
{ }
}
public static String convertToJson(HashMap<String, String> respMap)
{
JSONObject respJson = new JSONObject();
JSONObject respDetsJson = new JSONObject();
Iterator mapIt = respMap.entrySet().iterator();
try
{
while (mapIt.hasNext()) {
HashMap.Entry<String, String> entry = (HashMap.Entry) mapIt.next();
respDetsJson.put(entry.getKey(), entry.getValue());
}
//change according to your response
respJson.put("RESPONSE", respDetsJson);
}
catch (JSONException e)
{
return "";
}
return respJson.toString();
}
There are two ways you can send a body for Post methods, you can either create a JSON string in the format you want. Or you can simply create a model class with the same field names as your JSON keys, and then initialize values to them while sending a request.
Model class:
class Example {
var description: String? = null
var reportedpriority_description: String? = null
var reportedby: String? = null
var assetnum: String? = null
var affectedperson: String? = null
}
Init values:
val obj = Example()
obj.description = "aaaaaa"
// and so on
You can then pass the object to your POST method.
You can refer to documentations to learn how to code the API methods.
Hope this works for you!
When posting a JSONObject to my webservices, I always get the following error:
I/System.out: Error com.android.volley.ParseError: org.json.JSONException: Value Hat of type java.lang.String cannot be converted to JSONObject.message
Always the VolleyError is displayed.
Json looks like this: {"channel1":255,"channel2":255,"channel3":0}
Code to generate JSON:
data class DMX(
var channel1: Int = 0,
var channel2: Int = 0,
var channel3: Int = 0,
)
val DMXValues = DMX(255, 255, 0)
val j = Gson().toJson(DMXValues)
val json = JSONObject(j)
My Webservice processes this one fine, with no errors.
But what's the "Value Hat"?? Didn't find anything on Google...
My code:
val jsonRequest = JsonObjectRequest(Request.Method.POST, url, json, { response ->
Toast.makeText(applicationContext, response.toString(), Toast.LENGTH_SHORT).show()
},
{error: VolleyError ->
println("Error $error.message")
Toast.makeText(applicationContext, "Didn't work!", Toast.LENGTH_SHORT).show()
})
Can you post the exact json you used to get this error, basically your json string has a error(syntax error - in the source string or a duplicated key) in being converted into a JSONObject.
Sample kotlin verion of String request with post body,
val stringRequest: StringRequest = object : StringRequest(httpMethod, url, Response.Listener { response ->
// on response implementation
}, Response.ErrorListener { error ->
//on error implementation
}) {
#Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
return httpHeaders ?: java.util.HashMap()
}
#Throws(AuthFailureError::class)
override fun getBody(): ByteArray {
// return your body here
return 'you body'
}
}
I wanna send data that is content-type : application/json. when I send not creating data class file but only parsing JSONObject to String, I got incorrect string like this
{\"mobile\":\"01011111111\"}" I want to send without this \. how can I remove that?
here is my code
override fun checkSMS(mobile: String): Call<NetworkResult> {
val jsonObject = JSONObject()
try {
jsonObject.put("mobile", mobile)
} catch (e: JSONException) {
e.printStackTrace()
}
showLog("jsonObject : "+jsonObject)
return service.checkSMS(jsonObject.toString())
}
#POST("smsCheck")
fun checkSMS(
#Body params: String
) :Call<NetworkResult>
Try with accumulate
val jsonObject = JSONObject()
jsonObject.accumulate("mobile",mobile)
Your POST Request #Body should be JSONObject
#POST("smsCheck")
fun checkSMS(
#Body json: JSONObject
) :Call<NetworkResult>
FYI
For nameValuePairs issue You can use JsonObject.
package com.google.gson;
JsonObject reqObject = new JsonObject();
try{
reqObject.addProperty("mobile","12345678");
}
Add this in build.gradle section
implementation "com.google.code.gson:gson:2.8.6"
i am trying Android App to connect the Mysql through API call. I am following this article to create the app.
https://www.simplifiedcoding.net/volley-with-kotlin/
But I have populate the mysql JSON result into 2 textView android objects. I am getting error while compile the String Request.
type mismatch: Expected string, Found: int, and another error which are attached here.
StringRequest Function error
Type mismatch error
My code is here. I am new to this Kotlin, I couldn't figure out upto my level. where is the problem caused.. How do I resolve this?
//MainActivity.kt
val requestQueue = Volley.newRequestQueue(this#MainActivity)
downtxtvalue = findViewById<TextView>(R.id.downtxt) as TextView
uploadtxtvalue = findViewById<TextView>(R.id.uptxt) as TextView
//findViewById<Button>(R.id.btnGetspeed).setOnContextClickListener(getSpeed()){
val stringRequest = StringRequest(Request.Method.GET,URL_GET_ARTIST;
Response.Listener<String> { s ->
try {
val obj = JSONObject(s)
if (!obj.getBoolean("error")) {
val array = obj.getJSONArray("internet")
for (i in 0..array.length() - 1) {
val objValue = array.getJSONObject(i)
objValue.getInt("download_value")
objValue.getInt("upload_value")
}
}
} catch (e: JSONException) {
e.printStackTrace()
}
},
Response.ErrorListener { volleyError -> Toast.makeText(applicationContext, volleyError.message, Toast.LENGTH_LONG).show() }
requestQueue.add(stringRequest)
} }