I have looked through all of my code, but I can't find any null references, so I am lost. I am saving certain contacts the the user collects into shared preferences:
public void saveContacts() {
contacts = this.getSharedPreferences("contacts", MainActivity.MODE_PRIVATE); //Making a shared preferences
Set<String> set = new HashSet<String>();
set.addAll(contactArrayList);
contactEditor.clear(); //Clearing current values in shared pref
contactEditor.putStringSet("contactSetKey", set); //Adding contacts
contactEditor.commit();
Toast.makeText(MainActivity.this, "Contacts have been saved!", Toast.LENGTH_SHORT).show();
}
Here is where I get the contacts:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactArrayList= new ArrayList<String>();
listview = (ListView) findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter (this, android.R.layout.simple_list_item_1, contactArrayList);
listview.setAdapter(arrayAdapter);
loadSavedStuff();
}
public void loadSavedStuff() {
//CLEAR CONTENTS OF ARRAYLIST AND GET THEM FROM SHARED PREFERENCE
if(contacts.getStringSet("contactSetKey", null) != null) {
contactArrayList.clear();
contactArrayList = new ArrayList<String>(contacts.getStringSet("contactSetKey", null));
arrayAdapter.notifyDataSetChanged();
}
}
I have been adding stuff to my list like so:
contactArrayList.add(contactName +" - " +contactNumber);
arrayAdapter.notifyDataSetChanged();
My null pointer exception is here:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Set android.content.SharedPreferences.getStringSet(java.lang.String, java.util.Set)' on a null object reference
Pointing here:
if(contacts.getStringSet("contactSetKey", null) != null) {
and here:
loadSavedStuff();