
我正在一个例子中,我有一个列表视图和一个使用片段的详细视图.
当我第一次打开应用程序时,我加载(从Web服务)项目列表(使用asyntask).
我想“保存”该列表,所以如果我需要回到这个活动(列表),我不需要再次执行asynctask.
哪个是“保存”此列表的更好地方? Application对象是个好地方吗?
然后,当我单击列表中的项目时,我想打开一个新活动并从该对象加载详细数据.
将该对象传递给详细活动的最佳方法是什么?
使用Application对象并从列表中获取所选项(例如,使用onItemSelectedListener中的位置参数)(如果我有一个包含应用程序对象中项目的列表)?
让我的“Item”对象实现Parcelable接口并在意图中传递整个对象?
还有其他想法吗?
谢谢,抱歉我的英语.
解决方法 如果您想保持良好的数据,sqlite是正确的选择.如果要暂时缓存数据,那么savedInstanceState Bundle就在这里.我向您展示了使用Fragment和ListVIEw的示例.
public static final String BUNDLE_CACHE = "ListFragment.BUNDLE_CACHE";private ArrayList<ListItem> mCachedData;private ListVIEw mListVIEw;private ListItemAdapter mlistadapter;@OverrIDepublic voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if ((savedInstanceState != null) && savedInstanceState.containsKey(BUNDLE_CACHE)) { this.mCachedData = savedInstanceState.getParcelableArrayList(BUNDLE_CACHE); }@OverrIDepublic 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;}@OverrIDepublic 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 dataintent.putExtra("keyItem",item); 并使用以下命令将其放入新创建的DetailsActivity中:
Bundle extras = getIntent().getExtras();if (extras !=null) { ListItem value = (ListItem) extras.getParcelable("keyItem");} 总结 以上是内存溢出为你收集整理的android – 存储状态数据的更好方式/位置(listview)全部内容,希望文章能够帮你解决android – 存储状态数据的更好方式/位置(listview)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)