我想在fragment中设置一个适配器视图,从webservice获取数据。我应该在哪里执行异步任务,以便在视图加载时不会出现延迟? 我在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;
}`
答案 0 :(得分:0)
使用onActivityCreated方法调用Web服务,然后更新您的视图
答案 1 :(得分:0)
你可以这样做......
new TimeSheetTask<String, String, String>() {
@Override
protected String doInBackground(String... params) {
String j="{\"userId\":\"733894\",\"startDate\":\"24-04-2016\",\"endDate\":\"25-04-2016\"}";
return 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();
如果你想显示一些加载栏,那么你可以调用onPreExecute()方法。
希望这对你有所帮助。