How to save a list of elements with Shared Preferences

Asked

Viewed 2,292 times

6

I am creating a contact list and would like to save this list with Sharedpreferences.

Example:

public class MeusContatos extends Activity implements OnClickListener {
    int pos=0;
    public static final String PREFS_NAME = "Preferences";
    private List<Contatos> contatos = new ArrayList<Contatos>();
    private ContatoAdapter adaptador = null;

    EditText etNome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meus_contatos);

         /*
        etNome = (EditText) findViewById(R.id.nome);

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        etNome.setText(settings.getString("PrefUsuario",""));


        Button salvar = (Button) findViewById(R.id.salvar);
        salvar.setOnClickListener(this);
        */

        ListView lista = (ListView) findViewById(R.id.contato);
        adaptador = new ContatoAdapter();
        lista.setAdapter(adaptador);

    }

    protected void onStop(){
        super.onStop();

        Button salvar = (Button) findViewById(R.id.salvar);
        salvar.setOnClickListener(this);

        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("PrefUsuario", etNome.getText().toString());

        editor.commit();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_meus_contatos, menu);
        return true;
    }

    public void onClick(View v){
        EditText nome = (EditText) findViewById(R.id.nome);
        EditText email = (EditText) findViewById(R.id.email);
        EditText telefone = (EditText) findViewById(R.id.telefone);

        Contatos contato = new Contatos();

        contato.setNome(nome.getText().toString());
        contato.setEmail(email.getText().toString());
        contato.setTelefone(telefone.getText().toString());

        String name  = nome.getText().toString();
        String mail = email.getText().toString();
        String fone  = telefone.getText().toString();

        RadioGroup tipoContato = (RadioGroup) findViewById(R.id.tipo_contato);

        switch (tipoContato.getCheckedRadioButtonId()){
            case R.id.pessoal:
                contato.setTipo(Contatos.Tipo.PESSOAL);
                break;
            case R.id.profissional:
                contato.setTipo(Contatos.Tipo.PROFISSIONAL);
                break;
            case R.id.academico:
                contato.setTipo(Contatos.Tipo.ACADEMICO);
                break;
        }
        adaptador.add(contato);

    }

//CRIANDO UM ADAPTADOR PARA MELHORAR A LISTA DE ITENS
    private class ContatoAdapter extends ArrayAdapter {

        public ContatoAdapter() {
            super(MeusContatos.this, android.R.layout.simple_list_item_1,
                    contatos);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View linha = convertView;
            ArmazenadorDeContatos armazenador = null;

            if (linha == null) {
                LayoutInflater inflater = getLayoutInflater();
                linha = inflater.inflate(R.layout.elemento_lista, null);
                armazenador = new ArmazenadorDeContatos(linha);
                linha.setTag(armazenador);
            } else {
                armazenador = (ArmazenadorDeContatos) linha.getTag();
            }

            armazenador.popularFormulario(contatos.get(position));

            return linha;
        }
    }

    static class ArmazenadorDeContatos {
        private TextView nome = null;
        private TextView email = null;
        private TextView telefone = null;
        private ImageView icone = null;

        public ArmazenadorDeContatos(View linha) {
            nome = (TextView) linha.findViewById(R.id.titulo);
            email = (TextView) linha.findViewById(R.id.subtitulo);
            telefone = (TextView) linha.findViewById(R.id.subTel);

            icone = (ImageView) linha.findViewById(R.id.icone);
        }

        void popularFormulario(Contatos contato) {
            nome.setText(contato.getNome());
            email.setText(contato.getEmail());
            telefone.setText(contato.getTelefone());

            switch (contato.getTipo()) {
                case ACADEMICO:
                    icone.setImageResource(R.drawable.img_oi);
                    break;
                case PESSOAL:
                    icone.setImageResource(R.drawable.img_claro);
                    break;
                case PROFISSIONAL:
                    icone.setImageResource(R.drawable.img_vivo);
                    break;
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

2 answers

8

An alternative to serialize in any version is to create a JSON, in case an array, from your contacts collection, and save as String in the SharedPreferences.

To serialize

Just create a JSONArray, fill it with JSONObject's with contact data and obtain the String to save:

JSONArray array = new JSONArray();
JSONObject obj;

for(Contato c : contatos) {
   obj = new JSONObject();

   obj.put("nome", contato.getNome());
   // Adicionar as demais propriedades...

   array.put(obj);
}

String arrayStr = array.toString();

SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("contatos", arrayStr).commit();

The JSON which will be stored in the SharedPreferences at the end will have that shape:

[{nome: 'NOME', email: 'EMAIL', ...}, {...}, {...}, ...]

To recover

SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

JSONArray array = new JSONArray(sharedPreferences.getString("contatos"));
List<Contato> contatos = new ArrayList<Contato>();
Contato contato;
JSONObject obj;

for(int i = 0; i < array.length(); ++i) {
    obj = array.getJSONObject(i);

    contato = new Contato();

    contato.setNome(obj.getString("nome"));
    // O mesmo para as demais propriedades...

    contatos.add(contato);    
}

OBS

Never good to use SharedPreferences as a form of storage for many objects. The purpose of SharedPreferences is to save user options, but nothing prevents using for other means. The most recommended for the requirement is to use the SQLite, but it all depends on the need.

4

From API 11 onwards you can save the contacts using Set.
With the contact list in hand just do the following:

//Salvando
private void saveContactList(ArrayList<Contatos> listaDeContatos){
    SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();

    Set<String> contactSet = new HashSet<>();
    contactSet.addAll(listaDeContatos);

    editor.putStringSet("lista_de_contatos_key", contactSet);
    editor.commit();
}

//Recuperando
private ArrayList<Contatos> retrieveContactList(){
    SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    Set<String> concatcSet = sharedPreferences.getStringSet("lista_de_contatos_key", null);

    return new ArrayList<Contatos>(contactSet);
}

Reference: stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences

Browser other questions tagged

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