parsed gson returns null in kotlin - android

I'm new to programming,
i'm trying to get sunrise/sunset time out of yahoo weather api and toast it on Ui
(i'm using gson and anko library )
and this is my mainactivity code :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fetchJson()
}
fun fetchJson(){
val url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call?, e: IOException?) {
toast("Failed to execute request")
}
override fun onResponse(call: Call?, response: Response?) {
val body = response?.body()?.string()
println(body)
val gson = GsonBuilder().create()
val Info = gson.fromJson(body, astronomy::class.java)
runOnUiThread {
// info.sunrise is returning null ???????
toast("this is running from UiThread ${Info.sunrise}")
}
}
})
}
}
class astronomy(val sunrise: String, val sunset: String)
where should i fix?
Thanks

The response you get back from that Yahoo! API is much larger than just the astronomy section. You've got two options (one real option and one temporary one to check things):
Create a number of models to parse the entire stack (meaning you'd have a Query class with properties like count, created, lang, and results). This would be the better approach since you'll be dealing with real classes each step of the way.
data class Query(val count: Int?, val created: String?, val lang: String?, val results: Results?)
data class Results(val channel: Channel?)
//Channel should include more fields for the rest of the data
data class Channel(val astronomy: Astronomy?)
data class Astronomy(val sunrise: String?, val sunset: String?)
Throw the entire string into a generic JsonObject (which is GSON's provided class) and traverse through that object (query -> results -> channel -> astronomy -> sunrise and sunset). This isn't the proper approach but can work to make sure your data is coming in correctly:
val jsonObj: JsonObject = JsonParser().parse(body).asJsonObject
val astronomy = jsonObj
.getAsJsonObject("query")
.getAsJsonObject("results")
.getAsJsonObject("channel")
.getAsJsonObject("astronomy")
runOnUiThread {
toast("this is running from UiThread ${astronomy.get("sunrise").asString}")
}

Hey ebrahim khoshnood!
Welcome to StackOverflow. The problem seems to be, that you haven't created POJOs (classes) for the parent objects of astronomy. If you would like to parse everything only with Gson, you will have to create objects for "query", "results", "channel" and then inside of the channel you can have the astronomy object.
So for example you could have something like this.
class Query(val results: List<Channel>?)
class Channel(val astronomy: astronomy?) // astronomy? is the class you have posted.
and then you could parse everything like this
val query = gson.fromJson(body, astronomy::class.java)
val astronomy = query.results?.astronomy

Related

How to print on the screen having an API request?

I have been several tutorials to create an API request and printing on the screen, and all the tutorials I did have some deprecated function that now I can't use.
What I have? I have the API request as you can see in the code, but now I need to print on the screen. And I don't know how to do it
PS: I use okhttp and the gson library
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fetchJson()
}
fun fetchJson() {
val url = "https://api.letsbuildthatapp.com/youtube/home_feed"
var request = Request.Builder().url(url).build()
var client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call, response: Response) {
val body = response.body()?.string()
val gson = GsonBuilder().create()
val homeFeed = gson.fromJson(body, HomeFeed::class.java)
println(homeFeed.videos)
}
override fun onFailure(call: Call, e: IOException) {
println("Failed on execute")
}
})
}
}
class HomeFeed(val videos: List<Video>)
class Video(val id: Int, val name:String, val link: String, val imageUrl: String, numberOfViews: String, val channel: Channel)
class Channel(val name: String, val profileImageUrl: String)
To simply print your debug logs to the Logcat just use:
Log.d("TAG", "videos: ${homeFeed.videos}")
Note: to print your list of videos in a human readable way you must make your Video and Channel classes as data classes (this automatically overrides their toString() functions):
data class Video(val id: Int, val name:String, val link: String, val imageUrl: String, numberOfViews: String, val channel: Channel)
data class Channel(val name: String, val profileImageUrl: String)
Also, as a long term solution, there is a better way to do HTTP logging (for debugging purposes) when using okhttp and it relies on using HttpLoggingInterceptor.
So, to print all your HTTP requests and responses with error codes, simply add a httpLoggingInterceptor to your client like this:
val httpLoggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
val client: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build()
You can read more about OkHttp interceptors here.
print()/println() isn't working in Android.
You have two options:
Add TextView to your activity and show text there
textView.text = homeFeed.videos
or
textView.text = "Failed on execute"
Use logcat, Log.d() or similar method from Log class.

Sorting data from json in Kotlin

I have data from json file which I display in recyclerview in my app. I'm trying to sort this data by year. That's how my code looks:
In MainActivity.kt everythings happend in fetchJson() function
private fun fetchJson(jsonUrl: String) {
Log.d(TAG, "Attempting to fetch json")
val request = okhttp3.Request.Builder().url(jsonUrl).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onFailure(call: Call, e: IOException) {
Log.d(TAG, "Failed to execute request")
}
override fun onResponse(call: Call, response: Response) {
val body = response.body()?.string()
Log.d(TAG, "$body")
val gson = GsonBuilder().create()
val homeFeed = gson.fromJson(body, HomeFeed::class.java)
homeFeed.standups.sortedWith(compareBy({it.year}))
runOnUiThread {
rv.adapter = Adapter(homeFeed)
}
}
})
}
fun <T> compareBy(vararg selectors: (T) -> Comparable<*>?): Comparator<T> {
return Comparator<T> { a, b -> compareValuesBy(a, b, *selectors) }
}
class HomeFeed is here:
class HomeFeed(val standups: List<StandUps>)
and data class StandUps:
data class StandUps(
val artist: String,
val title: String,
val year: String,
val poster: String,
val description: String,
val netflix_link: String,
val imdb_rate: String,
val imdb_link: String,
val duration_min: String
)
It doesn't shows any errors or warnings, it just doesn't do anything. How could I achieve this?
You have to first store the sorted list in another variable and then use that variable to pass it to your adapter
val homeFeed = gson.fromJson(body, HomeFeed::class.java)
val sortedHomeFeed = homeFeed.standups.sortedWith(compareBy({it.year}))
runOnUiThread {
rv.adapter = Adapter(sortedHomeFeed)
}
The reason for this is, changes are not made to the original list following the concepts of immutability.
Kotlin gives you easy sorting. Jus like below
make a temp object (i.e)., tempFilterData here
val standUps = tempFilterData?.sortedWith(compareBy({ it.Year }))
Now you can get the sorted data based on YEAR
If you want to sort your list ascending by a year you can do this:
val sortedStandUps = homeFeed.standups.sortedBy { it.year }
If you want to sort list descending do this:
val sortedStandUps = homeFeed.standups.sortedByDescending { it.year }

Kotlin API call using Retrofit

I'm new to Kotlin, Android and OOP in general (Natural-ADABAS background, never did Java, C++, etc) so I'm pretty desperate.
I have an API whose data looks like this, an array of book details:
API data sample
I'm confused about data models. I know it's supposed to look like how the data in the API and return an array but how exactly do I code it in Kotlin? And then how do I parse it? I've read some tutorials but they all differ. Some use an object, and some use a class.
I'm also probably breaking some standard by putting everything in the main activity but I haven't gotten to that part yet.
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
class MainActivity : AppCompatActivity()
{
private val api: RestAPI = RestAPI()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val apiGetBooks = api.getBooksList("token123123123")
val response = apiGetBooks.execute()
if (response.isSuccessful) {
val books = response.body()?.title
println(books)
} else {
println("error on API") // What do I do?
}
}
object Model {
val ResultArray : MutableList<BookProperties>? = null
}
data class BookProperties (val id: Int,val title: String, val coverURI: String, val pageURI: String, val pageCount: Int, val languageId: Int,val description: String, val isFree: Boolean) {
}
private val buriApi: MainActivity.BooksAPI? = null
class RestAPI {
private val buriApi: BooksAPI
init {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.someurl.com")
.addConverterFactory(MoshiConverterFactory.create())
.build()
buriApi = retrofit.create(BooksAPI::class.java)
}
fun getBooksList(token: String): Call<BookProperties>{
return buriApi.getBooks(token)
}
}
fun getBooksList(token: String): Call<MainActivity.BookProperties> {
return buriApi!!.getBooks(token)
}
interface BooksAPI {
#GET("/v1/books")
fun getBooks (#Query("token")token: String) : Call<BookProperties>
}
}
After much googling, I finally solved my problem thanks to How to Quickly Fetch Parse JSON with OkHttp and Gson on YouTube.
fun fetchBooks () {
println("fetching books")
val url = "https://api.someurl.com/v1/books?"
val request = Request.Builder().url(url).build()
println(request)
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call?, response: Response?) {
val body = response?.body()?.string()
println(body)
}
override fun onFailure(call: Call?, e: IOException?) {
println("Failed to execute request")
e?.printStackTrace()
}
})
}
Still need to format the data and figure out how to turn on wifi in my Android emulator but at least I can consume the JSON.
Let's start with a sample and I guess you can map it accordingly to your requirement.
I don't have your JSON as text so I am giving an example of mine.
sample JSON response
{
"status": true,
"message": "User created Successfully.",
"response": {
"user": {
"id": 12,
"email": "testmail#gmailtest.com"
},
"token": "eyJlbWFpbCI6ImVzaGFudHNhaHUxMTBAZ21hc2kyMmwuY29tIiwidXNlcklkIjoxNSwiaWF0IjoxNTIxNTYyNjkxfQ"
}
}
so create a new class and name it something like this
CreateResponse.kt
and just map those objects and arrays from json to data classes and list here.
data class CreateUserResponse(override val status: Boolean? = null,
override val message: String? = null,
val response: Response? = null)
data class Response(val user: User?, val token: String)
data class User(val id: Int, val email: String)
easy right, now with Kotlin you can declare your data classes without creating separate files each time for each object just create one file and declare all of them at once.
I'm attaching some of the resources here which may help you understand the things better.
https://antonioleiva.com/retrofit-android-kotlin/
https://segunfamisa.com/posts/using-retrofit-on-android-with-kotlin

Kotlin JSON Data not arranging into arraylist properly with Retrofit

I'm working on a kotlin android app with Retrofit. I'm making an API call to IEX stock data using this link:
https://api.iextrading.com/1.0/stock/market/batch?symbols=aapl,fb,ge&types=quote
The JSON data doesn't seem to arrange itself into an arraylist naturally. When I plug the data into jsonschema2pojo, it tells me that I should create class names for each of the stocks like this:
public class GE {
#SerializedName("quote")
#Expose
public Quote__ quote;
}
Naturally, I want the stock names to be variable so I can plug any list into there. Is there something wrong with the JSON data, or am I missing a step??
My Methods in case you wanted to see them (They're generic):
private fun getStock(stock: String) {
Timber.d("Start Retrofit Get Stocks")
val service = initiateRetrofit()
val call = service.queryStock("GE")
Timber.d("Url: " + call.request().url())
call.enqueue(object : retrofit2.Callback<StockModel> {
override fun onResponse(call: Call<StockModel>, response: retrofit2.Response<StockModel>) {
Timber.d("Successful Query. Message: " + response.message())
val stocklist : StockModel = response.body()
Timber.d("See what you get in the stock model")
}
override fun onFailure(call: Call<StockModel>, t: Throwable) {
Timber.d("Failed Call: " + t)
}
})
}
private fun initiateRetrofit(): RetrofitService {
val gson = GsonBuilder().setLenient().create()
val retrofit = Retrofit.Builder().baseUrl(RetrofitService.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson)).build()
return retrofit.create(RetrofitService::class.java)
}
There's a really clean and simple way of solving for this problem.
To get at the "quote" JSON object, you'll want to create a custom JSON deserializer. The JsonDeserializer is an interface that you implement from the Gson library.
First, we need our response object to use for deserialization.
// PortfolioResponse.kt
class PortfolioResponse {
var quotes: List<Quote>? = null
}
Next, we'll setup our ApiService class to make a call for a PortfolioResponse object.
// ApiService.kt
interface ApiService {
#GET("stock/market/batch")
abstract fun queryStockList(#Query("symbols") stocks: String, #Query("types") types: String): Call<PortfolioResponse>
}
Then, setup the deserializer. This is where we'll strip the unnecessary JSON object keys, and get the "quote" JSON objects we're looking for.
// PortfolioDeserializer.kt
class PortfolioDeserializer : JsonDeserializer<PortfolioResponse> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): PortfolioResponse {
val portfolioResponse = PortfolioResponse()
json?.let {
val jsonObject = it.asJsonObject
val symbolSet = jsonObject.entrySet()
val quoteElements = ArrayList<JsonObject>()
val quotes = ArrayList<Quote>()
val gson = Gson()
// this will give us a list of JSON elements that look like ""Quote": {}"
symbolSet.mapTo(quoteElements) { it.value.asJsonObject }
// this will take each quote JSON element, and only grab the JSON that resembles a Quote
// object, and add it to our list of Quotes
quoteElements.mapTo(quotes) { gson.fromJson(it.entrySet().first().value, Quote::class.java) }
portfolioResponse.quotes = quotes
}
return portfolioResponse
}
}
Finally, update your existing network call in your Activity, and it's done.
// MainActivity.kt
call.enqueue(object : retrofit2.Callback<PortfolioResponse> {
override fun onResponse(call: Call<PortfolioResponse>, response: retrofit2.Response<PortfolioResponse>) {
Timber.d("Successful Market Batch Query. Response.body=${response.body()}")
}
override fun onFailure(call: Call<PortfolioResponse>, t: Throwable) {
Timber.d("Failed Call: " + t)
}
})
The data is in a Map, not an array. Looks like the automated converter is trying to make it an object with field names. Try making your return value in your retrofit interface Call<Map<String, Quote__>>.
You will need to update the rest of your code to pull the key and values out of the map for processing.

Kotlin/Android app using Retrofit2. JSON query not working as I expect

Working on a small android app to help me learn about JSON queries. The little test app works until I try to drill a little deeper in to my test JSON data.
I'll post a link to the JSON data I'm working with to save space here in the question. It is example code pulled from weatherwunderground's API and hosted on myjson.com.
JSON: https://api.myjson.com/bins/19uurt
MAIN ACTIVITY CODE
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val retriever = CycloneRetriever()
val callback = object : Callback<Cyclones> {
override fun onResponse(call: Call<Cyclones>?, response: Response<Cyclones>?) {
println("Got a response!")
println(response?.body()?.currenthurricane?.get(1)?.stormInfo?.get(0)?.stormName).toString()
}
override fun onFailure(call: Call<Cyclones>?, t: Throwable?) {
println("The thing, it failed!")
}
}
retriever.getCyclones(callback)
}
}
This is my class that helps build/gather the JSON data
CLASS
interface WeatherWunderGroundAPI {
#GET("bins/19uurt")
weatherwunderground.com API
fun getCyclones() : Call<Cyclones>
}
class Cyclones(val currenthurricane: List<CurrentHurricane>)
class CurrentHurricane(val stormInfo: List<StormInfo>)
class StormInfo(val stormName: String)
class CycloneRetriever {
val apiRetriever: WeatherWunderGroundAPI
init {
val retrofitCyclone =
Retrofit.Builder().baseUrl("https://api.myjson.com/")
.addConverterFactory(GsonConverterFactory.create()).build()
apiRetriever =retrofitCyclone.create(WeatherWunderGroundAPI::class.java)
}
fun getCyclones(callback: Callback<Cyclones>) {
val call = apiRetriever.getCyclones()
call.enqueue(callback)
}
}
Right now I'm just trying to get a good response and print that to the console. Eventually, I will take the JSON data and dump it into a RecyclerView.
I can get a good response if I do the following Println, but it does not return anything of use:
println(response?.body()?.currenthurricane
But once I try to dig further into .currenthurricane, onFailure() is called.
According to some JSON docs, this should get me what I want: $.currenthurricane.[stormInfo].stormName As an example.
But I cannot figure out how to get this working in my code. I was gonna give Klaxxon a try, but have not quite figured out how to get that working either.
I'm using Retrofit2 and GSON plugins in the code above. I'm fairly confident the issue is my JSON query.
Finally figured out the problem. I was on the right track, but needed a little tweaking on my JSON queries and need to change my classes.
I'm still working on it, and I'm sure there is a much better way to do this, but here is the quick and dirty.
Changed my classes and added a couple data classes:
class Cyclones(val currenthurricane: List<CurrentHurricane>)
class CurrentHurricane(val stormInfo: StormInfo, val Current: Current)
data class StormInfo(val stormName: String)
data class Current(val lat: Double, val lon: Double, val
SaffirSimpsonCategory: Int, val Category: String, val WindSpeed: WindSpeed,
val Movement: Movement)
data class WindSpeed(val Kts: Int, val Mph: Int, val Kph: Int)
data class Movement(val kts: Int, val mph: Int, val kph: Int)
And changed my JSON queries to the following:
val cycloneInfo =
response?.body()?.currenthurricane?.get(0)?.stormInfo?.stormName
val cycloneCurrentLat =
response?.body()?.currenthurricane?.get(0)?.Current?.lat
val cycloneCurrentLon =
response?.body()?.currenthurricane?.get(0)?.Current?.lon
val cycloneCurrentSSCat =
response?.body()?.currenthurricane?.get(0)?.Current?.SaffirSimpsonCategory
val cycloneCurrentCategory =
response?.body()?.currenthurricane?.get(0)?.Current?.Category
val cycloneCurrentWindKts =
response?.body()?.currenthurricane?.get(0)?.Current?.WindSpeed?.Kts
val cycloneCurrentMovement =
response?.body()?.currenthurricane?.get(0)?.Current?.Movement?.kts

Categories

Resources