我无法编写一个从SharedPref获取StringSet的方法

时间:2016-10-08 14:34:22

标签: java android list

我遇到了问题,也许你们可以帮助我。我正在为Android创建购物列表应用程序。 在下面的代码中,一切正常:

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()));
    }
}

但是当我在getArrayList方法中进行更改时,我不仅可以使用一个LIST,而且可以使用更多(添加参数)它不起作用。我刚刚开始“App停止工作”

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()));
    }
}

2 个答案:

答案 0 :(得分:0)

在第二个snnipet中,您拨打getArrayList(list),但getArrayList()未返回任何内容。在您尝试在

处致电list之后
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);

但是list它什么都没有,甚至不是空的,所以你会得到nullpointerexception并崩溃你的应用......你必须至少让getArrayList返回一些内容然后分配属性list,或者您没有将list作为参数传递,并尝试以this.list而不是lists来访问它。

答案 1 :(得分:0)

我的最终工作代码是:

public List<String> getArrayList(String nameOfSavedFile) {

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

}

感谢您的帮助;)