我的应用程序中有复选框,并使用共享首选项方法来保存它们,我最终将数据存储在共享首选项中,并且只有在应用程序未完全关闭时才能检索它。
这是我保存数据的代码
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;
}
}
答案 0 :(得分:0)
创建一个扩展服务的类,但我不知道您的偏好,但这里有一些让您自己了解服务的one,two,three,four
public class MyBackgroundjob extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// call it here..
loadArray(String arrayName, Context mContext); //
// you can create a singleton class that will hold your data, which will be global
// to your application, and yea, now you have your stuff do your stuff
return START_STICKY;
}
// copy your retrieving method and paste the void here.. starting from this line
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;
}
}
}
顺便说一下,你从你的活动开始服务(MyBackgroundJob类),如Intent i = new Intent(activity, MyBackgroundJob.class); context.startService(i);
你的签名课可能是
public class Mysingle extends Application{
// then you create your "list" here okay make it static
static List<type> list; // and you call it by = Mysingle.list
}
是的,请与其他人一起玩..您甚至可以在服务中运行整个应用程序流程并绑定到您的活动并更新用户,利用这些内容。 AYT ..
希望我明智而清醒......