我正在构建一个包含片段的应用。我不完全确定何时进行http nw调用以获取数据来填充这些片段中的组件。我有一个调用,可以获取我所有片段绘制屏幕所需的所有数据。我已经测试了异步任务获取该数据的确定但是在postExecute中我不能访问组件,除非我在片段类中,即使那样我将如何将它放在那里。
我可以做一个asyncTask并看到我的数据回来但是我把它放在哪里,我想打一次电话。
ActivityTileData.getLoginTileDataArray(getActivity());
当前返回虚拟数据,理想情况下,这将进行网络调用。
public class StaggeredGridActivityFragment extends FragmentActivity {
private static final String TAG = "StaggeredGridActivityFragment";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); //remove title bar
final FragmentManager fm = getSupportFragmentManager();
// Create the list fragment and add it as our sole content.
if (fm.findFragmentById(android.R.id.content) == null) {
final StaggeredGridFragment fragment = new StaggeredGridFragment();
fm.beginTransaction().add(android.R.id.content, fragment).commit();
}
}
private class StaggeredGridFragment extends Fragment implements
AbsListView.OnScrollListener, AbsListView.OnItemClickListener {
private StaggeredGridView mGridView;
private boolean mHasRequestedMore;
private TilesAdapter mAdapter;
private ArrayList<String> mData;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_sgv, container, false);
}
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
//Encapsulate all within a post cereate from a async task or call a blocking http call
super.onActivityCreated(savedInstanceState);
mGridView = (StaggeredGridView) getView().findViewById(R.id.grid_view);
if (savedInstanceState == null) {
final LayoutInflater layoutInflater = getActivity().getLayoutInflater();
View header = layoutInflater.inflate(R.layout.list_item_header_footer, null);
mGridView.addHeaderView(header);
}
if (mAdapter == null) {
mAdapter = new TilesAdapter(getActivity(), R.id.summary1_value);
}
if (mData == null) {
mData = ActivityTileData.getLoginTileDataArray(getActivity());
}
for (String data : mData) {
mAdapter.add(data); //Add each mData TileAdapter element to an mAdapter where it will be further broken down and used by the TileAdapter
}
mGridView.setAdapter(mAdapter);
mGridView.setOnScrollListener(this);
mGridView.setOnItemClickListener(this);
}
答案 0 :(得分:1)
我建议您在活动的onCreate中进行n / w调用,并为每个片段创建数据集,并将它们放在片段的参数中。您可以通过从bundle获取所需的数据来加载newInstance片段中的数据。我已经完成了一个这种类型的项目,它对我有用。
注意:如果数据一旦设置就不需要更改,则上述方法有效。
答案 1 :(得分:0)
不要在片段和/或活动中进行异步调用。如果这样做,您将遇到许多处理配置更改的问题(例如当用户旋转屏幕时)。根据我的经验,我通常做的是创建一个名为Loader的类(不是Android框架Loader类,这对于此目的而言是一种过度杀伤)并将AsyncTask或loader线程放在那里。从您的片段/活动中获取对该类的引用,该类应该在其onCreate()
上实现为单例(覆盖您的Application类)。然后,只要您需要,请致电loader.loadDate()
。如果要处理配置更改,请在Loader类中创建一个可观察的模式,以便片段和活动可以注册以听取加载loadFinished(data)
或loadError(error)
等事件。此外,如果您不想在每次配置更改发生时查询数据,请在加载器中设置一个包含先前加载数据的catched变量。