且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android:在应用关闭后将值保留在列表中

更新时间:2022-04-22 22:31:37

您的问题的解决方案如下:

the solution to your problem is as follows:

由于此链接,我也尝试并重新编写了代码:

I tried and reworked your code also thanks to this link:

public class MainActivity extends ListActivity {

    private static final String SHARED_PREFS_NAME = "MY_SHARED_PREF";
    ArrayList<String> mylist = new ArrayList<String>();
    ArrayAdapter<String> adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listview = (ListView) findViewById(R.id.list);
        Button btn = (Button) findViewById(R.id.button);

        //NOTE: acquire array from shared preferences
        mylist = getArray();

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

        OnClickListener listener = new OnClickListener() {          
            @Override
            public void onClick(View v) {                               
                EditText edit = (EditText) findViewById(R.id.edittext);
                mylist.add(edit.getText().toString());
                edit.setText("");               
                adapter.notifyDataSetChanged();
            }
        };
        btn.setOnClickListener(listener);
        listview.setAdapter(adapter);        
    }

    public boolean saveArray() {
        SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor mEdit1 = sp.edit();
        Set<String> set = new HashSet<String>();
        set.addAll(mylist);
        mEdit1.putStringSet("list", set);
        return mEdit1.commit();
    }

    public ArrayList<String> getArray() {
        SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);

        //NOTE: if shared preference is null, the method return empty Hashset and not null          
        Set<String> set = sp.getStringSet("list", new HashSet<String>());

        return new ArrayList<String>(set);
    }
}

..并在关闭应用程序之前调用SaveArray()

..and calls SaveArray () before closing the application

public void onStop() {
    saveArray();
    super.onStop();
}

或者,每次添加元素时保存数组(all'onclick按钮会覆盖当前列表中的共享首选项)

or, alternatively, save the array every time you add an element (all'onclick button overwrites the shared preference in the current list)