Retrofit pass String to url - android

How can I pass the variable day by pressing a button to the apiInterface class?
The fragment FragJornadas, from where I want to pass the variable to #Get in Interface?
class FragJornadas : Fragment() {
var jornada = "1"
var dataList = ArrayList<TodasModel>()
lateinit var recyclerView: RecyclerView
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.jornadas_list, container, false)
val miTexto: TextView = view.findViewById(R.id.tv_Jornadas)
miTexto.text = (getString(R.string.num_jornada))
val numJor = intArrayOf(R.id.tv_01, R.id.tv_02, R.id.tv_03, R.id.tv_04, R.id.tv_05,
R.id.tv_06, R.id.tv_07, R.id.tv_08, R.id.tv_09, R.id.tv_10, R.id.tv_11, R.id.tv_12,
R.id.tv_13, R.id.tv_14, R.id.tv_15, R.id.tv_16, R.id.tv_17, R.id.tv_18, R.id.tv_19,
R.id.tv_20, R.id.tv_21, R.id.tv_22, R.id.tv_23, R.id.tv_24, R.id.tv_25, R.id.tv_26,
R.id.tv_27, R.id.tv_28, R.id.tv_29, R.id.tv_30)
val button = arrayOfNulls<Button>(numJor.size)
for(i in numJor.indices){
button[i] = view.findViewById(numJor[i]) as Button
val buttonValue = i+1
val buttonText = Integer.toString(buttonValue)
button[i]!!.setOnClickListener {
miTexto.text = getString(R.string.num_jornada) + " " + buttonText
jornada = buttonText
getData(jornada)
}
}
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val progressBar: ProgressBar = this.progressBar1
recyclerView = view.findViewById(R.id.recycler_view)
recyclerView.adapter= TodasAdapter(dataList,activity!!)
recyclerView.layoutManager=LinearLayoutManager(activity!!,LinearLayoutManager.VERTICAL,false)
Thread(Runnable {
activity!!.runOnUiThread {
progressBar.visibility = View.VISIBLE
}
try {
var i = 0
while(i < Int.MAX_VALUE){
i++
}
} catch (e: InterruptedException) {
e.printStackTrace()
}
activity!!.runOnUiThread {
progressBar.visibility = View.GONE
}
}).start()
getData(jornada)
}
private fun getData(jornada: String) {
val call: Call<List<TodasModel>> = ApiFederacion.getClient.getTodasJuvenil(jornada)
call.enqueue(object : Callback<List<TodasModel>> {
override fun onResponse(call: Call<List<TodasModel>>?, response: Response<List<TodasModel>>?) {
dataList.addAll(response!!.body()!!)
recyclerView.adapter!!.notifyDataSetChanged()
}
override fun onFailure(call: Call<List<TodasModel>>?, t: Throwable?) {
//progerssProgressDialog.dismiss()
}
})
}
TodasAdapter
class TodasAdapter(private var actList: List<TodasModel>, private val context: Context) : RecyclerView.Adapter<TodasAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(context).inflate(R.layout.actual_row, parent, false))
}
override fun getItemCount(): Int {
return actList.size
}
#SuppressLint("SetTextI18n", "SimpleDateFormat")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val dataModel= actList.get(position)
holder.itemView.setOnClickListener(){
Toast.makeText(context, dataModel.nomLocal, Toast.LENGTH_LONG).show()
}
val parser = SimpleDateFormat("dd/MM/yyyy") //Formato de fecha obtenida
val formatter = SimpleDateFormat("EE dd 'de' MMMM 'del 'yyyy \n" + "' a las '") //Formato a mostrar
val output = formatter.format(parser.parse(dataModel.fecha + "/2019"))
holder.tv_Fecha.text = output + dataModel.hora
//holder.tv_Fecha.text = dataModel.fecha + "\n" + dataModel.hora
holder.tv_NomLocal.text = dataModel.nomLocal
holder.tv_ResultadoL.text = dataModel.resulLocal
holder.tv_Estado.text = " - " + dataModel.estadoPartido + " - "
holder.tv_ResultadoV.text = dataModel.resulVisitante
holder.tv_NomVisitante.text = dataModel.nomVisitante
Picasso.get()
.load("https://ffcv.es/ncompeticiones/" + dataModel.escudoLocal)
.fit()
//.resize(150, 150)
.into(holder.imageEscLocal)
Picasso.get()
.load("https://ffcv.es/ncompeticiones/" + dataModel.escudoVisitante)
.fit()
.into(holder.imageEscVisi)
}
class ViewHolder(itemLayoutView: View) : RecyclerView.ViewHolder(itemLayoutView) {
var tv_Fecha:TextView
var tv_NomLocal:TextView
var tv_ResultadoL:TextView
var tv_Estado:TextView
var tv_ResultadoV:TextView
var tv_NomVisitante:TextView
var imageEscLocal: ImageView
var imageEscVisi: ImageView
init {
tv_Fecha = itemLayoutView.findViewById(R.id.tv_Fecha)
tv_NomLocal = itemLayoutView.findViewById(R.id.tv_Equipo_Local)
tv_ResultadoL = itemLayoutView.findViewById(R.id.tv_Result_Local)
tv_Estado = itemLayoutView.findViewById(R.id.tv_Estado)
tv_ResultadoV = itemLayoutView.findViewById(R.id.tv_Result_Visitante)
tv_NomVisitante = itemLayoutView.findViewById(R.id.tv_Equipo_Visitante)
imageEscLocal = itemLayoutView.findViewById(R.id.iv_Local) as ImageView
imageEscVisi = itemLayoutView.findViewById(R.id.iv_Visi) as ImageView
}
}
}
And the ApiInterface class to receive it. Being the url I want to get is:
#GET("server.php?action=getResultados&cmp=328{jor}tmp=2018/2019") fun
getTodasJuvenil(
#Path("jor") jornada: String ): Call<List<TodasModel>>
The url I want to get is:
"server.php?action=getResultados&cmp=328&jor=1&tmp=2018/2019"
this is the error:
java.lang.IllegalArgumentException: URL query string
"action=getResultados&cmp=328{jor}&tmp=2018/2019" must not have
replace block. For dynamic query parameters
at com.myapplication.Jornadas.FragJornadas.getData(FragJornadas.kt:91)
at
com.myapplication.Jornadas.FragJornadas.onViewCreated(FragJornadas.kt:87)

Using #Path you're telling retrofit to replace that variable in the path of the url, but you want in the query string. The path is the bit after the domain and before the query string - in your case would be server.php and maybe some bits that come before, which I can't say without seeing the full url.
To add a parameter to the query string you want to use #Query and you don't want to specify it in the query string in the #GET annotation. So you could change things to:
#GET("server.php?action=getResultados&cmp=328&tmp=2018/2019") fun
getTodasJuvenil(
#Query("jor") jornada: String ): Call<List<TodasModel>>)
You've removed {jor} from the query string and replaced #Path with #Query.
Now, retrofit should add a query parameter with the desired jornada.

#Fred thanks for your answers, my mistake was not the previous one, I was not deleting the list, it was added at the end, the solution is:
dataList.clear()
override fun onResponse(call: Call<List<TodasModel>>?, response: Response<List<TodasModel>>?) {
dataList.clear()
dataList.addAll(response!!.body()!!)
recyclerView.adapter!!.notifyDataSetChanged()
}

Related

Data Binding not working for textView while using some function

First I have declared the variables in the layout file
<data>
<variable
name="signUpViewModel"
type="ac.connect.ui.signup.SignUpViewModel" />
</data>
Now I'm trying to use a function of StringExtension class which takes string value as parameter and to set the result to textView
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="20dp"
android:textStyle="bold"
android:background="#C1BDBD"
android:textColor="#3D3C3C"
app:capitalizeFirstLetter="#{signUpViewModel.name}" />
capitalize First Letter function
fun capitalizeFirstLetter(value: String): String {
var ans = ""
val words = value.split(" ")
words.forEach {
ans += it.capitalize() + " "
}
return ans
}
ViewModel
class SignUpViewModel(private val setProfileUseCase: SetProfileUseCase) :
ViewModel() {
private val _profile = MutableLiveData<ProfileModel>()
val profile: LiveData<ProfileModel>
get() = _profile
private val _name = MutableLiveData<String>()
val name: LiveData<String>
get() = _name
fun setName(name: Editable) {
_name.value = name.toString()
}
fun setProfileData() {
viewModelScope.launch {
val profile = ProfileModel(
name = "kamal nayan",
branch = "CSE",
gender = "Male",
mobileNumber = "+91-73555555517",
rollNo = "GCS/345353",
uid = "ghafagaraggGGG"
)
val response = setProfileUseCase.invoke(profile)
_profile.value = profile
response.successOrError(::handleProductDetailsSuccess, ::handleSignUpFailure)
}
}
private fun handleProductDetailsSuccess(response: Boolean) {
_name.value = "User Data Uploaded Successfully"
}
private fun handleSignUpFailure(failure: Failure, error: ErrorResponse?) {
Timber.log(Log.ERROR, error?.message)
}
}
Fragment Code:
class SignUpFragment : Fragment(R.layout.fragment_sign_up) {
private val viewModel: SignUpViewModel by viewModel()
private var binding by autoCleared<FragmentSignUpBinding>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentSignUpBinding.bind(view)
binding.signUpViewModel = viewModel
binding.lifecycleOwner = this
binding.signUp.setOnClickListener {
viewModel.setProfileData()
}
}
companion object {
fun newInstance(): SignUpFragment {
return SignUpFragment()
}
}
}
The output is blank , like no text in the textView
Kindly help me with this, Thanks in advance.
I think the problem is you are not setting the value of the variable stringExtensions when setting up your DataBinding
import ac.connect.utils.StringExtensions
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentSignUpBinding.bind(view)
binding.signUpViewModel = viewModel
// binding.stringExtensions = StringExtensions() // If it is a class
// binding.stringExtensions = StringExtensions // If it is an object
binding.lifecycleOwner = this
binding.signUp.setOnClickListener {
viewModel.setProfileData()
}
}
If I understand right you need make BindingAdapter. So you need rewrite your 'capitalizeFirstLetter' function as below.
#BindingAdapter("app:capitalizeFirstLetter")
#JvmStatic fun capitalizeFirstLetter(textView: TextView, value: String){
var ans = ""
val words = value.split(" ")
words.forEach {
ans += it.capitalize() + " "
}
textView.setText(ans)
}
Also I didn't see where you call setName function. Are you sure that _name.value is not empty?

RecyclerView make endless scrolling with JSON

I'm trying to make my Android App (I'm only experienced in iOS).
I created a RecyclerView that gets the data from a web. I tried everything to implement endless scrolling to load more items, but when I call the function to get the items, the entire RecyclerView loads again and no attach the new results on the bottom.
This is my code:
ConversationUser.kt
data class ConversationUser(
val message_nickname: String,
val message_image_thumb: String,
val message_large_thumb: String,
val message_modified: String,
val message_status: String,
val message_unread: Int,
val conv_id: String,
val message_dest: String) {
}
ConversacionesActivity.kt
class ConversacionesActivity : AppCompatActivity() {
// MARK: Variables
var user_token = ""
var user_id = ""
override fun onCreate(savedInstanceState: Bundle?) {
// User Defaults
val sharedPreferences = getSharedPreferences("Preferences", Context.MODE_PRIVATE)
user_token = sharedPreferences.getString("user_token", "")!!
user_id = sharedPreferences.getString("user_id", "")!!
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_conversaciones)
recyclerConv.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL))
getConversationsData()
recyclerConv.setLoadingListener(object : LoadingListener {
override fun onRefresh() {
//refresh data here
}
override fun onLoadMore() {
// load more data here
getConversationsData()
}
})
}
fun getConversationsData() {
val httpAsync = "https://mywebsite.com/conversations/${user_token}"
.httpPost()
.responseString { request, response, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
val data = result.get()
runOnUiThread {
val conversaciones = processJson(data)
show(conversaciones)
return#runOnUiThread
}
}
}
}
httpAsync.join()
}
fun processJson(json: String): List<ConversationUser> {
val gson: Gson = GsonBuilder().create()
val conversaciones: List<ConversationUser> = gson.fromJson(
json,
Array<ConversationUser>::class.java
).toList()
return conversaciones
}
fun show(conversaciones: List<ConversationUser>) {
recyclerConv.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerConv.adapter = AdaptadorConv(conversaciones, this, user_token, user_id)
}
AdaptadorConv.kt
class AdaptadorConv(
val conversaciones: List<ConversationUser> = ArrayList(),
val context: Context,
val user_token: String,
val user_id: String) : RecyclerView.Adapter<AdaptadorConv.ConvViewHolder>() {
override fun onBindViewHolder(holder: ConvViewHolder, position: Int) {
holder.convName.text = conversaciones[position].message_nickname
holder.convTime.text = conversaciones[position].message_modified
}
override fun getItemCount(): Int {
return conversaciones.size - 1
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConvViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(
R.layout.conversaciones,
parent,
false
)
return ConvViewHolder(view)
}
class ConvViewHolder(vista: View): RecyclerView.ViewHolder(vista) {
val convImg: ImageView = itemView.findViewById(R.id.convImg)
val convStatus: ImageView = itemView.findViewById(R.id.convStatus)
val convName: TextView = itemView.findViewById(R.id.convName)
val convUnread: TextView = itemView.findViewById(R.id.convUnread)
val convTime: TextView = itemView.findViewById(R.id.convTime)
}
Thanks for any help or hint.
Please check your show () method, you are creating new Adapter every time with the new dataset. You have to append the new items to the adapter's list and adapter should be set to list once. Helpful tutorial can be found at here.

Is there a way to pass multiple arguments to a recyclerview adapter in kotlin?

I have 1 fragment , with a tab layout and 3 tabs
I am sending a bundle over to the fragment once each tab is clicked, and want to use the same recyclerview to display the data once tab is clicked.
Are 3 of my api calls (top stories, most popular, sports) are different, is there a way to have 3 arguments inside of my adapter and have the adapter only use one argument at a time?
Here's my adapter:
class NewsAdapter(private val news: List<News>) : RecyclerView.Adapter<NewsAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.news_row,parent, false)
return ViewHolder(view)
}
override fun getItemCount() = news.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val newsData = news[position]
holder.section.text = newsData.section.capitalize() + " > " + newsData.subsection.capitalize()
if (holder.section.text.contains('U')) {
holder.section.text = "U.S." + " > " + newsData.subsection.capitalize()
}
if (holder.section.text.startsWith('N')) {
holder.section.text = "N.Y. Region" + " > " + newsData.subsection.capitalize()
}
holder.title.text = newsData.title
holder.publishedDate.text = newsData.publishedDate.subSequence(5,7).toString() + "/" +
newsData.publishedDate.subSequence(8,10).toString() + "/" +
newsData.publishedDate.subSequence(0,4).toString()
// "https://static01.nyt.com/"
Picasso.with(holder.photo.context)
.load(newsData.multimedia.toString().substringAfter("url=").substringBefore(","))
.placeholder(R.drawable.worldnewsicon)
.error(R.drawable.worldnewsicon)
.into(holder.photo)
Log.d("amer", "MULTIMEDIA$$$: ${newsData.multimedia.toString().substringAfter("url=").substringBefore(",")}")
holder.itemView.setOnClickListener {
val url: String = newsData.url.toString()
val intent = Intent(holder.itemView.context, SecondActivity::class.java)
intent.putExtra("url", url)
holder.itemView.context.startActivity(intent)
}
}
class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val section: TextView = itemView.section
val publishedDate: TextView = itemView.publishedDate
val title: TextView = itemView.title
val photo: ImageView = itemView.photo
}
}
Can I do something like class NewsAdapter(private val news: News, private val mostPopular: PopularNews, private val sports: Sports)
?????
How should I go about this, what is the simplest way?
You don't need to pass all the three lists, if those lists are presented in the same way you can create an Interface to them something like this:
interface News {
fun getTitle(): String
fun getBody(): String
fun getImageUrl(): String
}
class Sports() : News {
override fun getTitle() = "Brasil 1, Germany 7"
override fun getBody() = "OMG"
override fun getImageUrl() = "http://bla.com/news.png"
}
So the adapter have a list of News:
class NewsAdapter() : RecyclerView.Adapter<NewsAdapter.ViewHolder>(){
var news by Delegates.observable(listOf<News>()) { _,_,_ -> notifyDataSetChanged()}
}
And on your activity you will change the list after receiving the list, here I'm using LiveData, but anything should do:
class NewsActivity : AppCompatActivity() {
private val newsLiveData = MutableLiveData<List<News>>
private val newsProvider = NewsProvider()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
newsLiveData.observe(this, Observer {
adapter.news = it
})
}
fun onSportsClick() {
newsLiveData.value = newsProvider.getSportsNews()
}
fun onMostPopularClick() {
newsLiveData.value = newsProvider.getMostPopularNews()
}
}

Getting Null exception in Toast inside fragment

Here's the code where i am getting exception, tried various ways to implement context but nothing is working out.
class GrowthStoryFragment : Fragment() {
private val TAG = "GrowthStoryFragment"
companion object{
private var countryID = "1"
private var date = "MAT TY"
private var spec = "val"
private var businessUnitID = "2"
private var category = "Fresh Milk"
private var firstReportTypeId = "1" //fixed for growth story and share story
private var isGroup = "false" //fixed to false
}
private val backendApi = WinRetrofitHelper.winApiInstance()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_growth_story, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getSpinnerResponse(businessUnitID, isGroup,firstReportTypeId)
getSuperRegionName(countryID, date,spec," ",businessUnitID, category, firstReportTypeId, isGroup)
growth_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val item = parent?.getItemAtPosition(position) as RespTwo
category = item.nameValue
Log.e(TAG,"Category name is: " + category)
getSuperRegionName(countryID, date,spec," ",businessUnitID, category, firstReportTypeId, isGroup)
}
}
}
private fun getSpinnerResponse(businessUnitID: String, isGroup: String, firstReportTypeId: String){
val request = backendApi.getCategoryBusinessUnit(businessUnitID, isGroup, firstReportTypeId)
request.enqueue(object : Callback<List<RespTwo>> {
override fun onFailure(call: Call<List<RespTwo>>?, t: Throwable?) {
Log.e(TAG, "Failure Super Region Name: ")
}
override fun onResponse(call: Call<List<RespTwo>>?, response: Response<List<RespTwo>>?) {
val myresponse = response?.body()
if (response?.body() != null && !response?.body()!!.isEmpty()) {
growth_spinner.adapter = GrowthSpinnerAdapter(response?.body())
Log.e(TAG, "Super Region Name: " + myresponse?.get(0)?.nameValue)
} else {
Toast.makeText(context!!.applicationContext, "Data Not Available!", Toast.LENGTH_LONG).show()
}
}
})
}
private fun getSuperRegionName(countryID: String, date: String, spec: String, superMarket: String,businessUnitID: String, category: String, firstReportTypeId: String, isGroup: String) {
val request = backendApi.getSuperRegion(countryID)
request.enqueue(object : Callback<List<RespMy>> {
override fun onFailure(call: Call<List<RespMy>>?, t: Throwable?) {
Log.e(TAG, "Failure Super Region Name: ")
}
override fun onResponse(call: Call<List<RespMy>>?, response: Response<List<RespMy>>?) {
val myresponse = response?.body()
if (response?.body() != null && !response?.body()!!.isEmpty()) {
getDataFromApi(countryID, date, spec, myresponse?.get(0)!!.nameValue, businessUnitID, category, firstReportTypeId, isGroup)
Log.e(TAG, "Super Region Name: " +countryID+" "+ date+" "+ spec+" "+ myresponse?.get(0)?.nameValue+" "+businessUnitID+" "+ category+" "+ firstReportTypeId+" " + isGroup+" ")
} else {
Toast.makeText(myApplicationContext, "Data Not Available!", Toast.LENGTH_LONG).show()
}
}
})
}
}
Please suggest something and i have heard a viewModel conversion of the requests made directly from fragments can fix this out but i don't know how to do that. Please help in either way.
Update:
Don't want to use static context here
ViewModel and Repository pattern is way to go.
You are doing async network call on Main thread, very bad idea.
For learning purposes - here is how to get your code working:
replace:
myApplicationContext = context!!.applicationContext
with:
myApplicationContext = requireContext()
or better - get rid of this variable entirely and just use requireContext() instead.
Toasts are usually applied to the activity rather than an generic context, and demanding the context via context!! should be avoided; it is optional for a reason. I would try the following after defining #string/data_not_available and #string/super_region_name_template in the string resource xml:
val body = response?.body()
if (body?.isNotEmpty() == true) {
growth_spinner.adapter = GrowthSpinnerAdapter(body)
Log.e(TAG, getString(R.string.super_region_name_template, body.get(0).nameValue)) // if applicable, use .first() over .get(0)
} else {
activity?.run {
Toast.makeText(this, getString(R.string.data_not_available), Toast.LENGTH_LONG).show()
}
}
try to use this
myApplicationContext: Context = this.context ?: return
then
Toast.makeText(myApplicationContext, "Data Not Available!",Toast.LENGTH_LONG).show()
for more details, you can see this link

How to get icons from OpenWeatherMap onto Screen

So I am using the OpenWeatherMap Api to create a sun spotter app, so the issue I have right now is that, I have all the icons in my drawable folder, the issue is I want to display all the icons right now I have ti set up like this:
I am using that hard coded icon as a placeholder but I want all the other icons to show, my issue is how do I do that, the image from the api is given in string format and i don't know how I would get them from by drawable folder
Code
// Array Adapter
class ForecastAdapter(val forecast: Forecast) : RecyclerView.Adapter<ForecastData>(){
override fun getItemCount(): Int {
return forecast.list.count()
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ForecastData {
val layoutInflator = LayoutInflater.from(p0?.context)
val cellForRow = layoutInflator.inflate(R.layout.weather_row, p0, false)
return ForecastData(cellForRow)
}
override fun onBindViewHolder(p0: ForecastData, p1: Int) {
val getWeather = forecast.list[p1]
val clouds = getWeather.weather[0]
val getDateTime = forecast.list[p1]
val getIcon = forecast.list[p1]
// val icon = getIcon.weather[0]
p0.view.textView_text_clouds.text = clouds.main
p0.view.textView_date_time.text = getDateTime.dt_txt
// p0.view.imageView_icon = icon.icon
}
}
class ForecastData(val view: View): RecyclerView.ViewHolder(view){
}
// MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
searchButton.setOnClickListener {
getRequest()
}
view.layoutManager = LinearLayoutManager(this)
// val drawableId: Int = getResources().getIdentifier("drawable", "drawable", getPackageName())
}
private fun getRequest() {
val input = searchBar.getText().toString()
val url = "http://api.openweathermap.org/data/2.5/forecast?zip=" + input + "&units=imperial&APPID=" + getString(R.string.OPEN_WEATHER_MAP_API_KEY)
val request = okhttp3.Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback {
override fun onResponse(call: Call, response: okhttp3.Response) {
val body = response?.body()?.string()
println(body)
val gson = GsonBuilder().create()
val weather = gson.fromJson(body, Forecast::class.java)
runOnUiThread {
view.adapter = ForecastAdapter(weather)
}
}
override fun onFailure(call: Call, e: IOException) {
println("Failed to execute")
}
})
}
}
Use When
when("forecast.list[p1]") {
"icon01d.png" -> p0.view.imageView_icon.setDrawable(R.drawable.icon01d.png)
"icon02n.png" -> p0.view.imageView_icon.setDrawable(R.drawable.icon02n.png)
else -> // Your place holder icon for imageview
}

Categories

Resources