grgvn
grgvn

Reputation: 1329

Strange NullPointerException

I have strange problem...

My file strings.xml contains:

<?xml version="1.0" encoding="utf-8?>
<resources>
    <string name="building_name">My House</string>
</resources>

Well, my R contains:

[...]
public static final class String {
    public static final int building_name=0x7f02383;
}
[...]

So, when I try to call this String in my code like this:

private final String BUILDING_NAME = getString(R.string.building_name);

I have this error:

java.lang.RuntimeException: Unable to instanciate activity ComponentInfo{...}:          java.lang.NullPointerException
{...}
  caused by: java.lang.NullPointerException

at {the line where I instanciate the building_name}

What's wrong with my code?Please help

Upvotes: 2

Views: 3362

Answers (4)

Vaibhav Pallod
Vaibhav Pallod

Reputation: 534

if you have error in getting some text from one activity to another activity Like for example

StudentID = getIntent().getExtras().getString("Value");

getString giving null pointer exception then

that StudentID is of String type so just declare StudentID as

private String StudentID;

Upvotes: 0

inazaruk
inazaruk

Reputation: 74790

You can't call getString before your Activity has been initialized. That's because getString is the same as context.getResources().getString(). And context is not initialized.

So basically, you can not assign value to static variables in this way.

But there is a way to use resource strings in your static variables. For this create your application (see this and this) and then retrieve context from there. Here is a short example:

<manifest ...>
    ...
    <application  android:name="com.mypackage.MyApplication" ... >
       ...
    </application>
    ...
</manifest>

Then create MyApplication.java file:

public class MyApplication extends Application 
{   
    private static MyApplication s_instance;

    public MyApplication ()
    {
        s_instance = this;
    }

    public static Context getContext()
    {
        return s_instance;
    }

    public static String getString(int resId)
    {
        return getContext().getString(resId);       
    }
}

And then use it to get string resource:

private final String BUILDING_NAME = MyApplication.getString(R.string.building_name);

You can even do this fir static fields.

Upvotes: 10

Paresh Mayani
Paresh Mayani

Reputation: 128458

There are some cases where this happens, for the same you should try some steps mentioned below:

  1. Try to clean your project.
  2. Check whether the android.R class file is imported or not, if it is imported then remove it and import your R class file.
  3. Try using getResources().getString(R.string.myString) method.

Upvotes: 2

Jaydeep Khamar
Jaydeep Khamar

Reputation: 5985

Using this might help you

getResources().getString(R.string.building_name);

This works for me

Upvotes: 2

Related Questions