How to create constructor for data class in Kotlin Android? - android

How to create constructor for data class in Kotlin Android ?
data class EventItem(
#SerializedName("dateEvent")
val dateEvent: String,
#SerializedName("dateEventLocal")
val dateEventLocal: Any,
#SerializedName("idAwayTeam")
val idAwayTeam: String,
#SerializedName("idEvent")
val idEvent: String,
#SerializedName("idHomeTeam")
val idHomeTeam: String,
#SerializedName("idLeague")
val idLeague: String,
#SerializedName("idSoccerXML")
val idSoccerXML: String,
#SerializedName("intAwayScore")
val intAwayScore: Any,
#SerializedName("intAwayShots")
val intAwayShots: Any,
#SerializedName("intHomeScore")
val intHomeScore: Any,
#SerializedName("intHomeShots")
val intHomeShots: Any,
#SerializedName("intRound")
val intRound: String,
#SerializedName("intSpectators")
val intSpectators: Any,
#SerializedName("strAwayFormation")
val strAwayFormation: Any,
#SerializedName("strAwayGoalDetails")
val strAwayGoalDetails: String,
#SerializedName("strAwayLineupDefense")
val strAwayLineupDefense: String,
#SerializedName("strAwayLineupForward")
val strAwayLineupForward: String,
#SerializedName("strAwayLineupGoalkeeper")
val strAwayLineupGoalkeeper: String,
#SerializedName("strAwayLineupMidfield")
val strAwayLineupMidfield: String,
#SerializedName("strAwayLineupSubstitutes")
val strAwayLineupSubstitutes: String,
#SerializedName("strAwayRedCards")
val strAwayRedCards: String,
#SerializedName("strAwayTeam")
val strAwayTeam: String,
#SerializedName("strAwayYellowCards")
val strAwayYellowCards: String,
#SerializedName("strBanner")
val strBanner: Any,
#SerializedName("strCircuit")
val strCircuit: Any,
#SerializedName("strCity")
val strCity: Any,
#SerializedName("strCountry")
val strCountry: Any,
#SerializedName("strDate")
val strDate: String,
#SerializedName("strDescriptionEN")
val strDescriptionEN: Any,
#SerializedName("strEvent")
val strEvent: String,
#SerializedName("strEventAlternate")
val strEventAlternate: String,
#SerializedName("strFanart")
val strFanart: Any,
#SerializedName("strFilename")
val strFilename: String,
#SerializedName("strHomeFormation")
val strHomeFormation: Any,
#SerializedName("strHomeGoalDetails")
val strHomeGoalDetails: String,
#SerializedName("strHomeLineupDefense")
val strHomeLineupDefense: String,
#SerializedName("strHomeLineupForward")
val strHomeLineupForward: String,
#SerializedName("strHomeLineupGoalkeeper")
val strHomeLineupGoalkeeper: String,
#SerializedName("strHomeLineupMidfield")
val strHomeLineupMidfield: String,
#SerializedName("strHomeLineupSubstitutes")
val strHomeLineupSubstitutes: String,
#SerializedName("strHomeRedCards")
val strHomeRedCards: String,
#SerializedName("strHomeTeam")
val strHomeTeam: String,
#SerializedName("strHomeYellowCards")
val strHomeYellowCards: String,
#SerializedName("strLeague")
val strLeague: String,
#SerializedName("strLocked")
val strLocked: String,
#SerializedName("strMap")
val strMap: Any,
#SerializedName("strPoster")
val strPoster: Any,
#SerializedName("strResult")
val strResult: Any,
#SerializedName("strSeason")
val strSeason: String,
#SerializedName("strSport")
val strSport: String,
#SerializedName("strTVStation")
val strTVStation: Any,
#SerializedName("strThumb")
val strThumb: Any,
#SerializedName("strTime")
val strTime: String,
#SerializedName("strTimeLocal")
val strTimeLocal: String,
#SerializedName("strTweet1")
val strTweet1: Any,
#SerializedName("strTweet2")
val strTweet2: Any,
#SerializedName("strTweet3")
val strTweet3: Any,
#SerializedName("strVideo")
val strVideo: Any
) {
constructor(
idEvent: String,
strEvent: String,
strDate: String,
idHomeTeam: String,
strHomeTeam: String,
intHomeScore: Any,
idAwayTeam: String,
strAwayTeam: String,
intAwayScore: Any
) : this(idEvent, strEvent, strDate, idHomeTeam, strHomeTeam, intHomeScore, idAwayTeam, strAwayTeam, intAwayScore)
}
screenshot : https://i.stack.imgur.com/riGkU.png
How to create constructor for data class in Kotlin Android ?
i've try to create constructor. But, i get "There's a cycle in the delegation calls chain"
please, correct my code and tell me solution for it. . .

For a data class, the constructor defined in the class header is the primary constructor. It can't delegate to any other constructor in that class (though it can delegate to a superclass constructor).
However, you can define secondary constructors in the body of the class, as long as those delegate to the primary constructor. For example:
data class EventItem(val dateEvent: String) {
constructor(date: Date) : this(date.toString())
}
The problem in the code you've posted is that your secondary constructor is trying to delegate back to itself. You have to delegate to the primary constructor instead, and that means you need to be able to determine a value for all of the parameters missing from the secondary constructor.

Related

how to get data from rest api using retrofit kotlin android

I am trying to get data from rest api using retrofit on Android app.
I am trying to reach the data structured below;
sections -> items -> venue -> id (Unique id of the venue)
sections -> items -> venue -> name (Name of the venue)
sections -> items -> venue -> short_description (Description of the venue)
I can reach to the sections but not the data under the section.
data class VenueModel(
val created: Created,
val expires_in_seconds: Int,
val filtering: Filtering,
val name: String,
val page_title: String,
val sections: List<Section>,
val show_large_title: Boolean,
val show_map: Boolean,
val sorting: SortingX,
val track_id: String
)
data class Section(
val items: List<Item>,
val link: LinkX,
val name: String,
val template: String,
val title: String
)
data class Item(
val description: String,
val filtering: FilteringX,
val image: Image,
val link: Link,
val overlay: String,
val quantity: Int,
val quantity_str: String,
val sorting: Sorting,
val template: String,
val title: String,
val track_id: String,
val venue: Venue
)
data class Venue(
val address: String,
val badges: List<Badge>,
val categories: List<Any>,
val city: String,
val country: String,
val currency: String,
val delivers: Boolean,
val delivery_price: String,
val delivery_price_highlight: Boolean,
val delivery_price_int: Int,
val estimate: Int,
val estimate_range: String,
val franchise: String,
val id: String,
val location: List<Double>,
val name: String,
val online: Boolean,
val price_range: Int,
val product_line: String,
val promotions: List<Any>,
val rating: Rating,
val short_description: String,
val show_wolt_plus: Boolean,
val slug: String,
val tags: List<String>
)
this is api service interface;
interface APIService {
#GET("v1/pages/restaurants?lat=60.170187&lon=24.930599")
fun getVenues(#Query("lat") locationLatitude: String, #Query("lon") locationLongitude: String) : Call<VenueModel>
}
And this is main activity;
class MainActivity : AppCompatActivity() {
var locationLatitude = "60.170187"
var locationLongitude = "24.930599"
lateinit var venueSearchListSection: List<Section>
lateinit var venueSearchListItem: List<Item>
lateinit var venueSearchListVenue: List<Venue>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
venueSearchListSection = ArrayList<Section>()
venueSearchListItem = ArrayList()
venueSearchListVenue = ArrayList()
fetchDataFromApi()
}
private fun fetchDataFromApi(){
//venue results from api
val retrofitVenueSearch = Retrofit.Builder()
.baseUrl("https://restaurant-api.wolt.com/")
.addConverterFactory(GsonConverterFactory.create()).build()
val apiVenueSearch = retrofitVenueSearch.create(APIService::class.java)
apiVenueSearch.getVenues(locationLatitude, locationLongitude).enqueue(object :
Callback<VenueModel> {
override fun onResponse(
call: Call<VenueModel>,
response: Response<VenueModel>
) {
venueSearchListSection = response.body()?.sections ?: venueSearchListSection
//I have the problem here. I can get the data in venueSearchListSection
//arraylist but I can not reach the data inside it.
}
override fun onFailure(call: Call<VenueModel>, t: Throwable) {
t.message?.let { Log.e("venue", it) }
}
})
}
}
Thanks for your helps in advance.

Can't parse json correctly

need help in parsing this json file from this endpoint
http://ergast.com/api/f1/constructors
this is my data class
data class Teams(
val MRData: MRdata
){
data class MRdata(
val ConstructorTable: ConstructorsTable,
val limit: String,
val offset: String,
val series: String,
val total: String,
val url: String,
val xmlns: String
){
data class ConstructorsTable(
val Constructors: List<Constructor>?
) {
data class Constructor(
val constructorId: String?,
val name: String?,
val nationality: String?,
val url: String?
)
}
}
}
when i use Teams class as a return model it logs actual data but, when i try to return specific data like constructorID or nationality it returns null.

Kotlin android development diffutil itemCallback type error

Im trying to implement diffutil in my adapter and im getting the following error:
One type argument expected for class Result<out T>
This is the code where i get the error:
private val diffCallback = object: DiffUtil.ItemCallback<Result>() {
}
This is my Result class:
data class Result(
val adult: Boolean,
val backdrop_path: String,
val genre_ids: List<Int>,
val id: Int,
val media_type: String,
val original_language: String,
val original_title: String,
val overview: String,
val popularity: Double,
val poster_path: String,
val release_date: String,
val title: String,
val video: Boolean,
val vote_average: Double,
val vote_count: Int
)
I don't understand,this is exactly how i do this every time,and it works without problems
Kotlin already has a Result<T> type, and it's imported by default. You might need to fully qualify your own class name if you want to make sure you're using that one. Or maybe just rename your class, it will make things easier.

Parameter specified as non-null is null error in Room Database

Here is my entity class:
#Entity
data class User(
#PrimaryKey
#Json(name = "id") val userId: String,
#Json(name = "login") val userName: String,
#Json(name = "avatar_url") val userAvatar: String,
val profile: Profile? = null
) : Serializable
Here is my Profile data class
data class Profile(
val avatar_url: String,
val bio: String,
val blog: String,
val company: Any,
val created_at: String,
val email: Any,
val events_url: String,
val followers: Int,
val followers_url: String,
val following: Int,
val following_url: String,
val gists_url: String,
val gravatar_id: String,
val hireable: Boolean,
val html_url: String,
val id: Int,
val location: String,
val login: String,
val name: String,
val node_id: String,
val organizations_url: String,
val public_gists: Int,
val public_repos: Int,
val received_events_url: String,
val repos_url: String,
val site_admin: Boolean,
val starred_url: String,
val subscriptions_url: String,
val twitter_username: Any,
val type: String,
val updated_at: String,
val url: String
) : Serializable
but every time I try to insert data into the table I am getting the error, how can I insert null data object in table while using room database?
The issue here is that Room doesn't know how to insert attribute of type Profile to the table.
The simple solution would be to use a type converter. Something like the following:
class DatabaseConverters {
#TypeConverter
fun toProfile(profileJson: String): Profile? {
return <Create a Profile object out of a JSON string>
}
#TypeConverter
fun fromProfile(profile: Profile?): String {
return <JSON string representation of Profile object>
}
}
In your case - you can use "" (empty string) when Profile is null.
More info about converters: Here

Moshi - convert string to object

I can't figure out how to do this in kotlin. I want to convert this string, to an object array:
[
{mode=bus, line=381, line_name=381, direction=Waterloo, operator=CX, date=2019-10-16, expected_departure_date=2019-10-16, aimed_departure_time=20:11, expected_departure_time=20:13, best_departure_estimate=20:13, source=Countdown instant, dir=outbound, operator_name=ABELLIO LONDON LIMITED, id=https://transportapi.com/v3/uk/bus/route/CX/381/outbound/490010596E/2019-10-16/20:11/timetable.json?app_id=f56baf6a&app_key=6b0d065a1465ccbb6f32438f3d960803},
{mode=bus, line=381, line_name=381, direction=Waterloo, operator=CX, date=2019-10-16, expected_departure_date=2019-10-16, aimed_departure_time=20:33, expected_departure_time=20:34, best_departure_estimate=20:34, source=Countdown instant, dir=outbound, operator_name=ABELLIO LONDON LIMITED, id=https://transportapi.com/v3/uk/bus/route/CX/381/outbound/490010596E/2019-10-16/20:33/timetable.json?app_id=f56baf6a&app_key=6b0d065a1465ccbb6f32438f3d960803}
]
The object I want to convert it too:
#JsonClass(generateAdapter = true)
data class BusLive(val aimed_departure_time: String, val best_departure_estimate: String, val date: String, val dir: String,
val direction: String,
val expected_departure_date: String,
val expected_departure_time: String,
val id: String,
val line: String,
val line_name: String,
val mode: String,
val operator: String,
val operator_name: String,
val source: String
)
I've tried:
fun moshiConverter(test:String) : String {
val moshi = Moshi.Builder().build()
val type = Types.newParameterizedType(LiveBus::class.java, LiveBus::class.java)
val adapter:JsonAdapter<String> = moshi.adapter(type)
val a = adapter.toJson(test)
return a
}
And no joy :(
I hope what you posted as JSON as just an example. Because it is not valid JSON string.
To fix your example you have to change couple of lines:
val type = Types.newParameterizedType(LiveBus::class.java, LiveBus::class.java)
val adapter:JsonAdapter<String> = moshi.adapter(type)
to
val type = Types.newParameterizedType(List::class.java, LiveBus::class.java)
val adapter = moshi.adapter(type)

Categories

Resources