I want to fetch data from the server using Retrofit but it shows me HTTP 500 server error I know it is due to a null value in parameters but I don't where is the null value comes from. I try my best to find the null value but can't find it. If any other reason then please tell me.
Here is my Fragment Code
#RequiresApi(Build.VERSION_CODES.M)
override fun inOnCreateView(mRootView: ViewGroup, savedInstanceState: Bundle?) {
val homeActivity = activity as HomeNavHostActivity
homeActivity.toolbar_id?.visibility = View.VISIBLE
homeActivity.toolbar_search_icon_id.visibility = View.VISIBLE
homeActivity.toolbar_add_icon_id.visibility = View.GONE
homeActivity.home_view_layout?.visibility = View.VISIBLE
homeActivity.bottom_layout?.visibility = View.VISIBLE
homeActivity.toolbar_title_tv.text = "Home"
homeActivity.toolbar_search_icon_id.setOnClickListener() {
showSearchDialog(mRootView)
}
homeActivity.cancel_text.setOnClickListener() {
homeActivity.search_layout.visibility = View.GONE
homeActivity.toolbar_title_tv.visibility = View.VISIBLE
homeActivity.search_view?.setQuery("", false)
homeActivity.search_view?.clearFocus()
}
val dialogHelper by inject<MaterialDialogHelper>()
setupProgressDialog(viewModel.showHideProgressDialog, dialogHelper)
if (isNetworkAvailable(requireContext())) {
var area:String = "20"
var zipcode:String = "WC2N5DU"
viewModel.getSkipFilterList(zipcode, area)
} else {
showAlertDialog(getString(R.string.no_internet))
}
attachViewModel()
}
Here is my ViewModel Code
var filterSkipList: MutableLiveData<SkipListResponse> = MutableLiveData()
fun getSkipFilterList(zipcode: String, area: String) {
viewModelScope.launch {
_showHideProgressDialog.value = true.wrapWithEvent()
sharedWebServices.getFilterSkip(zipcode, area).run {
onSuccess {
_showHideProgressDialog.value = false.wrapWithEvent()
if (it.code == VALID_STATUS_CODE) {
filterSkipList.value = it
}else {
showSnackbarMessage(it.message)
}
}
onFailure {
_showHideProgressDialog.value = false.wrapWithEvent()
it.message?.let { it1 -> showSnackbarMessage(it1) }
}
}
}
}
Here is my data class
#Serializable
data class SkipFilterList(
val zipcode:String,
val area:String
)
Here is my Post
#POST("search-skip")
suspend fun skipListing(
#Header("Authorization") token: String?,
#Body body: SkipFilterList): SkipListResponse
Here is My Repostry
suspend fun getFilterSkip(
zipcode: String,
area: String
) = withContext(dispatcher) {
val token = SharePrefrenceHelper.getInstance(app).getToken()
val body = SkipFilterList(zipcode, area)
safeApiCall {
Result.success(apiServices.skipListing("Bearer" + token, body))
}
}
By passing json object in the body this was solved.
val jsonObject = JsonObject()
jsonObject.addProperty("zipcode", zipcode)
jsonObject.addProperty("radius", area)
Related
Inside my Fragment File
Here I am try to call locationProvider to get the latitude and longitude. And once i get those i want to call api to get the weather data weatherApi. I cannot initialise variables inside locationProvider.lastLocation.addOnSuccessListener also i cannot call weatherApi inside the locationProvider.lastLocation.addOnSuccessListener as it suspend function. I tried many different approaches but nothing seems to work. Right now i am using global variable to store the value of lat and long by calling setLat(), setLong(), inside the locationProvider.lastLocation.addOnSuccessListener, and right now i am using the delay of 3secs so that lat and long can be initialised first and then weatherApi can be called. I want to know a better approach to do it.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
requestPermissions()
locationProvider = LocationServices.getFusedLocationProviderClient(requireContext())
val weatherApi = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(WeatherApi::class.java)
CoroutineScope(Dispatchers.Main).launch {
try {
val job1 = async {
locationProvider.lastLocation.addOnSuccessListener {
setLat(it.latitude.toString())
setLong(it.longitude.toString())
}
}
val weatherData = async {
delay(3000)
weatherApi.getCurrentLocationWeatherData(
latitude = LAT,
longitude = LONG,
key = API_KEY,
units = "metric"
)
}
log(weatherData.await())
setCurrentWeatherCardView(weatherData.await())
} catch (e: Exception) {
Log.d("Error: ", e.message.toString())
}
}
}
...
private fun setCurrentWeatherCardView(weatherData: CurrentWeatherData) {
current_locatin_title.text = weatherData.name
temp_value.text = weatherData.main.temp.toString()+"°C"
wind_value.text = weatherData.wind.speed.toString()+" km/h"
humidity_value.text = weatherData.main.humidity.toString()+"%"
Glide.with(requireContext()).load("$BASE_URL/img/w/${weatherData.weather[0].icon}.png").into(current_weather_icon)
}
private fun setLat(lat: String) {
LAT = lat
}
private fun setLong(long: String) {
LONG = long
}
WeatherApi File
interface WeatherApi {
#GET("/data/2.5/weather")
suspend fun getCurrentLocationWeatherData(
#Query("lat") latitude: String,
#Query("lon") longitude: String,
#Query("appid") key: String,
#Query("units") units: String
): CurrentWeatherData
}
Constants File
object Contants {
const val BASE_URL = "https://api.openweathermap.org/"
const val API_KEY = {{API_KEY}}
const val REQUEST_CODE_LOCATION_PERMISSIONS = 0
var LAT = "0"
var LONG = "0"
}
i am working on an online shopping application using retrofit, coroutine, livedata, mvvm,...
i want to show progress bar before fetching data from server for afew seconds
if i have one api request i can show that but in this app i have multiple request
what should i do in this situation how i should show progress bar??
Api Service
#GET("homeslider.php")
suspend fun getSliderImages(): Response<List<Model.Slider>>
#GET("amazingoffer.php")
suspend fun getAmazingProduct(): Response<List<Model.AmazingProduct>>
#GET("handsImages.php")
suspend fun getHandsFreeData(
#Query(
"handsfree_id"
) handsfree_id: Int
): Response<List<Model.HandsFreeImages>>
#GET("handsfreemoreinfo.php")
suspend fun gethandsfreemoreinfo(): Response<List<Model.HandsFreeMore>>
#GET("wristmetadata.php")
suspend fun getWristWatchMetaData(
#Query(
"wrist_id"
) wrist_id: Int
): Response<List<Model.WristWatch>>
repository
fun getSliderImages(): LiveData<List<Model.Slider>> {
val data = MutableLiveData<List<Model.Slider>>()
val job = Job()
applicationScope.launch(IO + job) {
val response = api.getSliderImages()
withContext(Main + SupervisorJob(job)) {
data.value = response.body()
}
job.complete()
job.cancel()
}
return data
}
fun getAmazingOffer(): LiveData<List<Model.AmazingProduct>> {
val data = MutableLiveData<List<Model.AmazingProduct>>()
val job = Job()
applicationScope.launch(IO + job) {
val response = api.getAmazingProduct()
withContext(Main + SupervisorJob(job)) {
data.value = response.body()
}
job.complete()
job.cancel()
}
return data
}
fun getHandsFreeData(handsree_id: Int): LiveData<List<Model.HandsFreeImages>> {
val dfData = MutableLiveData<List<Model.HandsFreeImages>>()
val job = Job()
applicationScope.launch(IO + job) {
val response = api.getHandsFreeData(handsree_id)
withContext(Main + SupervisorJob(job)) {
dfData.value = response.body()
}
job.complete()
job.cancel()
}
return dfData
}
fun getHandsFreeMore(): LiveData<List<Model.HandsFreeMore>> {
val data = MutableLiveData<List<Model.HandsFreeMore>>()
val job = Job()
applicationScope.launch(IO + job) {
val response = api.gethandsfreemoreinfo()
withContext(Main + SupervisorJob(job)) {
data.value = response.body()
}
job.complete()
job.cancel()
}
return data
}
VIEWMODEL
fun getSliderImages() = repository.getSliderImages()
fun getAmazingOffer() = repository.getAmazingOffer()
fun recieveAdvertise() = repository.recieveAdvertise()
fun dailyShoes(context: Context) = repository.getDailyShoes(context)
i will appreciate your help
I couldn't help but notice that your repository contains lots of repetitive code. first point to learn here is that all that logic in Repository, it usually goes in the ViewModel. second thing is that you are using applicationScope to launch your coroutines, which usually is done using viewModelScope(takes care of cancellation) object which is available in every viewModel.
So first we have to take care of that repetitive code and move it to ViewModel. So your viewModel would now look like
class YourViewModel: ViewModel() {
// Your other init code, repo creation etc
// Live data objects for progressBar and error, we will observe these in Fragment/Activity
val showProgress: MutableLiveData<Boolean> = MutableLiveData()
val errorMessage: MutableLiveData<String> = MutableLiveData()
/**
* A Generic api caller, which updates the given live data object with the api result
* and internally takes care of progress bar visibility. */
private fun <T> callApiAndPost(liveData: MutableLiveData<T>,
apiCall: () -> Response<T> ) = viewModelScope.launch {
try{
showProgress.postValue(true) // Show prgress bar when api call is active
if(result.code() == 200) { liveData.postValue(result.body()) }
else{ errorMessage.postValue("Network call failed, try again") }
showProgress.postValue(false)
}
catch (e: Exception){
errorMessage.postValue("Network call failed, try again")
showProgress.postValue(false)
}
}
/******** Now all your API call methods should be called as *************/
// First declare the live data object which will contain the api result
val sliderData: MutableLiveData<List<Model.Slider>> = MutableLiveData()
// Now call the API as
fun getSliderImages() = callApiAndPost(sliderData) {
repository.getSliderImages()
}
}
After that remove all the logic from Repository and make it simply call the network methods as
suspend fun getSliderImages() = api.getSliderImages() // simply delegate to network layer
And finally to display the progress bar, simply observe the showProgress LiveData object in your Activity/Fragment as
viewModel.showProgress.observer(this, Observer{
progressBar.visibility = if(it) View.VISIBLE else View.GONE
}
First create a enum class status:
enum class Status {
SUCCESS,
ERROR,
LOADING
}
Then create resource class like this:
data class Resource<out T>(val status: Status, val data: T?, val message: String?) {
companion object {
fun <T> success(data: T?): Resource<T> {
return Resource(Status.SUCCESS, data, null)
}
fun <T> error(msg: String, data: T?): Resource<T> {
return Resource(Status.ERROR, data, msg)
}
fun <T> loading(data: T?): Resource<T> {
return Resource(Status.LOADING, data, null)
}
}
}
Now add your request to a list of response:
var list = java.util.ArrayList<Response<*>>()
suspend fun getApis() = list.addAll(
listOf(
api.advertise(),
api.getAmazingProduct(),
api.dailyShoes(),
api.getSliderImages(),
.
.
.
)
)
In your viewmodel class:
private val _apis = MutableLiveData<Resource<*>>()
val apis: LiveData<Resource<*>>
get() = _apis
init {
getAllApi()
}
fun getAllApi() {
val job = Job()
viewModelScope.launch(IO + job) {
_apis.postValue(
Resource.loading(null)
)
delay(2000)
repository.getApis().let {
withContext(Main + SupervisorJob(job)) {
it.let {
if (it) {
_apis.postValue(Resource.success(it))
} else {
_apis.postValue(Resource.error("Unknown error eccured", null))
}
}
}
}
job.complete()
job.cancel()
}
}
Now you can use status to show progress like this . use this part in your target fragment:
private fun setProgress() {
viewModel.apis.observe(viewLifecycleOwner) {
when (it.status) {
Status.SUCCESS -> {
binding.apply {
progress.visibility = View.INVISIBLE
line1.visibility = View.VISIBLE
parentscroll.visibility = View.VISIBLE
}
}
Status.ERROR -> {
binding.apply {
progress.visibility = View.INVISIBLE
line1.visibility = View.INVISIBLE
parentscroll.visibility = View.INVISIBLE
}
}
Status.LOADING -> {
binding.apply {
progress.visibility = View.VISIBLE
line1.visibility = View.INVISIBLE
parentscroll.visibility = View.INVISIBLE
}
}
}
}
}
I hope you find it useful.
I am using Exoplayer to play some videos. I have some .mpd live url's which comes from a backend. Normally if the broadcast is live, the seek bar is set to right end side and on the left end side live video cache time is stated with minus value like (-00.59.51). I want to achive that in my project. But by default, current position of the video stated on left side and video duration on right side.
There is two problem:
1.We have to detect if the video is live or not.
2.We need to set time values for live video.
private fun initializePlayerXml(currentXmlLink: String) {
if (player == null) {
val trackSelector = DefaultTrackSelector(this)
trackSelector.setParameters(
trackSelector.buildUponParameters().setMaxVideoSizeSd()
)
try {
player = SimpleExoPlayer.Builder(this)
.build()
} catch (e: Exception) {
}
}
if (player!!.bufferedPosition == 0L) {
playButton.setImageResource(R.drawable.ic_pause)
}
playButton.setOnClickListener {
if (player!!.isPlaying) {
player!!.pause()
playButton.setImageResource(R.drawable.ic_play)
} else {
player!!.play()
playButton.setImageResource(R.drawable.ic_pause)
}
}
val doubleClickForwardFun = DoubleClick(object : DoubleClickListener {
override fun onSingleClickEvent(view: View?) {
}
override fun onDoubleClickEvent(view: View?) {
val currentPosition = player!!.currentPosition
player!!.seekTo(currentPosition + 10000)
}
})
val doubleClickBackwardFun = DoubleClick(object : DoubleClickListener {
override fun onSingleClickEvent(view: View?) {
}
override fun onDoubleClickEvent(view: View?) {
val currentPosition = player!!.currentPosition
player!!.seekTo(currentPosition - 10000)
}
})
doubleClickBackward.setOnClickListener(doubleClickBackwardFun)
doubleClickForward.setOnClickListener(doubleClickForwardFun)
forwardButton.setOnClickListener {
val currentPosition = player!!.currentPosition
player!!.seekTo(currentPosition + 10000)
}
backwardButton.setOnClickListener {
val currentPosition = player!!.currentPosition
player!!.seekTo(currentPosition - 10000)
}
val mediaItem =
MediaItem.Builder()
.setUri(currentXmlLink)
.setMimeType(MimeTypes.APPLICATION_MPD)
.build()
player!!.addMediaItem(mediaItem)
playerView!!.player = player
player!!.playWhenReady = playWhenReady
player!!.seekTo(currentWindow, playbackPosition)
playbackStateListener.let { player!!.addListener(it) }
player!!.prepare()
}
I have already a question on Exoplayer/Issues, you can check here. Also my repo is here.
I moved from sql db to room. I can't figure out how to check if item exist in database.
How to write this code using Room?
fun existsCheck(place: Places): Boolean {
val db= this.readableDatabase
val query = "SELECT * FROM $TABLE_PLACES WHERE $COLUMN_LAT = ${place.lat} AND $COLUMN_LNG = ${place.lng}"
val cursor = db.rawQuery(query, null)
if(cursor.count > 0){
cursor.close()
db.close()
return true
}
cursor.close()
db.close()
return false
}
I have tried to achieve this with this code, but always getting FALSE back
#Query("SELECT name FROM place WHERE lat = :lat AND lng = :lng")
fun exist(lat: Double?, lng: Double?): Flowable<String>
override fun save() {
Observable.just(dao)
.subscribeOn(Schedulers.io())
.subscribe { dao.insert(place) }
}
override fun itemExists(lat: Double?, lng: Double?): Single<Boolean> =
dao.exist(lat, lng)
.flatMapSingle { Single.just(it.isNotEmpty()) }
.onErrorReturn { false }
.first(false)
override fun delete() {
dao.deleteByLat(place.lat)
}
override fun saveClicked() {
var boolean = false
itemExists(place.lat, place.lng)
.subscribeOn(Schedulers.io())
.map { it -> boolean = it }
if (boolean){
delete()
v.setImageNotSaved()
} else {
save()
v.setImageSaved()
}
}
This works fine
override fun itemExists() {
Observable.just(dao)
.subscribeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.map { it -> it.exist(place.lat, place.lng) }
.subscribe( { it -> saveClicked(true) },
{error -> saveClicked(false)})
}
Currently, I use retrofit2 to call restful apis and get response. Because the response body can be multiple types, I wrote the code following.
//Interface
#FormUrlEncoded
#POST("payments/events/{id}")
fun postPayment(#Path("id") id: String): Call<Any>
//Api Manager
fun postPayment(id: String): Observable<Any> {
return Observable.create {
subscriber ->
val callResponse = api.postPayment(id)
val response = callResponse.execute()
if (response.isSuccessful) {
if (response.body() is MyClass1) {
// never success...
} else if (response.body() is MyClass2) {
// never success...
}
subscriber.onNext(response.body())
subscriber.onCompleted()
} else {
subscriber.onError(Throwable(response.message()))
}
}
}
So I'm not able to cast response.body() to MyClass1 or MyClass2.
response.body() as MyClass1 occurs error too.
MyClass1 and MyClass2 are normal template classes.
class MyClass1( val id: String, val data: String)
Is there any smart way to cast response body to my custom classes?
Small update for MyClass2
class MyClass2( val token: String, val url: String, val quantity: Int)
As mentioned by #Miha_x64, Retrofit doesn't know about your classes (MyClass1 and MyClass2) because your Call uses the Any type. Therefore, Retrofit is not creating an instance of MyClass1 or MyClass2, instead it is just creating an instance of the Any class.
The simplest solution would just be to combine the two classes:
data class MyClass(
val id: String?,
val data: String?,
val token: String?,
val url: String?,
val quantity: Int
)
Then you can specify the response type in your interface:
#FormUrlEncoded
#POST("payments/events/{id}")
fun postPayment(#Path("id") id: String): Call<MyClass>
In the case your response does not have an id or data element, they will just be null. Then you can check which type of response was received simply by checking which values are null:
if (response.body().id != null) {
// Handle type 1 response...
} else if (response.body().token != null) {
// Handle type 2 response...
}
A slightly more complex solution would be to write a wrapper for your two classes, and a type adapter to populate the wrapper. This would avoid the nullability of each of the fields, as well as keep your data structure separated.
This would differ based on the ConverterFactory you are using but if, for example, you are using Gson, it would look something like this:
data class ApiResponse(
val val1: MyClass1? = null,
val val2: MyClass2? = null
)
class ApiResponseAdapter : TypeAdapter<ApiResponse> {
#Throws(IOException::class)
override fun write(out: JsonWriter, value: ApiResponse?) {
if (value != null) {
out.beginObject()
value.val1?.id? let { out.name("id").value(it) }
value.val1?.data? let { out.name("data").value(it) }
value.val2?.token? let { out.name("token").value(it) }
value.val2?.url? let { out.name("url").value(it) }
value.val2?.quantity? let { out.name("quantity").value(it) }
out.endObject()
} else {
out.nullValue()
}
}
#Throws(IOException::class)
override fun read(in: JsonReader): ApiResponse {
reader.beginObject()
var id: String? = null
var data: String? = null
var token: String? = null
var url: String? = null
var quantity: Int = 0
while(in.hasNext()) {
val name = in.nextName()
if (name.equals("id", true)) {
id = in.nextString()
} else if (name.equals("data", true)) {
data = in.nextString()
} else if (name.equals("token", true)) {
token = in.nextString()
} else if (name.equals("url", true)) {
url = in.nextString()
} else if (name.equals("quantity", true)) {
quantity = in.nextInt()
}
}
reader.endObject()
if (id != null && data != null) {
return ApiResponse(MyClass1(id, data), null)
} else if (token != null && url != null) {
return ApiResponse(null, MyClass2(token, url, quantity))
} else {
return ApiResponse()
}
}
}
Then you can add this type adapter to your Gson instance:
val gson = GsonBuilder().registerTypeAdapter(ApiResponse::class.java, ApiResponseAdapter()).create()
Then replace the Call<Any> type with Call<ApiRepsone> and you can then check which response was received by checking which value is null:
if (response.body().val1 != null) {
// Handle MyClass1 response...
} else if (response.body().val2 != null) {
// Handle MyClass2 response...
}
First of all, thanks #Bryan for answer. Your answer was perfect but finally I did something tricky way.
...
if (response.isSuccessful) {
val jsonObject = JSONObject(response.body() as Map<*, *>)
val jsonString = jsonObject.toString()
if (jsonObject.has("id")) {
val myclass1Object = Gson().fromJson(jsonString, MyClass1::class.java)
...
} else {
val myclass2Object = Gson().fromJson(jsonString, MyClass2::class.java)
...
}
}
...