TheD3luxed TheD3luxed - 2 months ago 6
Android Question

I can't write a method to get StringSet from SharedPref

I've encountered issue and maybe you guys can help me. I'm creating Shopping list app for android.
In this code below everything works:

List<String> list,listRecipe;
ListView listView,listViewRecipe;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);


getArrayList();
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
}

public void getArrayList(){
SharedPreferences sharedPreferences = getSharedPreferences("Data", MODE_PRIVATE);
Set<String> mySetdownloaded = sharedPreferences.getStringSet("List", NotFoundSet());
if (mySetdownloaded.size() == 0){
list = new ArrayList<>();
}
else {
list = new ArrayList<>(sharedPreferences.getStringSet("List", NotFoundSet()));
}
}


But when i make changes in my getArrayList Method so i can use it not only with one LIST but more (added argument) it's not working. I just get "App stopped working" on start

List<String> list,listRecipe;
ListView listView,listViewRecipe;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);


getArrayList(list);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
}

public void getArrayList(List<String> lists){
SharedPreferences sharedPreferences = getSharedPreferences("Data", MODE_PRIVATE);
Set<String> mySetdownloaded = sharedPreferences.getStringSet("List", NotFoundSet());
if (mySetdownloaded.size() == 0){
lists = new ArrayList<>();
}
else {
lists = new ArrayList<>(sharedPreferences.getStringSet("List", NotFoundSet()));
}
}

Answer

In the second snnipet you call getArrayList(list), but getArrayList() doesn't return ANYTHING. And after you try to call list at

adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);

but list it's nothing, not even null, so you'll get nullpointerexception and crashes your app... You have to, at least, make getArrayList return something and assign to the attribute list, OR you don't pass list as argument, and try to access it as this.list instead lists.