在strings.xml中本地化字符串给出NullPointerException异常 [英] Localizing strings in strings.xml gives NullPointerException

查看:213
本文介绍了在strings.xml中本地化字符串给出NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Eclipse的安装在我的工作电脑没有因工作有关问题的互联网连接,使所有code和LogCat中的文字已经手工输入,而不是复制和粘贴,因为我所安装Eclipse的一个单独的笔记本电脑马上。所以我承担任何拼写错误。

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.

现在的问题。在我的应用程序的新版本,我使其成为西班牙的支持。我本地化我在的strings.xml 所有字符串。下面是我的Java code,我不usuing实现。

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
  }
}

如果我理解定位正确的,我一定要getResources()首先让应用程序知道该字符串显示的语言。但getResources()是什么弄乱我。

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?

推荐答案

要回答你的问题,你忘了初始化上下文对象。因此, C 为空。更换
loading.setText(c.getResources()了setString(R.string.loading));
通过

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的根据在运行时设备的区域设置加载相应的资源。

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)

这篇关于在strings.xml中本地化字符串给出NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆