【发布时间】:2016-09-30 14:52:48
【问题描述】:
我想在片段中设置一个适配器视图,从 web 服务获取数据。我应该在哪里执行异步任务,以免视图加载出现延迟? 我在 onAttach 和 onCreateview 中尝试过,但它没有按预期工作? `
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("oncreateview","oncreateview");
View root = inflater.inflate(R.layout.my_calendar_view, container, false);
_calendar = Calendar.getInstance(Locale.getDefault());
_calendar = Calendar.getInstance(Locale.getDefault());
month = _calendar.get(Calendar.MONTH) + 1;
year = _calendar.get(Calendar.YEAR);
String j="{\"userId\":\"733894\",\"startDate\":\"24-04-2016\",\"endDate\":\"25-04-2016\"}";
new TimeSheetTask(getActivity(),j) {
@Override
protected void onPostExecute( String result ) {
super.onPostExecute(result);
gson = new Gson();
timesheet = gson.fromJson(result, Timesheet.class);
if (timesheet != null) {
adapter = new GridCellAdapter(MyCalendarFragment.this,
R.id.calendar_day_gridcell, month, year, timesheet.getTimeSheetList());
calendarView.setAdapter(adapter);
}
}
}.execute();
prevMonth = (ImageView) root.findViewById(R.id.prevMonth);
prevMonth.setOnClickListener(this);
currentMonth = (TextView) root.findViewById(R.id.currentMonth);
currentMonth.setText(DateFormat.format(dateTemplate,
_calendar.getTime()));
nextMonth = (ImageView) root.findViewById(R.id.nextMonth);
nextMonth.setOnClickListener(this);
calendarView = (GridView) root.findViewById(R.id.calendar);
if (timesheet != null) {
adapter = new GridCellAdapter(MyCalendarFragment.this,
R.id.calendar_day_gridcell, month, year, timesheet.getTimeSheetList());
calendarView.setAdapter(adapter);
}
return root;
}`
【问题讨论】:
-
请提供一些代码:)。
-
onPostExecute 在主线程上执行,你应该反序列化你的 JSON onBackground。
标签: android android-fragments asynchronous