我从SharedPreferences
List<MyObject> oList = new ArrayList<MyObject>();
// Get JSON Data from storage.
HashSet<String> oStrings = new HashSet<String>();
oStrings = (HashSet<String>) oSharedPrefs.getStringSet(IConstants.MY_OBJECT_LIST, null);
if (oStrings != null && oStrings.size() > 0)
{
Gson oGson = new Gson();
for (String strJSONObject : oStrings)
{
MyObject oObject = oGson.fromJson(strJSONObject, MyObject.class);
oList.add(oObject);
}
}
return oList;
问题是,这是在UI线程&amp;随着SharedPreferences
JSON字符串变大,这可能导致我的应用暂停几秒钟。
如何在后台加载此数据然后检索对象列表?
答案 0 :(得分:0)
您可以使用AsyncTask:
public class LoadFromShared extends AsyncTask<Void, Void, List<MyObject>>{
private OnLoadingDoneListener mListener;
public interface OnLoadingDoneListener{
public void onDone(List<MyObject> result);
}
public void setOnLoadingDoneListener(OnLoadingDoneListener listener){
this.mListener = listener;
}
@Override
protected List<MyObject> doInBackground(Void... params) {
List<MyObject> oList = new ArrayList<MyObject>();
// Get JSON Data from storage.
HashSet<String> oStrings = new HashSet<String>();
oStrings = (HashSet<String>) oSharedPrefs.getStringSet(IConstants.MY_OBJECT_LIST, null);
if (oStrings != null && oStrings.size() > 0)
{
Gson oGson = new Gson();
for (String strJSONObject : oStrings)
{
MyObject oObject = oGson.fromJson(strJSONObject, MyObject.class);
oList.add(oObject);
}
}
return oList;
}
protected void onPostExecute(List<MyObject> result) {
if(mListener!=null={
mListener.onDone(result);
}
};
}
然后在你的主要:
LoadFromShared loader = new LoadFromShared();
loader.setOnLoadingDoneListener(new OnLoadingDoneListener(){
@Override
onDone(List<MyObject> result){
//do your stuff here
}
};);
loader.execute();
无法保证正确输入;)