我有一个应用程序,当listfragment
加载 a 时,它会加载我的自定义列表适配器,该适配器通常可以工作,但我现在正在尝试实现对象存储,这样即使应用程序关闭并重新打开,对象也会一直存在,并且是仅在用户手动删除它们时才被删除。
我正在尝试在这里实现它,但是使用这种方法,当listfragment
加载时,屏幕中央会出现一个不会消失的“加载图标”。我通过日志输出发现这是因为从未输入过try块,它之前的代码是,但是try块中的代码不是,为什么会这样?
public class MainListFragment extends ListFragment{
OnListSelectedListener mCallback;
public ObjectStorage mainObjectList = new ObjectStorage(); //creates the list of objects
SharedPreferences mPrefs;
int mCurrentPosition = -1;
// The container Activity must implement this interface so the frag can deliver messages
public interface OnListSelectedListener {
/** Called by ListFragment when a list item is selected */
public void onItemSelected(int position, String schedulename, String[] ampm, boolean[] days, int[] times, boolean vibrate);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
updateStorage();
ByteArrayInputStream byteArray = new ByteArrayInputStream(mPrefs.getString("myobject", "").getBytes());
ObjectInputStream in;
try {
in = new ObjectInputStream(byteArray);
ObjectStorage updatedStorageList = (ObjectStorage) in.readObject();
CustomListAdapter adapter = new CustomListAdapter(getActivity(),
R.layout.listview_item_row, updatedStorageList);
//setListAdapter(new ArrayAdapter<String>(getActivity(), layout, arraylist));
setListAdapter(adapter);
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void updateStorage()
{
getActivity();//used for MODE_PRIVATE
//store object list into android system
mPrefs = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor ed = mPrefs.edit();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream out;
try {
out = new ObjectOutputStream(arrayOutputStream);
out.writeObject(mainObjectList);
out.close();
arrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
ed.putString("myobject", arrayOutputStream.toString());
ed.commit();
}
}