# How to get a value from resource file in the main Activity class when using fragments?

**URL:** <https://discuss.kotlinlang.org/t/how-to-get-a-value-from-resource-file-in-the-main-activity-class-when-using-fragments/26502>\
**Category:** Android\
**Created:** [March 9, 2023, 11:50am UTC](https://discuss.kotlinlang.org/t/how-to-get-a-value-from-resource-file-in-the-main-activity-class-when-using-fragments/26502 "2023-03-09T11:50:57Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![eng.nataliamolinero](https://avatars.discourse-cdn.com/v4/letter/e/e5b9ba/32.png) [@eng.nataliamolinero](https://discuss.kotlinlang.org/u/eng.nataliamolinero)\
**Post date:** [March 9, 2023, 11:50am UTC](https://discuss.kotlinlang.org/t/how-to-get-a-value-from-resource-file-in-the-main-activity-class-when-using-fragments/26502/1 "2023-03-09T11:50:57Z")

</div>

I’m developing an app with fragments and I want to use a value from “strings.xml” in MainActivity.kt. These are the names of the tabs. But, if I do this:

```auto

private var title: String = getText(R.string.title).toString()

```

I get this error when I run the code:

> java.lang.NullPointerException: Attempt to invoke virtual method ‘android.content.res.Resources android.content.Context.getResources()’ on a null object reference

If I do:

```auto
private var title = getText(R.string.title)

```

I also get the error and if I do:

```auto
private var title = R.string.title

```

I get an integer. How can I get the atual text I have in `<string name="title">Start</string>`?

---

<div class="post-metadata">

**Author:** ![MikibeMiki](https://avatars.discourse-cdn.com/v4/letter/m/74df32/32.png) [@MikibeMiki](https://discuss.kotlinlang.org/u/MikibeMiki)\
**Post date:** [March 9, 2023, 1:04pm UTC](https://discuss.kotlinlang.org/t/how-to-get-a-value-from-resource-file-in-the-main-activity-class-when-using-fragments/26502/2 "2023-03-09T13:04:28Z")

</div>

Hi, this is an Android related question.  
Problem is you are calling `getText()` that needs to have `Context` which is not available until after the fragment is attached.  
So what you can do is call `getText()` at some other lifecycle time (for example `onViewCreated`) and the it will work.

---

<div class="post-metadata">

**Author:** ![al3c](https://avatars.discourse-cdn.com/v4/letter/a/e47774/32.png) [@al3c](https://discuss.kotlinlang.org/u/al3c)\
**Post date:** [March 9, 2023, 3:39pm UTC](https://discuss.kotlinlang.org/t/how-to-get-a-value-from-resource-file-in-the-main-activity-class-when-using-fragments/26502/3 "2023-03-09T15:39:36Z")

</div>

Another option is to use. `lazy` to compute it on first access
