Search code examples
javaandroidnullpointerexceptionlocalizable.stringsgetresource

Localizing strings in strings.xml gives NullPointerException


My work computer that Eclipse is installed on does not have internet connectivity due to work related issues so all code and LogCat text has been hand typed instead of copy and pasted since I am on a separate laptop that Eclipse is installed right now. So bear with me for any typos.

Now to the issue. In the new version of my app, I am making it Spanish supported. I localized all my strings in strings.xml. Below is my Java code that I am not usuing to implement.

public class SplashScreen extends SwarmActivity {

  Context c;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);

    loading = (TextView)findViewById(R.id.loading);
    //loading.setText(c.getResources().setString(R.string.loading));  //This way gives NPE
    //loading.setText(R.string.loading);  //This way works
    //loading.setText("Test");  //This way works
  }
}

If I understand localization correctly, I have to getResources() first so the app knows what language of the string to display. But the getResources() is what is messing me up.

What do I need to do to get the string displaying correctly?


Solution

  • To answer your problem, your forgot to initialize your Context object. So c is null. Replace loading.setText(c.getResources().setString(R.string.loading)); by

    loading.setText(getResources().setString(R.string.loading));

    But actually there is no need to do that.

    Android loads the appropriate resources according to the locale settings of the device at run time.

    You just have to respect this hierarchy in your project :

    res/
           values/
               strings.xml
           values-es / (here for spanish values)
               strings.xml
           values-fr /
               strings.xml (here for french values)