I'm needing help with SharedPreference. I'm developing a phrases APP, where there is a checkbox that marks the favorite phrases and plays those phrases in SharedPreferences where they can be accessed from a button called bookmarks.
The problem is that if we click on favorites without having any bookmarks in which it fires when the checkbox is checked, it closes the app and the log displays the following message:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size ()' on a null object reference
I would like to get around this, even if possible already leave a default value in the sharedpreference if that is the case or some other alternative.
Follow my code, if you can help me ...
// 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" + position, frasesR[position]);
editor.commit();
}
});
checkBox.setText("Marcar como Favorito?");
This information is passed to another Activity
* ACTIVITY FAVORITOS
final SharedPreferences sharedPreferences = getSharedPreferences("arquivoPreferencia", MODE_PRIVATE);
// CRIANDO A LISTA PARA RECEBER OS FAVORITOS
final List<String> frasesFavoritoArray = new ArrayList<>();
// TRANSFORMANDO ARRAY EM STRING
Object[] objectList = frasesFavoritoArray.toArray();
final String[] stringArray = Arrays.copyOf(objectList, objectList.length, String[].class);
// CAPTURANDO TODOS OS REGISTROS DO SHARED PREFERENCE
Map<String, ?> allEntries = sharedPreferences.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
frasesFavoritoArray.add(entry.getKey().toString());
frasesFavoritos = frasesFavoritoArray;
}