Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException trying to access a String resource

I have the following /res/values/uris.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="bladder">blahblah</string>
</resources>

I am accessing it in code:

private String bladderUrl= getString(R.string.bladder);

But it is returning null. I'm not sure why?

like image 373
Sheehan Alam Avatar asked Nov 11 '10 17:11

Sheehan Alam


2 Answers

My guess you placed bladderUrl smth like this:

public class YourActivity extends Activity {
    private String bladderUrl = getString(R.string.bladder);

    @Override
    public void onCreate(Bundle savedInstanceState) {

...

However you need to do smth like this:

public class YourActivity extends Activity {
    private String bladderUrl;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        bladderUrl = getString(R.string.bladder);
...
like image 91
Vit Khudenko Avatar answered Oct 13 '22 20:10

Vit Khudenko


First of all to clear that up. You don't have to have all your strings in strings.xml. Period.

Emmanuels answer is partially right. You have to get the string inside your onCreate() method when the context is initialized. His answer is only partially correct since he also mentioned that you have to have the strings inside the strings.xml which is not true.

like image 24
Octavian A. Damiean Avatar answered Oct 13 '22 21:10

Octavian A. Damiean