Android - Share Preferences for another device

Asked

Viewed 63 times

1

My question is the following: it is possible to share information saved by Sharedprefences to another device, either by bluetooth or another connection ?

Mainactivity.java:

SharedPreferences.EDITOR editor = getSharedPreferences("pref", MODE_PRIVATE).edit();
editor.putString("value1", "example");
editor.commit();

1 answer

1


"Yes, "it’s possible, not as directly as you might be thinking.

1. Saving preferences in something concrete

Using the Objectoutputstream we can create a file with primitive data to be later read and transformed back into a Java object. The point here is to take all preferences and save in a Map (since they are keys and values) using the Sharedpreferences.getAll()

File prefsFile = new File(getExternalFilesDir(null), "prefs.bak");
if (!prefsFile.exists()) {
    if (!prefsFile.createNewFile())
        // Falha ao criar arquivo
}

try {
    SharedPreferences prefs = getSharedPreferences("pref", MODE_PRIVATE);
    ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(prefsFile));
    output.writeObject(prefs.getAll());
    output.flush();
    output.close();
} catch (IOException e) {
    // Falha ao escrever no arquivo
}

2. Send prefs.Bak to the other device

Well, there are several ways to do this. Once submitted, be aware of the file path.

3. Read and apply prefs.Bak on the other device

Assuming both devices run your app:

File prefsFile = new File("caminho/para/o/prefs.bak");
if (prefsFile.exists()) {
    try {
        SharedPreferences.Editor editor = getSharedPreferences("pref", MODE_PRIVATE).edit();
        ObjectInputStream input = new ObjectInputStream(new FileInputStream(prefsFile));
        // Ler o objeto como um mapa
        Map<String, ?> entries = (Map<String, ?>) input.readObject();
        // Na falta de um método "putAll()" vamos dar um loop no mapa e pra cada entry, fazemos um apply()
        for (Map.Entry<String, ?> entry : entries.entrySet()) {
            Object o = entry.getValue();
            String key = entry.getKey();

            if (o instanceof Boolean)
                editor.putBoolean(key, (Boolean) o);
            else if (o instanceof Float)
                editor.putFloat(key, (Float) o);
            else if (o instanceof Integer)
                editor.putInt(key, (Integer) o);
            else if (o instanceof Long)
                 editor.putLong(key, (Long) o);
            else if (o instanceof String)
                 editor.putString(key, ((String) o));
            }
            // Finalmente aplique os novos valores importados
            editor.apply();
    } catch (ClassNotFoundException | IOException ex) {
         // Falha ao ler arquivo
    }
} else {
    // Arquivo não encontrado
}

Browser other questions tagged

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