Kotlin Retrofit response.body() returned null - android

So I'm trying to fetch an API with endpoint https://someURL.com/switching-product/switch?orderID=A001,
This is the returned JSON format as seen from Postman.
So I use this Interface in the NetworkConfig.kt class to fetch this endpoint:
//Endpoint: https://someURL.com/switching-product/switch?orderID=A001
interface getOutstandingOrderDetail{
#GET("switch")
fun getOutstandingOrderDetail(#Query("orderID") orderID: String): Call<OutstandingOrderDetailPOJODataClassData>
}
and store it in this data class (Generated by an Android Extension that generate POJO from JSON):
data class OutstandingOrderDetailPOJODataClass(
#field:SerializedName("data")
val data: OutstandingOrderDetailPOJODataClassData? = null,
#field:SerializedName("error")
val error: Error? = null
)
data class OutstandingOrderDetailPOJODataClassData(
#field:SerializedName("Header")
val header: OutstandingOrderDetailPOJODataClassHeader? = null,
#field:SerializedName("Detail")
val detail: List<OutstandingOrderDetailPOJODataClassDetailItem?>? = null
)
data class OutstandingOrderDetailPOJODataClassHeader(
#field:SerializedName("buyer_address")
val buyerAddress: String? = null,
#field:SerializedName("total_price")
val totalPrice: Int? = null,
#field:SerializedName("buyer_name")
val buyerName: String? = null,
#field:SerializedName("status_confirmed_yn")
val statusConfirmedYn: String? = null,
#field:SerializedName("order_date")
val orderDate: String? = null,
#field:SerializedName("outlet_id")
val outletId: String? = null,
#field:SerializedName("nip")
val nip: String? = null,
#field:SerializedName("jumlah_product")
val jumlahProduct: Int? = null,
#field:SerializedName("last_update")
val lastUpdate: String? = null,
#field:SerializedName("phone_number")
val phoneNumber: String? = null,
#field:SerializedName("order_running_id")
val orderRunningId: Int? = null,
#field:SerializedName("status_tagged_yn")
val statusTaggedYn: String? = null,
#field:SerializedName("order_id")
val orderId: String? = null
)
data class OutstandingOrderDetailPOJODataClassError(
#field:SerializedName("msg")
val msg: String? = null,
#field:SerializedName("code")
val code: Int? = null,
#field:SerializedName("status")
val status: Boolean? = null
)
data class OutstandingOrderDetailPOJODataClassDetailItem(
#field:SerializedName("item_price_new")
val itemPriceNew: Int? = null,
#field:SerializedName("item_name_new")
val itemNameNew: String? = null,
#field:SerializedName("total_price")
val totalPrice: Int? = null,
#field:SerializedName("item_price")
val itemPrice: Int? = null,
#field:SerializedName("item_name")
val itemName: String? = null,
#field:SerializedName("status_refund")
val statusRefund: String? = null,
#field:SerializedName("detail_id")
val detailId: Int? = null,
#field:SerializedName("procode_new")
val procodeNew: String? = null,
#field:SerializedName("refund_date")
val refundDate: String? = null,
#field:SerializedName("request_refund")
val requestRefund: String? = null,
#field:SerializedName("procode")
val procode: String? = null,
#field:SerializedName("last_update")
val lastUpdate: String? = null,
#field:SerializedName("item_qty_new")
val itemQtyNew: Int? = null,
#field:SerializedName("order_id")
val orderId: String? = null,
#field:SerializedName("total_price_new")
val totalPriceNew: Int? = null,
#field:SerializedName("item_qty")
val itemQty: Int? = null,
#field:SerializedName("refund")
val refund: Int? = null
)
This is a code snippet of the fragment where I fetch the URL data:
private fun fetchOrderedItemListData() {
NetworkConfig()
.getOutstandingDetailOrderedItemListService()
.getOutstandingOrderDetailOrderedItemList("A001")
.enqueue(object :
Callback<OutstandingOrderDetailPOJODataClassData> {
override fun onFailure(
call: Call<OutstandingOrderDetailPOJODataClassData>,
t: Throwable
) {
Log.i("Order", "It Failed!!")
if (call.isCanceled) {
Toast.makeText(
(activity as AppCompatActivity),
"Request Aborted",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
(activity as AppCompatActivity),
t.localizedMessage,
Toast.LENGTH_SHORT
).show()
}
}
override fun onResponse(
call: Call<OutstandingOrderDetailPOJODataClassData>,
response: Response<OutstandingOrderDetailPOJODataClassData>
) {
Log.i("Order", "Ordered Item FEtched -> \n ${response.body()}") <= This is for debugging purpose
binding.rvOrderedItemList.adapter =
response.body()
?.let { OrderedItemListAdapter(it, this#OrderDetailFragment) }
binding.rvOrderedItemList.layoutManager =
LinearLayoutManager((activity as AppCompatActivity))
}
})
}
As you can see above I use Log.i to try to print the response.body() in the LogCat, However it returns null in the Log Cat. You can see it here.
Am I missing something ? If there's any detail that I left out for this question, feel free to ask.

Your Retrofit function is set up as:
#GET("switch")
fun getOutstandingOrderDetail(#Query("orderID") orderID: String): Call<OutstandingOrderDetailPOJODataClassData>
The data type in the Call<> needs to match your JSON. You have data classes that match your JSON... but the root of that hierarchy is OutstandingOrderDetailPOJODataClass, not OutstandingOrderDetailPOJODataClassData. So, change your Retrofit function to:
#GET("switch")
fun getOutstandingOrderDetail(#Query("orderID") orderID: String): Call<OutstandingOrderDetailPOJODataClass>

Related

Validation failed, or the endpoint has been spammed. {Github's API}

I'm using Github's search API in Android App through retrofit
https://api.github.com/search/users?q=user
The API Service file states as :
interface ApiService {
#GET("search/users")
suspend fun getUsers(#Query ("q") searchQuery: String)
: UserResponse
}
Meanwhile, the data class is :
data class UserResponse(
val total_count: Int,
val incomplete_results: Boolean,
val items: MutableList<Item>
){
data class Item( val avatar_url: String,
val events_url: String,
val followers_url: String,
val following_url: String,
val gists_url: String,
val gravatar_id: String,
val html_url: String,
val id: Int,
val login: String,
val node_id: String,
val organizations_url: String,
val received_events_url: String,
val repos_url: String,
val site_admin: Boolean,
val starred_url: String,
val subscriptions_url: String,
val type: String,
val url: String)
}
But, I'm having an error
FATAL EXCEPTION: DefaultDispatcher-worker-2
Process: com.example.github, PID: 3542
retrofit2.HttpException: HTTP 422
I tried change #Query param but it's not working
data class Class1 (
#SerializedName("total_count")
var totalCount: Int? = null,
#SerializedName("incomplete_results")
var incompleteResults : Boolean?= null,
#SerializedName("items") var items: ArrayList<Items> = arrayListOf()
)
data class Items (
#SerializedName("login")
var login: String? = null,
#SerializedName("id")
var id: Int? = null,
#SerializedName("node_id")
var nodeId: String? = null,
#SerializedName("avatar_url")
var avatarUrl: String? = null,
#SerializedName("gravatar_id")
var gravatarId: String? = null,
#SerializedName("url")
var url: String? = null,
#SerializedName("html_url")
var htmlUrl: String? = null,
#SerializedName("followers_url")
var followersUrl : String? = null,
#SerializedName("following_url")
var followingUrl : String? = null,
#SerializedName("gists_url")
var gistsUrl : String? = null,
#SerializedName("starred_url")
var starredUrl: String? = null,
#SerializedName("subscriptions_url")
var subscriptionsUrl : String? = null,
#SerializedName("organizations_url")
var organizationsUrl : String? = null,
#SerializedName("repos_url")
var reposUrl: String? = null,
#SerializedName("events_url")
var eventsUrl : String? = null,
#SerializedName("received_events_url" )
var receivedEventsUrl : String? = null,
#SerializedName("type")
var type : String? = null,
#SerializedName("site_admin")
var siteAdmin : Boolean? = null,
#SerializedName("score")
var score: Int? = null
)

Get a specific value of JSON data Kotlin

I am trying to get a specific value from my JSON data. I could successfully call the entire json data,jsonOutput. But the thing is when I call a specific value in the jsonOutput, it shows me nullPointerError. I do not know why I lost the data when I call my data class. I marked the part I lost them with The problem occurs here. How can I get adminArea1?
I shared one data class as a sample. You can create the data classes with "Kotlin data class File from JSON".
I referred to many answers and examples but was hard to know the reason.
My code
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.networkBtn.setOnClickListener(View.OnClickListener {
var thread = NetworkThread()
thread.start()
})
}
inner class NetworkThread : Thread() {
override fun run() {
var url =
URL("https://www.mapquestapi.com/geocoding/v1/reverse?key=LBK8QWxDPYHfmeYVlEP1IO3BVbWHyznB&" +
"location=Your_laptitue,Your_longitute&includeRoadMetadata=true&includeNearestIntersection=true")
var countryCodeBufferedReader =
BufferedReader(InputStreamReader(url.openConnection().getInputStream()))
var stringBuffer = StringBuffer()
do {
var string = countryCodeBufferedReader.readLine()
if (string != null) {
stringBuffer.append(string)
}
} while (string != null)
var jsonObject = JSONObject(stringBuffer.toString())
val gson: Gson = GsonBuilder().setPrettyPrinting().create()
val jsonOutput: String = gson.toJson(jsonObject)
//The problem occurs here
var countryData = gson.fromJson(jsonOutput, NameValuePairsXXXXX::class.java)
val jsonOutput2 = countryData.adminArea1
Log.d("jsonOutput", jsonOutput)
Log.d("jsonOutput2", jsonOutput2)
runOnUiThread {
binding.lapLonText.text = jsonOutput2
}
}
}
}
Data class
Use this class and use Response data class to parse json,
data class Response(
val options: Options? = null,
val results: List<ResultsItem?>? = null,
val info: Info? = null
)
data class Options(
val thumbMaps: Boolean? = null,
val maxResults: Int? = null,
val ignoreLatLngInput: Boolean? = null
)
data class LatLng(
val lng: Double? = null,
val lat: Double? = null
)
data class Info(
val statuscode: Int? = null,
val copyright: Copyright? = null,
val messages: List<Any?>? = null
)
data class ProvidedLocation(
val latLng: LatLng? = null
)
data class Copyright(
val imageAltText: String? = null,
val imageUrl: String? = null,
val text: String? = null
)
data class DisplayLatLng(
val lng: Double? = null,
val lat: Double? = null
)
data class LocationsItem(
val dragPoint: Boolean? = null,
val displayLatLng: DisplayLatLng? = null,
val adminArea4: String? = null,
val unknownInput: String? = null,
val adminArea5: String? = null,
val adminArea6: String? = null,
val postalCode: String? = null,
val adminArea1: String? = null,
val adminArea3: String? = null,
val sideOfStreet: String? = null,
val type: String? = null,
val adminArea6Type: String? = null,
val geocodeQualityCode: String? = null,
val adminArea4Type: String? = null,
val linkId: String? = null,
val roadMetadata: Any? = null,
val street: String? = null,
val nearestIntersection: Any? = null,
val adminArea5Type: String? = null,
val mapUrl: String? = null,
val geocodeQuality: String? = null,
val adminArea1Type: String? = null,
val adminArea3Type: String? = null,
val latLng: LatLng? = null
)
data class ResultsItem(
val locations: List<LocationsItem?>? = null,
val providedLocation: ProvidedLocation? = null
)
var countryData = gson.fromJson(jsonOutput, Reponse::class.java)
It was caused due to API communication. I solved my problem by putting okHttpClient. I added the code to help anybody having the same question.
val client = OkHttpClient()
val request = Request.Builder().url(url).build()
client.newCall(request).enqueue(object :Callback{
override fun onFailure(call: Call, e: IOException) {
Log.d("fail", "fail")
}
override fun onResponse(call: Call, response: okhttp3.Response) {
var body = response.body?.string()
Log.d("body", "$body")
val jsonObject2 : JSONObject = JSONObject(body.toString())
val jsonOutput2 = gson.fromJson(body, Response::class.java)
val test2 = jsonOutput2.results?.get(0)?.locations?.get(0)?.adminArea1.toString()
Log.d("test2", test2) }}

Only getting null from API Kotlin

I'm making an android app using Kotlin where one of the features are getting a random drink from an API called The CocktailDB. But when I'm prompting the drink and its attributes it only says null. How to solve this?
My Drink class:
package com.example.drinkify.uhm
import com.google.gson.annotations.SerializedName
class Drink {
#SerializedName("idDrink")
val idDrink: String? = null
#SerializedName("strDrink")
val strDrink: String? = null
#SerializedName("strDrinkAlternate")
val strDrinkAlternate: Any? = null
#SerializedName("strDrinkES")
val strDrinkES: Any? = null
#SerializedName("strDrinkDE")
val strDrinkDE: Any? = null
#SerializedName("strDrinkFR")
val strDrinkFR: Any? = null
#SerializedName("strDrinkZH-HANS")
val strDrinkZHHANS: Any? = null
#SerializedName("strDrinkZH-HANT")
val strDrinkZHHANT: Any? = null
#SerializedName("strTags")
val strTags: String? = null
#SerializedName("strVideo")
val strVideo: Any? = null
#SerializedName("strCategory")
val strCategory: String? = null
#SerializedName("strIBA")
val strIBA: String? = null
#SerializedName("strAlcoholic")
val strAlcoholic: String? = null
#SerializedName("strGlass")
val strGlass: String? = null
#SerializedName("strInstructions")
val strInstructions: String? = null
#SerializedName("strInstructionsES")
val strInstructionsES: Any? = null
#SerializedName("strInstructionsDE")
val strInstructionsDE: Any? = null
#SerializedName("strInstructionsFR")
val strInstructionsFR: Any? = null
#SerializedName("strInstructionsZH-HANS")
val strInstructionsZHHANS: Any? = null
#SerializedName("strInstructionsZH-HANT")
val strInstructionsZHHANT: Any? = null
#SerializedName("strDrinkThumb")
val strDrinkThumb: String? = null
#SerializedName("strIngredient1")
val strIngredient1: String? = null
#SerializedName("strIngredient2")
val strIngredient2: String? = null
#SerializedName("strIngredient3")
val strIngredient3: String? = null
#SerializedName("strIngredient4")
val strIngredient4: String? = null
#SerializedName("strIngredient5")
val strIngredient5: String? = null
#SerializedName("strIngredient6")
val strIngredient6: String? = null
#SerializedName("strIngredient7")
val strIngredient7: String? = null
#SerializedName("strIngredient8")
val strIngredient8: String? = null
#SerializedName("strIngredient9")
val strIngredient9: String? = null
#SerializedName("strIngredient10")
val strIngredient10: String? = null
#SerializedName("strIngredient11")
val strIngredient11: String? = null
#SerializedName("strIngredient12")
val strIngredient12: String? = null
#SerializedName("strIngredient13")
val strIngredient13: String? = null
#SerializedName("strIngredient14")
val strIngredient14: String? = null
#SerializedName("strIngredient15")
val strIngredient15: String? = null
#SerializedName("strMeasure1")
val strMeasure1: String? = null
#SerializedName("strMeasure2")
val strMeasure2: String? = null
#SerializedName("strMeasure3")
val strMeasure3: String? = null
#SerializedName("strMeasure4")
val strMeasure4: String? = null
#SerializedName("strMeasure5")
val strMeasure5: String? = null
#SerializedName("strMeasure6")
val strMeasure6: String? = null
#SerializedName("strMeasure7")
val strMeasure7: String? = null
#SerializedName("strMeasure8")
val strMeasure8: String? = null
#SerializedName("strMeasure9")
val strMeasure9: String? = null
#SerializedName("strMeasure10")
val strMeasure10: String? = null
#SerializedName("strMeasure11")
val strMeasure11: String? = null
#SerializedName("strMeasure12")
val strMeasure12: String? = null
#SerializedName("strMeasure13")
val strMeasure13: String? = null
#SerializedName("strMeasure14")
val strMeasure14: String? = null
#SerializedName("strMeasure15")
val strMeasure15: String? = null
#SerializedName("dateModified")
val dateModified: String? = null
}
The interface:
package com.example.drinkify.ui
import com.example.drinkify.uhm.Drink
import retrofit2.Call
import retrofit2.http.GET
interface RandomDrinkAPI {
#get:GET("random.php")
val drinks: Call<Drink>
}
And lastly the activity:
package com.example.drinkify.ui
import android.annotation.SuppressLint
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.drinkify.R
import com.example.drinkify.uhm.Drink
import com.example.drinkify.uhm.Post
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class RandomizeActivity : AppCompatActivity() {
private var textViewResult: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_randomize)
textViewResult = findViewById(R.id.text_view_result)
val retrofit = Retrofit.Builder()
.baseUrl("https://www.thecocktaildb.com/api/json/v1/1/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val randomDrinkApi: RandomDrinkAPI = retrofit.create(RandomDrinkAPI::class.java)
val call = randomDrinkApi.drinks
call.enqueue(object: Callback<Drink> {
override fun onResponse(call: Call<Drink>, response: Response<Drink>) {
if (!response.isSuccessful) {
textViewResult?.setText("Code: " + response.code())
return
}
val drink = response.body()!!
var content = ""
content += """
Drink ${drink.strDrink}
""".trimIndent()
content += """
Category ${drink.strCategory}
""".trimIndent()
content += """
Alcoholic ${drink.strAlcoholic}
""".trimIndent()
content += """
Instructions ${drink.strInstructions}
""".trimIndent()
textViewResult?.append(content)
}
override fun onFailure(call: Call<Drink>, t: Throwable) {
textViewResult?.setText(t.message)
}
})
}
}
I've tried using other API's with this method and it has worked. Ive also tried changing it to a list e.g Call<List>, but then I got the error: "Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $"
This is the object returned by the api
{
"drinks": [{
"idDrink": "14860",
"strDrink": "Talos Coffee",
"strDrinkAlternate": null,
"strTags": null,
"strVideo": null,
"strCategory": "Coffee \/ Tea",
"strIBA": null,
"strAlcoholic": "Alcoholic",
"strGlass": "Brandy snifter",
"strInstructions": "Add your GM and then add your coffee.",
"strInstructionsES": null,
"strInstructionsDE": "F\u00fcge deinen GM und dann deinen Kaffee hinzu.",
"strInstructionsFR": null,
"strInstructionsIT": "Aggiungi il Grand Marnier e poi aggiungi il tuo caff\u00e8.",
"strInstructionsZH-HANS": null,
"strInstructionsZH-HANT": null,
"strDrinkThumb": "https:\/\/www.thecocktaildb.com\/images\/media\/drink\/rswqpy1441246518.jpg",
"strIngredient1": "Grand Marnier",
"strIngredient2": "Coffee",
"strIngredient3": null,
"strIngredient4": null,
"strIngredient5": null,
"strIngredient6": null,
"strIngredient7": null,
"strIngredient8": null,
"strIngredient9": null,
"strIngredient10": null,
"strIngredient11": null,
"strIngredient12": null,
"strIngredient13": null,
"strIngredient14": null,
"strIngredient15": null,
"strMeasure1": "3 parts ",
"strMeasure2": "1 part ",
"strMeasure3": null,
"strMeasure4": null,
"strMeasure5": null,
"strMeasure6": null,
"strMeasure7": null,
"strMeasure8": null,
"strMeasure9": null,
"strMeasure10": null,
"strMeasure11": null,
"strMeasure12": null,
"strMeasure13": null,
"strMeasure14": null,
"strMeasure15": null,
"strImageSource": null,
"strImageAttribution": null,
"strCreativeCommonsConfirmed": "No",
"dateModified": "2015-09-03 03:15:18"
}]
}
For gson to understand and deserialize this object, you will need to create another class.
data class DrinkHolder(
#SerializedName("drinks")
val drink: List<Drink>
)
Now you this new class to the call: Call

Moshi: Platform class java.lang.Class requires explicit JsonAdapter to be registered

I'm using a Moshi adapter to get the object from a JSON string. But, I'm getting an error,
java.lang.IllegalArgumentException: Platform class java.lang.Class requires explicit JsonAdapter to be registered
All the data members of the UserProfile class are only String type then why it is asking to create an explicit JsonAdapter?
MoshiDataConverter
class MoshiDataConverter() {
fun <T> getObjectFromJson(typeOfObject: Class<T>, jsonString: String): T? {
val moshi = Moshi.Builder().build()
val jsonAdapter: JsonAdapter<T> = moshi.adapter<T>(
typeOfObject::class.java
)
return jsonAdapter.fromJson(jsonString)!!
}
}
getObject method
fun <T> getObject(#Keys key: String?, typeOfObject: Class<T>?): T? {
val value = getString(key, null) ?: return null
return MoshiDataConverter().getObjectFromJson(typeOfObject!!, value)
}
UserProfile.kt
#Parcelize
#JsonClass(generateAdapter = true)
data class UserProfile(
#get:Json(name = "p_contact")
val pContact: String? = null,
#get:Json(name = "profile_pic")
var profilePic: String? = null,
#get:Json(name = "lname")
val lname: String? = null,
#get:Json(name = "token")
var token: String? = null,
#get:Json(name = "fname")
val fname: String? = null,
#SerializedName("_id")
#get:Json(name = "_id")
var id: String? = null,
#get:Json(name = "email")
var email: String? = null,
#SerializedName("refresh_token")
#get:Json(name = "refresh_token")
var refreshToken: String? = null
) : Parcelable
Your typeOfObject parameter is already a class reference, so you don't need to call ::class.java on it before passing it to the Moshi adapter.
Try replacing
val jsonAdapter: JsonAdapter<T> = moshi.adapter<T>(
typeOfObject::class.java
)
with
val jsonAdapter: JsonAdapter<T> = moshi.adapter<T>(typeOfObject)

Android Kotlin Retrofit Post Request Inputted data does not sent

So I have to handle a POST request with its body data taken from some input in a form.
The Endpoint of this service is https://someUrl.com/switching-product/switch?orderID=A002&procode=0200011&nip=P19120
The Response returned from Postman is like this.
The body of this request is like this :
In this case, I have this Interface for handling a POST request:
///Endpoint: https://someUrl.com/switching-product/switch?orderID=A002&procode=0200011&nip=P19120
interface editProductDetail{
#FormUrlEncoded
#POST("switch")
fun editProductDetail(#Query("orderID") orderID: String,
#Query("procode") procode: String,
#Query("nip") nip : String,
#Field("procode_new") procodeNew: String,
#Field("item_qty_new") itemQtyNew: String,
#Field("item_price_new") itemPriceNew: String,
#Field("item_name_new") itemNameNew: String,
#Field("total_price_new") totalPriceNew: String): Call<OutstandingOrderDetailPOJODataClassDetailItem>
}
This is the data class I use:
data class OutstandingOrderDetailPOJODataClassDetailItem(
#field:SerializedName("item_price_new")
val itemPriceNew: Int? = null,
#field:SerializedName("item_name_new")
val itemNameNew: String? = null,
#field:SerializedName("total_price")
val totalPrice: Int? = null,
#field:SerializedName("item_price")
val itemPrice: Int? = null,
#field:SerializedName("item_name")
val itemName: String? = null,
#field:SerializedName("status_refund")
val statusRefund: String? = null,
#field:SerializedName("detail_id")
val detailId: Int? = null,
#field:SerializedName("procode_new")
val procodeNew: String? = null,
#field:SerializedName("refund_date")
val refundDate: String? = null,
#field:SerializedName("request_refund")
val requestRefund: String? = null,
#field:SerializedName("procode")
val procode: String? = null,
#field:SerializedName("last_update")
val lastUpdate: String? = null,
#field:SerializedName("item_qty_new")
val itemQtyNew: Int? = null,
#field:SerializedName("order_id")
val orderId: String? = null,
#field:SerializedName("total_price_new")
val totalPriceNew: Int? = null,
#field:SerializedName("item_qty")
val itemQty: Int? = null,
#field:SerializedName("refund")
val refund: Int? = null
)
As you can see above, the body has attributes that are included in the data class as well. (This data class is also used in a related service in the App that uses the inputted data of this service).
And this is the function to trigger the POST request:
NetworkConfig().editOutstandingOrderProductDetailService().editProductDetail(
selectedOrderId,
selectedProcode,
selectedNip,
procodeNew,
itemNewQty,
itemPriceNew,
itemNewName,
totalPriceNew
).enqueue(object :
Callback<OutstandingOrderDetailPOJODataClassDetailItem> {
override fun onFailure(call: Call<OutstandingOrderDetailPOJODataClassDetailItem>, t: Throwable) {
Log.i("Order", "It Failed!!")
if (call.isCanceled) {
Toast.makeText((activity as AppCompatActivity), "Request Aborted", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText((activity as AppCompatActivity), t.localizedMessage, Toast.LENGTH_SHORT).show()
}
}
override fun onResponse(
call: Call<OutstandingOrderDetailPOJODataClassDetailItem>,
response: Response<OutstandingOrderDetailPOJODataClassDetailItem>
) {
Log.i("Order", "Switching Process done!!!")
Log.i("Order", "Status: ${response.body()}")
}
})
From above, it prints the response in the logCat like this:
Am I missing something here? Or there's something I need to Change? If there's any detail that I missed to point out, just let me know!
Your request is a JSON object, not a formurl.
#Field tag is used when you want to pass your parameters as formurl
Use model class or JsonObject with #Body tag to pass parameters as JsonObject.
Model class Exmaple,
data class TestClass{
val text1: String,
val text2: String
}
Now Pass this class as request
#POST("URL")
fun apiName(#Body request: TestClass);
JSON Object Exmaple,
JSONObject paramObject = new JSONObject();
paramObject.put("key1", "value1");
paramObject.put("key1", "vaalue2");
Now pass it as String or JsonObject
#POST("URL")
fun apiName(#Body request: String); // pass as String

Categories

Resources