Quick Development Tip – Android: Refactoring strings.xml

How to easily extract strings from your Android code into the strings.xml file

This handy little feature can save a lot of time and manual work when working with Android apps.

If you during Android development in Eclipse use hard-coded strings in your Java code, like in the example below:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package test.layout;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
 
public class LayoutTest extends Activity {
 
    private Button btn;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        btn = (Button) findViewById(R.id.Button01);
        btn.setText("Populate Data");
    }
}

Maybe you want to gather them in the strings.xml file where they belong, to separate hardcoded strings from the code and to get an overview of your string resources. This also makes it easier to internationalise your application later on.

You can just select the string to extract out, “Populate Data” on line 17, and then in the Eclipse main menu, go to: Refactor > Android > Extract Android String…

You can then give your new string a name, edit the string text if you want, and select where to place it (the default is in you strings.xml file: /res/values/strings.xml).

Then hit the OK button to extract your string.

[msg_box type=”success” icon=”yes” hide=”yes”]Tip: You could also use the keyboard shortcut: First press Shift + Alt + A, then press S[/msg_box]

You will notice that the hard-coded string “Populate Data” gets replaced with a resource id,R.string.populate_data

 

1
 btn.setText(R.string.populate_data);

This resource makes it easy to refer to your string several places in your code, while keeping only one version of the text itself in the strings.xml file, which now looks like this:

1
2
3
<!--?xml version="1.0" encoding="utf-8"?-->
 
    Populate Data

If you need to edit your text, just edit it in the strings.xml file.
That’s it, hope you found this useful, and saved you manual development time.