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?
To answer your problem, your forgot to initialize your
Context object
. Soc
is null. Replaceloading.setText(c.getResources().setString(R.string.loading));
byloading.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 :
You have this code
The member
c
is never set before it is used. This is the reason for theNullPointerException
. You must first initializec
withView.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
: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.