Domanda

Ho un ArrayList di oggetti che hanno un nome e un puntatore icona e voglio salvarlo in SharedPreferences. Come posso fare?

NOTA: Non voglio usare database

È stato utile?

Soluzione

Quindi, dal sito degli sviluppatori Android su Data Storage :

  

Preferenze utente

     

Preferenze condivise non sono strettamente per il salvataggio "delle preferenze utente" , come quello che ringtone un utente ha scelto. Se siete interessati a creare le preferenze degli utenti per la vostra applicazione, vedere PreferenceActivity, che fornisce un quadro di attività per la creazione di preferenze degli utenti, che verranno automaticamente rese persistenti (utilizzando le preferenze condivise).

Quindi penso che va bene in quanto è semplicemente coppie chiave-valore, che vengono mantenuti.

Per il manifesto originale, questo non è così difficile. È semplicemente iterare attraverso la vostra lista di array e aggiungere le voci. In questo esempio io uso una mappa per semplicità ma è possibile utilizzare una lista di array e cambiare in modo appropriato:

// my list of names, icon locations
Map<String, String> nameIcons = new HashMap<String, String>();
nameIcons.put("Noel", "/location/to/noel/icon.png");
nameIcons.put("Bob", "another/location/to/bob/icon.png");
nameIcons.put("another name", "last/location/icon.png");

SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();

for (String s : nameIcons.keySet()) {
    // use the name as the key, and the icon as the value
    keyValuesEditor.putString(s, nameIcons.get(s));
}
keyValuesEditor.commit()

Si potrebbe fare qualcosa di simile a rileggere le coppie chiave-valore. Fatemi sapere se questo funziona.

Aggiornamento: Se si sta utilizzando API di livello 11 o superiore, c'è un metodo per scrivere un set stringa

Altri suggerimenti

A prescindere dal livello di API, Controllare array stringhe e array di oggetti in SharedPreferences


Salva ARRAY

public boolean saveArray(String[] array, String arrayName, Context mContext) {   
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    SharedPreferences.Editor editor = prefs.edit();  
    editor.putInt(arrayName +"_size", array.length);  
    for(int i=0;i<array.length;i++)  
        editor.putString(arrayName + "_" + i, array[i]);  
    return editor.commit();  
} 

carico di matrice

public String[] loadArray(String arrayName, Context mContext) {  
    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(arrayName + "_size", 0);  
    String array[] = new String[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getString(arrayName + "_" + i, null);  
    return array;  
}  

Per scrivere,

SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(this);
JSONArray jsonArray = new JSONArray();
jsonArray.put(1);
jsonArray.put(2);
Editor editor = prefs.edit();
editor.putString("key", jsonArray.toString());
System.out.println(jsonArray.toString());
editor.commit();

Per leggere,

try {
    JSONArray jsonArray2 = new JSONArray(prefs.getString("key", "[]"));
    for (int i = 0; i < jsonArray2.length(); i++) {
         Log.d("your JSON Array", jsonArray2.getInt(i)+"");
    }
} catch (Exception e) {
    e.printStackTrace();
}

preferenze condivise introdotto un getStringSet e putStringSet metodi API livello 11, ma non è compatibile con le versioni precedenti di Android (che sono ancora popolari), ed anche è limitato a insiemi di stringhe.

Android non fornisce metodi migliori, e loop su mappe e array per salvare e caricare loro non è molto facile e pulita, specialmente per gli array. Ma una migliore applicazione non è così difficile:

package com.example.utils;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.content.SharedPreferences;

public class JSONSharedPreferences {
    private static final String PREFIX = "json";

    public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
        editor.commit();
    }

    public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
        editor.commit();
    }

    public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
    }

    public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
    }

    public static void remove(Context c, String prefName, String key) {
        SharedPreferences settings = c.getSharedPreferences(prefName, 0);
        if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
            SharedPreferences.Editor editor = settings.edit();
            editor.remove(JSONSharedPreferences.PREFIX+key);
            editor.commit();
        }
    }
}

Ora è possibile salvare qualsiasi raccolta nelle preferenze condivise con questo cinque metodi. Lavorare con JSONObject e JSONArray è molto facile. È possibile utilizzare JSONArray (Collection copyFrom) costruttore pubblico di fare un JSONArray di metodi JSONArray qualsiasi Java raccolta e l'uso di get per accedere agli elementi.

Non v'è alcun limite di dimensione per le preferenze condivise (oltre limiti di archiviazione del dispositivo), in modo che questi metodi possono funzionare per la maggior parte dei casi usuali in cui si desidera un deposito facile e veloce per qualche raccolta nella vostra app. Ma JSON parsing accade qui, e le preferenze in Android vengono memorizzate come XMLs internamente, quindi mi consiglia di utilizzare altri meccanismi persistente memorizzare i dati quando hai a che fare con i megabyte di dati.

Modalità facile per riporre oggetti complessi con l'utilizzo della libreria GSON Google [1]

public static void setComplexObject(Context ctx, ComplexObject obj){
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("COMPLEX_OBJECT",new Gson().toJson(obj)); 
    editor.commit();
}

public static ComplexObject getComplexObject (Context ctx){
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
    String sobj = preferences.getString("COMPLEX_OBJECT", "");
    if(sobj.equals(""))return null;
    else return new Gson().fromJson(sobj, ComplexObject.class);
}

[1] http://code.google.com/p/google-gson/

I caricata una vasta gamma di formati della vita (già creati nel mio array.xml) nel mio file preferences.xml con il codice qui sotto. @Array / pant_inch_size è l'id dell'intero array.

 <ListPreference 
 android:title="choosepantsize"
 android:summary="Choose Pant Size"
 android:key="pantSizePref" 
 android:defaultValue="34" 
 android:entries="@array/pant_inch_size"
 android:entryValues="@array/pant_inch_size" /> 

Questa popolato il menu con scelte dalla matrice. Ho impostato la dimensione predefinita di 34, in modo che quando il menu si apre, che vedono taglia 34 è pre-selezionato.

Il modo più semplice è, per convertirlo in JSON String come di seguito esempio:

Gson gson = new Gson();
String json = gson.toJson(myObj);

Poi memorizzare la stringa nelle preferenze condivise. Una volta che ne avete bisogno solo ottenere stringa dalle preferenze condivise e riconvertire JSONArray o JSONObject (secondo il vostro requisito.)

Per la scrittura:

 private <T> void storeData(String key, T data) {
    ByteArrayOutputStream serializedData = new ByteArrayOutputStream();

    try {
        ObjectOutputStream serializer = new ObjectOutputStream(serializedData);
        serializer.writeObject(data);
    } catch (IOException e) {
        e.printStackTrace();
    }

    SharedPreferences sharedPreferences = getSharedPreferences(TAG, 0);
    SharedPreferences.Editor edit = sharedPreferences.edit();

    edit.putString(key, Base64.encodeToString(serializedData.toByteArray(), Base64.DEFAULT));
    edit.commit();
}

Per la lettura:

private <T> T getStoredData(String key) {
    SharedPreferences sharedPreferences = getSharedPreferences(TAG, 0);
    String serializedData = sharedPreferences.getString(key, null);
    T storedData = null;
    try {
        ByteArrayInputStream input = new ByteArrayInputStream(Base64.decode(serializedData, Base64.DEFAULT));
        ObjectInputStream inputStream = new ObjectInputStream(input);
        storedData = (T)inputStream.readObject();
    } catch (IOException|ClassNotFoundException|java.lang.IllegalArgumentException e) {
        e.printStackTrace();
    }

    return storedData;
}

Questo è il codice preferenze condiviso io uso con successo, fare riferimento questo collegamento :

  public class MainActivity extends Activity {

private static final int RESULT_SETTINGS = 1;
Button button;
public String a="dd";

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

 button = (Button) findViewById(R.id.btnoptions);


setContentView(R.layout.activity_main);

  // showUserSettings();
  }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.settings, menu);
return true;
 }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {

case R.id.menu_settings:
 Intent i = new Intent(this, UserSettingActivity.class);
 startActivityForResult(i, RESULT_SETTINGS);
 break;

 }

return true;
}

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data)     {
  super.onActivityResult(requestCode, resultCode, data);

 switch (requestCode) {
 case RESULT_SETTINGS:
 showUserSettings();
 break;

 } 

  }

  private void showUserSettings() {
 SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);

 StringBuilder builder = new StringBuilder();

 builder.append("\n Pet: "
  + sharedPrefs.getString("prefpetname", "NULL"));

 builder.append("\n Address:"
 + sharedPrefs.getString("prefaddress","NULL" ));

 builder.append("\n Your name: "
 + sharedPrefs.getString("prefname", "NULL"));

 TextView settingsTextView = (TextView) findViewById(R.id.textUserSettings);


  settingsTextView.setText(builder.toString());


    }

   }

HAPPY codifica!

È possibile utilizzare putStringSet

Questo consente di salvare un HashSet nelle preferenze, proprio come questo:

Salva

Set<String> values;

SharedPreferences sharedPref = 
    mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);

Editor editor = sharedPref.edit();

editor.putStringSet("YOUR_KEY", values);
editor.apply();

retrive

SharedPreferences sharedPref = 
    mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);

Editor editor = sharedPref.edit();

Set<String> newList = editor.getStringSet("YOUR_KEY", null);

Il putStringSet consentono solo un insieme e questo è un non ordinato .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top