I'm making an app where I created a checkbox to represent a favorite item.
The problem I'm having is what I'm having is when I put more than one item as a favorite, the last one replaces the first one, that is, it's allowing you to add only one record.
How can I save multiple records using sharedPreferences?
Follow 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);
}
ACTIVITY FAVORITES
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);