Save ArrayList to SharedPreferences

前端 未结 30 3554
野的像风
野的像风 2020-11-21 04:43

I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves

30条回答
  •  执笔经年
    2020-11-21 05:15

        public  void saveUserName(Context con,String username)
        {
            try
            {
                usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
                usernameEditor = usernameSharedPreferences.edit();
                usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1)); 
                int size=USERNAME.size();//USERNAME is arrayList
                usernameEditor.putString(PREFS_KEY_USERNAME+size,username);
                usernameEditor.commit();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
    
        }
        public void loadUserName(Context con)
        {  
            try
            {
                usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
                size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);
                USERNAME.clear();
                for(int i=0;i(this, android.R.layout.simple_dropdown_item_1line, USERNAME);
                username.setAdapter(usernameArrayAdapter);
                username.setThreshold(0);
    
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    

提交回复
热议问题