Android的SharedPreferences同步问题将阵列
喜 我有这样Android的SharedPreferences同步问题将阵列
的场景我做了一个聊天程序,用户可以在广告的朋友,就像在雅虎Messenger或Hotmail信使。如果有很多的朋友请进来,以一个用户i'm他们节省动态 这样的:(每个请求(串)看起来像这样“queryaddnewfriend:名称:UUID”)
String msg = intent.getStringExtra("payload");
String[] split = msg.split(":");
String name = split[1];
String UUID = split[2];
if(msg.startsWith("queryaddnewfriend")){
//queryaddnewfriend:name:UUID
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String frn = prefs.getString("friendrequest1", "");
if(frn == ""){
SharedPreferences.Editor editor = prefs.edit();
String newReq = name.concat(":");
newReq = newReq.concat(UUID); //create the name:UUID string
editor.putString("friendrequest".concat(Integer.toString(1)), newReq);
editor.commit();
}else{
for(int index = 1; index < 1000; ++index) {
String line = prefs.getString("friendrequest".concat(Integer.toString(index)), "");
if(line == ""){
Log.d(TAG,"create new *********************************************");
String newLine = name.concat(":");
newLine = newLine.concat(UUID); //create the name:UUID string
SharedPreferences.Editor editor = prefs.edit();
editor.putString("friendrequest".concat(Integer.toString(index)), newLine);
editor.commit();
break;
}
}
}
所以我SharedPreferences具有非,这样的一行或多行 动态添加(注意“friendrequest1”增量)
prefs.getString(“friendrequest1”,“queryaddnewfriend:name:UUID”); prefs.getString(“friendrequest2”,“queryaddnewfriend:name:UUID”); prefs.getString(“friendrequest3”,“queryaddnewfriend:name:UUID”);
好友请求以friendrequest3开头,向用户逐一展示。
问题出现在用户接受好友请求时。 我必须删除friendrequest3,同时可能会有一个 新朋友请求进入,并执行上面的代码,添加一个新的friendrequest4。
即时通讯使用C2DM,所以我无法控制Google云执行上述代码时。 当我删除“friendrequest3”,因为用户已回复接受或拒绝朋友 我会做editor.remove(“friendrequest3”)editor.commit(); 但是,如果上面的代码添加了“friendrequest4”,我的代码将失败。 此代码的复杂性现在相当高,我猜可以让它更高 并在同一时间增加“bug因素”
任何关于这样做的想法会更好,谢谢!
如果是我,我想我会用这个Sqlite,而不是首选项。管理和处理数据行非常容易,而且您还会发现它更快。我发现写快速连续写入一系列偏好实际上非常非常缓慢,因为写入闪存RAM有时会花费比预期更长的时间。出于这个原因,当我写入首选项时,我通常会启动一个新线程来完成它。
但我的建议是......使用数据库Sqlite来存储传入的消息,并将它们放在内容提供者后面。
谢谢,我会阅读关于 – Erik 2011-04-02 11:14:15
一定要使用Content Provider作为Ollie C说。否则,它可能是数据库锁定,同时使用多线程数据库 – Maxim 2011-04-02 11:27:24
我刚刚阅读了有关内容提供者和数据库。 我正在与这个例子 http://thinkandroid.wordpress.com/2010/01/13/writing-your-own-contentprovider/ – Erik 2011-04-02 11:39:58