How to modify XML elements with Java?

3

I've never worked with XML before. I created the following XML configs.xml :

<resources>
    <string name="ip"></string>
    <string name="username"></string>
    <string name="password"></string>
    <string name="banco"></string>
    <string name="porta"></string>
    <string name="funcionario"></string>
    <string name="ultimoUpdate"></string>
</resources>

How to access and modify the above fields with Java language?

    
asked by anonymous 29.10.2014 / 20:13

1 answer

7

The answer addresses two issues:

  • Resources;
  • SharedPreferences.
  • Resources

    To use String's on the Android platform, you do not need parsing of XML.

    Android has a rich resource API ( Resources ).

    Resources are organized from the /res/values folder of your project. And they are treated hierarchically, that is, there are some modifiers that can cause some features to overwrite others. For example, you may have already seen that there are folders with xhdpi , mdpi , large , sw600dp , and others.

    In addition, this "hierarchy" feature (I'm not sure the correct term) is widely used to internationalize applications, this can be seen in more detail in this question: How to apply internationalization in an Android app?

    Examples of resources would be: Animations, Colors, Drawables , Layouts, String's and more. The full list you can check in the official documentation at: Resource Types .

    For String's , it is recommended that you place your XML in the same format in the /res/values folder for organization and standardization purposes. For more details, I recommend reading this documentation: Providing Resources .

    When your application compiles, aapt compiles all its resources and generates the class R , where it has identifiers for all its resources.

    From the identifiers you can access the resources at runtime, all through the Resources class.

    In the case of String's , you access through the path: R.string.id_da_sua_string .

    To access Resources , it may depend a little on where your code is.

    In Activity , Fragment , Service or any class that extends from class Context (by taking Fragment ), just use getResources() , for String's itself class Activity provides getString(int resId) , but is only a shortcut to getResources().getString(int resId) .

    Elsewhere, you either have a reference to a Context or you can use a Singleton of the Application class. Using the second alternative, it is very common to do:

    public class MyApplication extends android.app.Application {
    
        private static MyApplication sInstance;
    
        @Override public void onCreate() {
            sInstance = this;
        }
    
        public static MyApplication getInstance() {
            return sInstance;
        }
    }
    

    Declaring in AndroidManifest :

    <application
        android:name="seu.pacote.MyApplication"
        ...
    />
    

    Using this alternative:

    String s = MyApplication.getInstance().getString(R.string.suaString);
    

    If the access is within a file of Layout or any other resource (including the resources of String's ), just refer to this way: @string/sua_string .

    SharedPreferences

    Features managed by the Resources API are read-only. In order to manage the information you need, you will need to use some kind of persistent storage.

    In this context, I recommend using SharedPreferences , where the main feature is to save user-private key-value preferences to your application. The SharedPreferences accepts several primitive types, which I believe in your case is sufficient.

    To recover a SharedPreferences , simply access a Context :

    Context context = getActivity();
    SharedPreferences sharedPref = context.getSharedPreferences(
        getString(R.string.chave_da_preferences), Context.MODE_PRIVATE);
    

    The first parameter is the name, always use the same name to retrieve the same values.

    A simpler way is:

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    

    Remembering that getPreferences uses name as getLocalClassName() .

    Access to data is done using SharedPreferences itself:

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    
    String ipPadrao = getResources().getInteger(R.string.ip);
    String ipUsuario = sharedPref.getString(getString(R.string.chave_ip), ipPadrao);
    

    In this code, I retrieve the ip that I save in Resources because it might not have already put that value in SharedPreferences . the getString needs a key and receives a second parameter indicating the value that will be returned if it does not have that key yet.

    To write, you need to use SharedPreferences.Editor , which will initiate a "transaction" and at the end of the write needs to commit changes in SharedPreferences .

    The writing would be:

    SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    
    editor.putString(getString(R.string.chave_ip), ip);
    editor.commit();
    

    You can have multiple instances of SharedPreferences , when you commit in an edit in any of them, all instances are synchronized, and through OnSharedPreferenceChangeListener you can be notified of any changes, if you want.

    More details on Saving Key-Value Sets

    As a matter of curiosity, SharedPreferences is also serialized on disk as XML , and you can see in your application data in /data/data/NOME_DO_PACOTE/shared_prefs/NOME_DO_SHARED_PREFERENCES.xml .

        
    30.10.2014 / 00:16