0
我在我的應用程序中有複選框,並使用共享首選項方法來保存它們,我最終將數據存儲在共享首選項中,並且能夠檢索它,但只有當應用程序不是完全關閉。Android:檢索存儲在sharedpreference中的數據,即使在關閉應用程序後
這裏是我的代碼保存我的數據
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
prefs = getApplicationContext().getSharedPreferences("preferencename", MODE_PRIVATE);
editor = prefs.edit();
editor.clear();
editor.commit();
saveArray(list, "list", getApplicationContext());
Toast.makeText(getApplicationContext(), "Save"+" "+cou, Toast.LENGTH_SHORT).show();
cou=0;
}
});
}
方法來保存它
public boolean saveArray(List<Model> list2, String arrayName, Context mContext) {
prefs = getApplicationContext().getSharedPreferences("preferencename", MODE_PRIVATE);
editor = prefs.edit();
for(int i=0;i<list2.size();i++){
if(list2.get(i).isSelected()){
editor.putString(arrayName +"."+i, "true");
cou++;
}else{ editor.putString(arrayName +"."+i, "false");}
}
return editor.commit();
}
數據檢索
try
{
adapter = new CustomAdapter(this,loadArray("list", getApplicationContext()));
}
catch(Exception e){
adapter = new CustomAdapter(this,getModel());
}
方法檢索
public List<Model> loadArray(String arrayName, Context mContext) {
prefs= getSharedPreferences("preferencename", MODE_PRIVATE);
String mp3Directory = "/Music";
String directoryPath= Environment.getExternalStorageDirectory().getAbsolutePath()+mp3Directory;
lst = getMP3Files(directoryPath);
//print in LogCat the list of .mp3:
for(int i=0;i<lst.size();i++){
list.add(new Model(lst.get(i).getName()));
if(prefs.getString(arrayName+"." +i, "")=="true")
{
list.get(i).setSelected(true);
}
else
list.get(i).setSelected(false);
}
return list;
}
}
使用services..call從那裏,當你達到關閉 – Elltz
這裏我該怎麼把這個服務,而且可以請你給我一些關於它的主意,就像一個示例程序@Elltz – ajuju
它有幫助嗎?它解決了你的問題嗎? – Elltz