How to store more than one value using Sharedpreferences?

Asked

Viewed 462 times

0

I’m making an app where I created a checkbox to represent a favorite item.

The problem I’m having is that when I put more than one item as a favorite, the last one replaces the first one, that is, it’s allowing adding only one record.

How can I save multiple records using sharedPreferences?

Follows my code:

MAIN ACTIVITY

// EVENTO DE CLIQUE
           lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
               @Override
               public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                   // CHECK BOX
                   View checkBoxView = View.inflate(FraseAutorFrase.this, R.layout.checkbox, null);
                   CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkbox);
                   checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                       @Override
                       public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                           // Save to shared preferences
                           SharedPreferences sharedPreferences = getSharedPreferences("arquivoPreferencia", MODE_PRIVATE);
                           SharedPreferences.Editor editor = sharedPreferences.edit();
                           editor.putString("frase", frasesR[position]);
                           editor.commit();
                       }
                   });
                   checkBox.setText("Marcar como Favorito?");
                   // Recuperar dados
                   SharedPreferences sharedPreferences = getSharedPreferences(ARQUIVO_PREFERENCIA, MODE_PRIVATE);
                   if (sharedPreferences.contains("frase"))
                   {
                       Intent intent = new Intent(FraseAutorFrase.this, Favoritos.class);
                   }

FAVORITE ACTIVITY

SharedPreferences sharedPreferences = getSharedPreferences("arquivoPreferencia", MODE_PRIVATE);
        String fraseR = sharedPreferences.getString("frase","Não Existem Favoritos!");
            // CRIANDO O ARRAY
            final String[] frasesFavoritoArray =
                    {
                            fraseR
                    };
            // UTILIZANDO O ADPTADOR PARA RECEBER O LISTVIEW
            ArrayAdapter<String> adaptador = new ArrayAdapter<String>
                    (
                            // Primeiro Parametro do Array Adpater é o Context
                            getApplicationContext(),
                            // Segundo Parametro do Array Adpater é o Layout
                            android.R.layout.simple_list_item_1,
                            android.R.id.text1,
                            // Terceiro Parametro do Array Adapter é indicar o nome do Array para exibição
                            frasesFavoritoArray
                    );
            lista.setAdapter(adaptador);

1 answer

1


The values saved in Sharedpreferences work as a "Value Key" pair. To store multiple values, you have to use separate keys. In your case, you are using the same "phrases" key for the entire list. You can do something like this in your code:

editor.putString("frase" + position, frasesR[position]);

It will save the data in the keys "frase1", "frase2", etc. Then you have to adapt the code that reads these keys.

Particularly it is not a good practice to use Sharedpreferences to store a lot of data, especially if the data in your list is dynamic, because the data saved may not match the time they were saved.

  • Thanks for the answer, Marty. What would be the easiest way to read this information from the "phrase" + position?

  • As I said, and reading your code better, storing what you want in Sharedpreferences is not very good, incidentally it will even take a lot of work to implement. The ideal would be to actually use database.

  • If you still want to insist on Sharedpreferences, take a look at this answer, I think it will suit you: https://stackoverflow.com/questions/22089411/how-to-get-all-keys-of-sharedpreferences-programmatically-in-android

  • Thank you, Márcio. I’m using Sharedpreference more for limited database knowledge, I know that the ideal would be to use Sqlite. Once again, thank you!!!

  • Take a look at this course, it’s very good. I learned from it: https://br.udacity.com/course/android-basics-data-storage-ud845/

  • Thanks, Márcio. Thank you very much, I’m going to take this course, I need it. Hug!

Show 1 more comment

Browser other questions tagged

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