Get a string from Rescources in Adapter
Asked Answered
L

1

5

Trying to get a string value from R.string to display here in my adapter but only getting an integer in return:

class AlarmListAdapter() :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {

class MyViewHolder(binding: LayoutAlarmBinding) : RecyclerView.ViewHolder(binding.root)

var alarmList = ArrayList<Alarm>()


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
    val binding = LayoutAlarmBinding.inflate(LayoutInflater.from(parent.context))
    return MyViewHolder(binding)
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    val currentItem = alarmList[position]
    val recurring = currentItem.repeat


    //set repeat text
    holder.itemView.findViewById<TextView>(R.id.tv_repeat_days).text =
        if (recurring) {
            "${R.string.daily_alarm.}"
        } else {
            "${R.string.once_alarm}"
        }

I have also tried setting the values like this:

val once : String? =  Resources.getSystem().getString(R.string.once_alarm) ?: "Once"

but in this case get:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pleavinseven.alarmclockproject, PID: 16832
android.content.res.Resources$NotFoundException: String resource ID #0x7f1200d0

Is there a way around this, or do I need to move this function out of the adapter somehow?

Levator answered 23/3, 2022 at 1:1 Comment(0)
O
13

Get context from a View and call getString:

holder.itemView.context.getString(R.string.here)

In your case your code will look like this:

//set repeat text
holder.itemView.findViewById<TextView>(R.id.tv_repeat_days).text =
     if (recurring) 
         holder.itemView.context.getString(R.string.daily_alarm)
     else 
         holder.itemView.context.getString(R.string.once_alarm)

Another solution is to pass Context as an argument to AlarmListAdapter:

class AlarmListAdapter(val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
....
//set repeat text
holder.itemView.findViewById<TextView>(R.id.tv_repeat_days).text =
     if (recurring) 
         context.getString(R.string.daily_alarm)
     else 
         context.getString(R.string.once_alarm)
}
Oval answered 23/3, 2022 at 1:8 Comment(2)
No need to wrap the returned strings in ”${}”.Redhot
This if not working when string receives argumentsFrowsy

© 2022 - 2024 — McMap. All rights reserved.