SharedPreferences的使用三

2021-08-28 20:38:57 字數 2623 閱讀 2421

上一節我們學習了如何對sharedpreferences的資料進行增刪改查,由上一節我們可以知道sharedpreferences只能儲存int、long、float、boolean、string和string的set集合,如果我們想要儲存乙個可序列化物件怎麼辦呢?要儲存乙個可序列化物件的集合又怎麼辦呢?同樣如果要儲存乙個位元組陣列怎麼辦?以及其他型別的陣列怎麼辦?接下來我們一一解決這些問題。

首先解決位元組陣列,乙個思路就是將位元組陣列轉化為string型別在儲存為string,位元組陣列轉string很簡單就不寫了,接下來解決可序列化物件儲存問題,思路就是先將可序列化物件轉化為位元組陣列,在用位元組陣列的儲存方法儲存,下面是可序列化物件轉位元組陣列的方法

public byte putserializable(string key, serializable serializable)  catch (exception e) 

return buff;

}

其他的問題也可以用相應的辦法解決,這裡就不一一介紹了,我們會發現全都轉化到string型別儲存的,這樣就引入了乙個新問題就是如何區分是string型別還是其他型別呢,用系統自帶的是不好區分了,下面我們就自己編寫乙個sharedpreferences,先看**

public class sharedpreferences  catch (exception e) 

if (file.exists())

} private void paras()

} catch (exception e) finally

} //將節點轉化為節點物件

private entry paras(node node)

return new entry(type, key, set);

}throw new runtimeexception("標籤出錯了");

} catch (exception e)

return null;

} public string getstring(string key, string defvalue)

public int getint(string key, int defvalue)

public long getlong(string key, long defvalue)

public float getfloat(string key, float defvalue)

public boolean getboolean(string key, boolean defvalue)

public double getdouble(string key, double defvalue)

@suppresswarnings("unchecked")

public setgetset(string key, setdefvalue)

public boolean contains(string key)

public sharedpreferences putstring(string key, string value)

public sharedpreferences putint(string key, int value)

public sharedpreferences putlong(string key, long value)

public sharedpreferences putfloat(string key, float value)

public sharedpreferences putboolean(string key, boolean value)

public sharedpreferences putdouble(string key, double value)

public sharedpreferences putset(string key, setvalue)

public sharedpreferences remove(string key)

public sharedpreferences clear()

private int indexof(string key)

return -1;

} private entry serch(string key)

//提交資料,將資料儲存到檔案中

public boolean commit()

}} else

}transformer.transform(new domsource(document), result);

streamutil.close(filewriter);

return true;

} catch (exception e)

return false;

} private node entry2node(document document, entry entry)

private class entry

}}

通過上面我們發現我們用型別作為標籤名,key是屬性,value是值,這樣我們就可以區分型別了,上面只是模仿了系統的sharedpreferences,如果需要儲存其他型別或其他型別的集合,就需要對這個類稍微修改下,重點是修改解析和儲存方法。這樣就解決了上面提到的問題。

SharedPreferences的使用方法

獲取sharedpreferences的兩種方式 1 呼叫context物件的getsharedpreferences 方法 2 呼叫activity物件的getpreferences 方法 兩種方式的區別 呼叫context物件的getsharedpreferences 方法獲得的sharedpr...

使用SharedPreferences記錄資訊

在android中有數種不同儲存狀態的機制,包括儲存於android提供的首選物件 sharedpreferences 存成檔案,存成資料庫 sqlite 存到網路上 通過http或者其他網路協議 使用sharepreferences物件儲存資料 在activity中使用getpreferences...

SharedPreferences 使用注意事項

1.建立 sharedpreferences preferences getsharedpreferences first mode world readable mode multi process 注意剛剛生成的這個檔案first的許可權,後續貌似改不了許可權的,除非解除安裝了重新run sha...