Resource-provided integer being garbled at runtime

75 Views Asked by At

In my Android app, I've created the file app/src/main/res/values/integers.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="server_port">8080</integer>
</resources>

I then have

public class MyApplication extends Application {
    final MyServer server = new MyServer(R.integer.server_port);
}

However, when the app launches, a log statement reveals the value (i.e., R.integer.server_port) to be 2131296322.

Why is the value being garbled? Is that not how integer resources are supposed to be implemented?

1

There are 1 best solutions below

0
Daniel Walker On BEST ANSWER

R.integer.server_port gives the resource ID of the integer, not the integer itself. In order to get the actual integer, you have to do getResources().getInteger(R.integer.server_port). However, this requires some modification to your original code as the resources won't have been set up by the time MyApplication is instantiated. Instead, you can do

public class MyApplication extends Application {
    MyServer server;

    @Override
    public void onCreate() {
        super.onCreate();
        server = new MyServer(getResources().getInteger(R.integer.server_port));
    }
}

Of course, server won't be final anymore. You can refactor to

public class MyApplication extends Application {
    private MyServer server;

    public MyServer getServer() {
        return server;
    }

    ...