How to change statistic text to String?

guys. I want to replace the statistical code for code that can receive text from strings.xml (in this case "App Name":

private final static String APP_TITLE = "App name";

This is full code.

Thank you!

P.S. Nope, getString doesn't work(

Answers


If you want to change a property value, don't make it final static. Instead you should do :

private  String appTitle = "App name";

If I understand you correctly you want a static String field to contain a value from resources? You cannot initialize a static string from resources because resources are not available at that point. What you can do is

private static final int RES_ID = R.String.app_name;

and call getString(RES_ID) anywhere you would call APP_TITLE (or just once and save to a variable)


Your main problem is you don't have a context to get resources. This can be solved by getting a context before this field is initialized. A possible workaround for this is to create an Application class, set it's context to a static field, then used this field in your Activty to get the desired string.

Application class:

public class AppContext extends Application {

   public static Context cntx;
    @Override
    public void onCreate() {
        super.onCreate();
        cntx=getApplicationContext();
    }
}

Register it in the manifest:

  <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Test"
        android:name=".AppContext"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Main2Activity"
            android:label="Test" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

Activity:

public class Main2Activity extends AppCompatActivity {

    private final static String APP_TITLE = AppContext.cntx.getResources().getString(R.string.app_name);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main2);
        Button b = (Button) findViewById(R.id.button);
        b.setText(APP_TITLE);
    }
}

Need Your Help

Blog engine supporting multiple blogs in ASP.NET?

asp.net blogs

I'm using ASP.NET on my current website and now I need to add some blogs to the site. I need at least 5 multiple blogs and I'm looking for a solution in ASP.NET.

Keep getting errors on my Pointer code in c++ for no apparent reason

c++ pointers

So I am experimenting with pointers as I am quite new to C++ programming the error p1 was not declared in this scope keeps coming up I have no clue what's wrong I have searched the deepest corners...