How to modify XML elements with Java?

Asked

Viewed 1,503 times

3

I have 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?

  • If you are looking for a tutorial see this here

  • What platform are you working with? android?

  • am with android

  • Lucas, you’re putting that file in the folder res/values? If it is, you can access through the class Resources using the identifier. No need to parse xml.

1 answer

7


The answer addresses two issues:

  1. Resources;
  2. Sharedpreferences.

Resources

To use String's on the Android platform is not necessary to do Parsing of XML.

Android has a feature API (Resources) very rich.

Resources are organized from the folder /res/values of your project. And are treated hierarchically, that is, there are some modifiers that can cause some resources to overwrite others. For example, you may have seen that there are folders with suffixes xhdpi, mdpi, large, sw600dp and among 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: Applying internationalization to an Android app?

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

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

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

From the identifiers it is possible to access the resources at runtime, all through the class Resources.

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

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

In a Activity, Fragment, Service or any class extending from the class Context (apart from the Fragment), just use getResources(), for String's the class itself Activity provides the getString(int resId), but it’s just a shortcut to the getResources().getString(int resId).

Anywhere else, or you will have a reference to a Context or else you can use a class Singleton Application. 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 the 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 String's), just reference this way: @string/sua_string.


Sharedpreferences

The resources managed by the Resources 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 the use of SharedPreferences, where the main feature is to save user key-value type preferences, private to your application. The SharedPreferences accepts several primitive types, which I believe in your case is sufficient.

To recover a SharedPreferences, just have access to 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 recover the same values.

A simpler way is:

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

Recalling that the getPreferences uses the name as getLocalClassName().

Data access is done using the SharedPreferences:

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 recover the ip that saves us Resources because it may not have yet put that value in SharedPreferences. the getString needs a key and receives a second parameter stating the value that will be returned if you do not have this key yet.

To write, you need to use the SharedPreferences.Editor, that will initiate a "transaction" and at the end of the writing needs to give commit in the amendments to 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 may have multiple instances of SharedPreferences, when you do commit in an edition in any of them, all instances are synchronized, and through OnSharedPreferenceChangeListener you may be notified of any change if you wish to.

More details on Saving Key-Value Sets

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

  • Good wakim response! but we shouldn’t wait for him to speak?

  • @Joannis If you have the Android tag, we can safely assume that you are using Android and the answers regarding Android are correct.

  • @Zuul, now I understand what @Joannis meant... My answer does not answer... He wants to modify, I read fast and did not notice. I think the answer he wants is to use SharedPreference.

  • Yeah, I was reading better too and I guess so... @Joannis, more attentive than all of us :)

  • I’ll wait for the OP to respond, if that’s the case I delete the answer.

  • Good answer but what to set? I’m saving values that can be changed from within the application

  • @Lucasbertollo, I updated my answer with another solution.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.