[英]Load Json accross several fragment on a ViewPager, needs of a better way
Developer advisory: The following content might hurt the sensibility of some developers, please read it at your own risks. 开发人员建议:以下内容可能会损害某些开发人员的敏感性,请自担风险阅读。
I'm beginning in Android developement / java, and my goal is to load a json from a remote rest service, and use it across 2 fragments on a ViewPager, currently i'm doing it this way (please read developer advisory :) , i just show the important part of the code here, in an algorythmic way, no need to check syntax): 我从Android开发/ Java开始,我的目标是从远程Rest服务加载json,并在ViewPager的2个片段中使用它,目前我正以这种方式进行(请阅读开发者建议:),我只是以一种算法的方式在这里显示代码的重要部分,而无需检查语法):
I declare a variable on the viewpager, that i plan to call back using getActivity from fragment 我在viewpager上声明了一个变量,计划使用片段中的getActivity进行回调
Viewpager.java Viewpager.java
public class Viewpager extends AppCompatActivity{
...
public static JSONObjInvitationParser jsonParser;
...
}
Fragment1.java Fragment1.java
public class Fragment1 extends ListFragment{
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Viewpager activity = (Viewpager) getActivity();
activity.jsonParser = CallMyRestServiceAndGetTheJSON();
populateListView(activity.jsonParser.getanOtherListArrayOfSTuff());
}
}
On the second fragment, i can't call my activy.jsonParser during onCreatView of course, otherwise i get pointerNull, my guess is that the Viewpager is Calling all the createView at once, so does the setUserVisibleHint hack. 在第二个片段上,我当然不能在onCreatView期间调用activy.jsonParser,否则我会得到pointerNull,我的猜测是Viewpager会立即调用所有createView,因此setUserVisibleHint也会被调用。
Fragment2.java Fragment2.java
public class Fragment2 extends ListFragment{
...
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
final Viewpager activity = (Viewpager) getActivity();
if (isVisibleToUser) {
System.out.println(activity.jsonParser.getListArrayOfSTuff());
populateListView(activity.jsonParser.getListArrayOfSTuff());
}
}
...
}
}
Like this, it works, and i can acutally populate my listvews on my 2 fragments calling only once the rest service, but there must be a wayyyy better way than this ugly hack :/ Unfortunately, i don't know it yet, anyone could let me know how he would implement properly that ? 这样,它就可以了,我可以在我的2个片段上手动填充listvews,只调用一次剩余服务,但是必须有一个比这种丑陋的hackyyy更好的方法:/不幸的是,我还不知道,任何人都可以让我知道他将如何正确实施?
thanks a lot in advance :) 在此先感谢:)
I often create a model class to represent JSON data. 我经常创建一个模型类来表示JSON数据。 That class implement Parcelable
interface. 该类实现Parcelable
接口。 And you can put your data to Fragment: 您可以将数据放入Fragment:
DetailsFragment f = new DetailsFragment();
Bundle args = new Bundle();
args.putParcelable("data", yourDataObject);
f.setArguments(args);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.