1

I am trying to extract a string resource out of my activity but get the following error -

error

I don't remmber in the past that there was anything that I should have filled before the dot of the "getString" method for extracting a string out of an activity. What am I missing?

2
  • String from another activity or string from the string resource file? Commented Aug 27, 2019 at 19:01
  • from the resource file Commented Aug 27, 2019 at 19:08

3 Answers 3

2

You can use:

String myValue = getResources().getString(R.string.mystring);

but getResources() is a method of the Context class.

It means that you can't do this:

private static String BASE_URL = getResources().getString(R.string.myurl); //it DOESN'T work!!

You can use your BuildConfig class to set these kind of values.
Also in your build.gradle file you can config them:

buildTypes {
    release {
      //..
      buildConfigField("String", "BASE_URL", "....")
    }
    //....
}

It will populate BuildConfig.BASE_URL.

Sign up to request clarification or add additional context in comments.

2 Comments

I have tried your solution and here is my line of code - ' public String BASE_URL = getResources().getString(R.string.hero_apps_api); ' but still getting a NPE. What am I missing? I am declaring the variable before onCreate, if it matters.
alright, answered to myself. I need to put it inside the lifecycle. Thanks! works.
1

If you want to use another constant declared in another activity make sure that is declared public and import it.

If you wand to use a string declared in the string resource file:

    getResources().getString(R.string.mystring);

2 Comments

your solution gives the following error - 'NPE - Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference'
If you are getting it from the resource file you don't need to assign it to a constant. Retrieve it when you need it.
0

Try to call getResources() like this:

Java

String yourString = getResources().getString(R.string.herro_app_aoi);

kotlin

val yourString = resources.getString(R.string.herro_app_aoi)

5 Comments

your solution gives the following error - 'NPE - Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference'
I was sure that you are using activity. Are you using a fragment ? if so check this thread
I am using a string from the resouce file and when trying your method I got the NPE I posted to your comment
I am using an activity
My code works fine for me, have you checked What is a NullPointerException, and how do I fix it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.