如果您想保持良好的数据,SQLite是正确的选择.
如果要暂时缓存数据,那么savedInstanceState Bundle就在这里.我向您展示了使用Fragment和ListView的示例.
public static final String BUNDLE_CACHE = "ListFragment.BUNDLE_CACHE";
private ArrayList mCachedData;
private ListView mListView;
private ListItemAdapter mListAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(BUNDLE_CACHE)) {
this.mCachedData = savedInstanceState.getParcelableArrayList(BUNDLE_CACHE);
}
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater,container,savedInstanceState);
LinearLayout layout = (LinearLayout) inflater.inflate(
R.layout.layout_fragment,null);
this.mListAdapter = new ListAdapter(inflater.getContext(),R.layout.item_list_topic_categories);
this.mListView = (ListView) layout.findViewById(R.id.listView);
this.mListView.setAdapter(this.mListAdapter);
this.mListView.setOnItemClickListener(this.mItemClickListener);
if (this.mCachedData == null) {
Log.d("onCreateView","I make the request");
this.downloadData();
... // After download is finished,you put somewhere:
this.mCachedData = downloadedData;
} else {
Log.d("onCreateView","Cool,the data is cached");
this.buildList(this.mCachedData);
}
return layout;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// You put the content of your list,which is this.mCachedData,in the state
outState.getParcelableArrayList(BUNDLE_CACHE,this.mCachedData);
}
我还在我的一些应用程序上使用webservices,而且当我在片段之间切换视图时,savedInstanceState对于不再执行webservice调用非常有用.
当片段视图被销毁但片段仍然存在时,将应用此案例.当再次创建视图时,它将使用缓存的数据,而不是从webservices再次下载.
要将Parcelable发送到Activity中的片段(根据biovamp的示例),您可以使用:
Bundle args = new Bundle();
args.putParcelable("keyName",parcelableObject);
fragment.setArguments(args);
在你的片段中你用它来获得你的Parcelable:
this.getArguments().getParcelable("keyName");
要创建Parcelable,请参阅本教程,例如:http://techdroid.kbeanie.com/2010/06/parcelable-how-to-do-that-in-android.html
现在,你说:
Then,when i click an item from the list i want to open a new activity
因此,如果您仍想从ListFragment创建DetailsActivity,则使用Intent发送数据:
ListItem item = ... // get your item data
intent.putExtra("keyItem",item);
并使用以下命令将其放入新创建的DetailsActivity中:
Bundle extras = getIntent().getExtras();
if (extras !=null) {
ListItem value = (ListItem) extras.getParcelable("keyItem");
}