Saving a list of elements with Shared Preferences

6

I'm 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);
    }

}
    
asked by anonymous 23.04.2015 / 05:30

2 answers

8

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

To serialize

Just create a JSONArray , fill it with JSONObject's with the contact data and get 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 that will be stored in SharedPreferences at the end will have this form:

[{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

It is 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 from using for other means. The most recommended for the requirement is to use SQLite , but everything depends on the need.

    
23.04.2015 / 15:15
4

From API 11 you can save 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

    
23.04.2015 / 06:38