Home > Back-end >  Get a string from Rescources in Adapter
Get a string from Rescources in Adapter

Time:03-24

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?

CodePudding user response:

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)
}
  • Related