Localizing strings in strings.xml gives NullPointerException

↘锁芯ラ 提交于 2019-12-25 01:55:56

问题


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?


回答1:


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)



回答2:


You have this code

Context c;

public void onCreate(Bundle savedInstanceState) {
    ...
    loading.setText(c.getResources().setString(R.string.loading));  //This way gives NPE

The member c is never set before it is used. This is the reason for the NullPointerException. You must first initialize c with View.getContext() for example.

Localization is handled automatically according to the device's capabilities and settings.

In your layout definition, you can define the text string with a reference to a string id and Android will automatically load the appropriate resource

In res/layout/splashscreen.xml:

...
<TextView android:id="@+id/loading"
    android:text="@string/loading"
    .../>
...

So there is no need to explicitly set the text string in your code, because Android will do so already. The only thing you have to do, is to define the appropriate text strings in the res/values*/strings.xml files.



来源:https://stackoverflow.com/questions/16362524/localizing-strings-in-strings-xml-gives-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!