SharedPreferences介紹,用來做資料存放區

來源:互聯網
上載者:User

標籤:style   sha   cat   com   div   bool   介紹   stat   try   

 

sharedPreferences是通過xml檔案來做資料存放區的。
一般用來存放一些標記性的資料,一些設定資訊。


*********使用sharedPreferences儲存資料

 

 public static boolean saveUserInfo(Context context, String username, String password) {        try {            //1使用Context建立一個SharePerference對象            SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);            //2SharePerference對象得到Editor對象            Editor edit = sharedPreferences.edit();            //3往Editor對象裡面添加資料            edit.putString("username",username);            edit.putString("password",password);            //4提交Editor對象            edit.commit();            return true;        } catch (Exception e) {            e.printStackTrace();        }        return false;    }

 

*********使用sharedPreferences讀取資料

public static Map<String, String> getUserInfo(Context context) {              try {            //1 使用Context建立一個SharePerference對象            SharedPreferences sharedPreferences = context.getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);            //2SharePerference對象擷取存放的資料            String username = sharedPreferences.getString("username", "");            String password = sharedPreferences.getString("password", "");            HashMap<String, String> hashMap = new HashMap<String, String>();            hashMap.put("username", username);            hashMap.put("password", password);            return hashMap;        } catch (Exception e) {            e.printStackTrace();        }        return null;    }

通過PreferenceManager可以擷取一個預設的sharepreferences對象
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

SharedPreferences介紹,用來做資料存放區

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.