code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.TracksFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.ViewGroup; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment}, a * {@link SessionsFragment}, and {@link SessionDetailFragment}. * * This activity requires API level 11 or greater because {@link TracksDropdownFragment} requires * API level 11. */ public class SessionsMultiPaneActivity extends BaseMultiPaneActivity { private TracksDropdownFragment mTracksDropdownFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sessions); Intent intent = new Intent(); intent.setData(ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_SESSIONS); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mTracksDropdownFragment.reloadFromArguments(intentToFragmentArguments(intent)); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_session_detail); if (detailContainer != null && detailContainer.getChildCount() > 0) { findViewById(R.id.fragment_container_session_detail).setBackgroundColor(0xffffffff); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (SessionsActivity.class.getName().equals(activityClassName)) { return new FragmentReplaceInfo( SessionsFragment.class, "sessions", R.id.fragment_container_sessions); } else if (SessionDetailActivity.class.getName().equals(activityClassName)) { findViewById(R.id.fragment_container_session_detail).setBackgroundColor( 0xffffffff); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_session_detail); } return null; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.TracksFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorsActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.ViewGroup; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment}, a * {@link VendorsFragment}, and {@link VendorDetailFragment}. This activity is very similar in * function to {@link SessionsMultiPaneActivity}. * * This activity requires API level 11 or greater because {@link TracksDropdownFragment} requires * API level 11. */ public class VendorsMultiPaneActivity extends BaseMultiPaneActivity { private TracksDropdownFragment mTracksDropdownFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.activity_vendors); Intent intent = new Intent(); intent.setData(ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_VENDORS); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mTracksDropdownFragment.reloadFromArguments(intentToFragmentArguments(intent)); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_vendor_detail); if (detailContainer != null && detailContainer.getChildCount() > 0) { findViewById(R.id.fragment_container_vendor_detail).setBackgroundColor(0xffffffff); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (VendorsActivity.class.getName().equals(activityClassName)) { return new FragmentReplaceInfo( VendorsFragment.class, "vendors", R.id.fragment_container_vendors); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { findViewById(R.id.fragment_container_vendor_detail).setBackgroundColor( 0xffffffff); return new FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_vendor_detail); } return null; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.TracksAdapter; import com.google.android.apps.iosched.ui.TracksFragment; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; /** * A tablet-specific fragment that is a giant {@link android.widget.Spinner}-like widget. It shows * a {@link ListPopupWindow} containing a list of tracks, using {@link TracksAdapter}. * * Requires API level 11 or later since {@link ListPopupWindow} is API level 11+. */ public class TracksDropdownFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, AdapterView.OnItemClickListener, PopupWindow.OnDismissListener { public static final String EXTRA_NEXT_TYPE = "com.google.android.iosched.extra.NEXT_TYPE"; public static final String NEXT_TYPE_SESSIONS = "sessions"; public static final String NEXT_TYPE_VENDORS = "vendors"; private boolean mAutoloadTarget = true; private Cursor mCursor; private TracksAdapter mAdapter; private String mNextType; private ListPopupWindow mListPopupWindow; private ViewGroup mRootView; private TextView mTitle; private TextView mAbstract; private NotifyingAsyncQueryHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mAdapter = new TracksAdapter(getActivity()); if (savedInstanceState != null) { // Prevent auto-load behavior on orientation change. mAutoloadTarget = false; } reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments if (mListPopupWindow != null) { mListPopupWindow.setAdapter(null); } if (mCursor != null) { getActivity().stopManagingCursor(mCursor); mCursor = null; } mHandler.cancelOperation(TracksAdapter.TracksQuery._TOKEN); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri tracksUri = intent.getData(); if (tracksUri == null) { return; } mNextType = intent.getStringExtra(EXTRA_NEXT_TYPE); // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; if (TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType)) { // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; } else if (TracksFragment.NEXT_TYPE_VENDORS.equals(mNextType)) { // Only show tracks with at least one vendor projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT; selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0"; } // Start background query to load tracks mHandler.startQuery(TracksAdapter.TracksQuery._TOKEN, null, tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_tracks_dropdown, null); mTitle = (TextView) mRootView.findViewById(R.id.track_title); mAbstract = (TextView) mRootView.findViewById(R.id.track_abstract); mRootView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mListPopupWindow = new ListPopupWindow(getActivity()); mListPopupWindow.setAdapter(mAdapter); mListPopupWindow.setModal(true); mListPopupWindow.setContentWidth(400); mListPopupWindow.setAnchorView(mRootView); mListPopupWindow.setOnItemClickListener(TracksDropdownFragment.this); mListPopupWindow.show(); mListPopupWindow.setOnDismissListener(TracksDropdownFragment.this); } }); return mRootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null || cursor == null) { return; } mCursor = cursor; getActivity().startManagingCursor(mCursor); // If there was a last-opened track, load it. Otherwise load the first track. cursor.moveToFirst(); String lastTrackID = UIUtils.getLastUsedTrackID(getActivity()); if (lastTrackID != null) { while (!cursor.isAfterLast()) { if (lastTrackID.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) { break; } cursor.moveToNext(); } if (cursor.isAfterLast()) { loadTrack(null, mAutoloadTarget); } else { loadTrack(cursor, mAutoloadTarget); } } else { loadTrack(null, mAutoloadTarget); } mAdapter.setHasAllItem(true); mAdapter.setIsSessions(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType)); mAdapter.changeCursor(mCursor); } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); loadTrack(cursor, true); if (cursor != null) { UIUtils.setLastUsedTrackID(getActivity(), cursor.getString( TracksAdapter.TracksQuery.TRACK_ID)); } else { UIUtils.setLastUsedTrackID(getActivity(), ScheduleContract.Tracks.ALL_TRACK_ID); } if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } public void loadTrack(Cursor cursor, boolean loadTargetFragment) { final String trackId; final int trackColor; final Resources res = getResources(); if (cursor != null) { trackColor = cursor.getInt(TracksAdapter.TracksQuery.TRACK_COLOR); trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); mTitle.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_NAME)); mAbstract.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_ABSTRACT)); } else { trackColor = res.getColor(R.color.all_track_color); trackId = ScheduleContract.Tracks.ALL_TRACK_ID; mTitle.setText(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType) ? R.string.all_sessions_title : R.string.all_sandbox_title); mAbstract.setText(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType) ? R.string.all_sessions_subtitle : R.string.all_sandbox_subtitle); } boolean isDark = UIUtils.isColorDark(trackColor); mRootView.setBackgroundColor(trackColor); if (isDark) { mTitle.setTextColor(res.getColor(R.color.body_text_1_inverse)); mAbstract.setTextColor(res.getColor(R.color.body_text_2_inverse)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_light); } else { mTitle.setTextColor(res.getColor(R.color.body_text_1)); mAbstract.setTextColor(res.getColor(R.color.body_text_2)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_dark); } if (loadTargetFragment) { final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.putExtra(SessionDetailFragment.EXTRA_TRACK, trackUri); if (NEXT_TYPE_SESSIONS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Sessions.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildSessionsUri(trackId)); } } else if (NEXT_TYPE_VENDORS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Vendors.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildVendorsUri(trackId)); } } ((BaseActivity) getActivity()).openActivityOrFragment(intent); } } public void onDismiss() { mListPopupWindow = null; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import android.app.FragmentBreadCrumbs; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.ViewGroup; /** * A multi-pane activity, where the primary navigation pane is a * {@link com.google.android.apps.iosched.ui.ScheduleFragment}, that * shows {@link SessionsFragment} and {@link SessionDetailFragment} as popups. * * This activity requires API level 11 or greater because of its use of {@link FragmentBreadCrumbs}. */ public class ScheduleMultiPaneActivity extends BaseMultiPaneActivity implements View.OnClickListener, FragmentManager.OnBackStackChangedListener { private FragmentManager mFragmentManager; private FragmentBreadCrumbs mFragmentBreadCrumbs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_schedule); mFragmentManager = getSupportFragmentManager(); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mFragmentManager.addOnBackStackChangedListener(this); updateBreadCrumb(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_schedule_detail); if (detailContainer != null && detailContainer.getChildCount() > 0) { findViewById(R.id.fragment_container_schedule_detail).setBackgroundColor(0); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (SessionsActivity.class.getName().equals(activityClassName)) { getSupportFragmentManager().popBackStack(); findViewById(R.id.fragment_container_schedule_detail).setBackgroundColor(0); return new FragmentReplaceInfo( SessionsFragment.class, "sessions", R.id.fragment_container_schedule_detail); } else if (SessionDetailActivity.class.getName().equals(activityClassName)) { findViewById(R.id.fragment_container_schedule_detail).setBackgroundColor(0); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_schedule_detail); } return null; } @Override protected void onBeforeCommitReplaceFragment(FragmentManager fm, FragmentTransaction ft, Fragment fragment) { super.onBeforeCommitReplaceFragment(fm, ft, fragment); if (fragment instanceof SessionDetailFragment) { ft.addToBackStack(null); } else if (fragment instanceof SessionsFragment) { fm.popBackStack(); } updateBreadCrumb(); } /** * Handler for the breadcrumb parent. */ public void onClick(View view) { mFragmentManager.popBackStack(); } public void onBackStackChanged() { updateBreadCrumb(); } public void updateBreadCrumb() { final String title = getString(R.string.title_sessions); final String detailTitle = getString(R.string.title_session_detail); if (mFragmentManager.getBackStackEntryCount() >= 1) { mFragmentBreadCrumbs.setParentTitle(title, title, this); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(title, title); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorsActivity; import android.app.FragmentBreadCrumbs; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; /** * A multi-pane activity, where the primary navigation pane is a {@link MapFragment}, that shows * {@link SessionsFragment}, {@link SessionDetailFragment}, {@link VendorsFragment}, and * {@link VendorDetailFragment} as popups. * * This activity requires API level 11 or greater because of its use of {@link FragmentBreadCrumbs}. */ public class MapMultiPaneActivity extends BaseMultiPaneActivity implements View.OnClickListener, FragmentManager.OnBackStackChangedListener { private static final int POPUP_TYPE_SESSIONS = 1; private static final int POPUP_TYPE_VENDORS = 2; private int mPopupType = -1; private boolean mPauseBackStackWatcher = false; private FragmentManager mFragmentManager; private FragmentBreadCrumbs mFragmentBreadCrumbs; private MapFragment mMapFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); mFragmentManager = getSupportFragmentManager(); mFragmentManager.addOnBackStackChangedListener(this); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mMapFragment = (MapFragment) mFragmentManager.findFragmentByTag("map"); if (mMapFragment == null) { mMapFragment = new MapFragment(); mMapFragment.setArguments(intentToFragmentArguments(getIntent())); mFragmentManager.beginTransaction() .add(R.id.fragment_container_map, mMapFragment, "map") .commit(); } findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { clearBackStack(getSupportFragmentManager()); } }); updateBreadCrumb(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (SessionsActivity.class.getName().equals(activityClassName)) { clearBackStack(getSupportFragmentManager()); mPopupType = POPUP_TYPE_SESSIONS; showHideDetailAndPan(true); return new FragmentReplaceInfo( SessionsFragment.class, "sessions", R.id.fragment_container_map_detail); } else if (SessionDetailActivity.class.getName().equals(activityClassName)) { mPopupType = POPUP_TYPE_SESSIONS; showHideDetailAndPan(true); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_map_detail); } else if (VendorsActivity.class.getName().equals(activityClassName)) { clearBackStack(getSupportFragmentManager()); mPopupType = POPUP_TYPE_VENDORS; showHideDetailAndPan(true); return new FragmentReplaceInfo( VendorsFragment.class, "vendors", R.id.fragment_container_map_detail); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { mPopupType = POPUP_TYPE_VENDORS; showHideDetailAndPan(true); return new FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_map_detail); } return null; } @Override protected void onBeforeCommitReplaceFragment(FragmentManager fm, FragmentTransaction ft, Fragment fragment) { super.onBeforeCommitReplaceFragment(fm, ft, fragment); if (fragment instanceof SessionsFragment || fragment instanceof VendorsFragment) { mPauseBackStackWatcher = true; clearBackStack(fm); mPauseBackStackWatcher = false; } ft.addToBackStack(null); updateBreadCrumb(); } /** * Handler for the breadcrumb parent. */ public void onClick(View view) { mFragmentManager.popBackStack(); } private void clearBackStack(FragmentManager fm) { while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } } public void onBackStackChanged() { if (mPauseBackStackWatcher) { return; } if (mFragmentManager.getBackStackEntryCount() == 0) { showHideDetailAndPan(false); } updateBreadCrumb(); } private void showHideDetailAndPan(boolean show) { View detailPopup = findViewById(R.id.map_detail_popup); if (show != (detailPopup.getVisibility() == View.VISIBLE)) { detailPopup.setVisibility(show ? View.VISIBLE : View.GONE); mMapFragment.panLeft(show ? 0.25f : -0.25f); } } public void updateBreadCrumb() { final String title = (mPopupType == POPUP_TYPE_SESSIONS) ? getString(R.string.title_sessions) : getString(R.string.title_vendors); final String detailTitle = (mPopupType == POPUP_TYPE_SESSIONS) ? getString(R.string.title_session_detail) : getString(R.string.title_vendor_detail); if (mFragmentManager.getBackStackEntryCount() >= 2) { mFragmentBreadCrumbs.setParentTitle(title, title, this); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(title, title); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.SessionsFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class SessionsActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new SessionsFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.ScheduleFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class ScheduleActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new ScheduleFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.MapFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class MapActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new MapFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.VendorDetailFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class VendorDetailActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new VendorDetailFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.TracksFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class TracksActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new TracksFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class SessionDetailActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new SessionDetailFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.VendorsFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class VendorsActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new VendorsFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; /** * A simple {@link ListFragment} that renders a list of tracks with available sessions or vendors * (depending on {@link TracksFragment#EXTRA_NEXT_TYPE}) using a {@link TracksAdapter}. */ public class TracksFragment extends ListFragment implements NotifyingAsyncQueryHandler.AsyncQueryListener { public static final String EXTRA_NEXT_TYPE = "com.google.android.iosched.extra.NEXT_TYPE"; public static final String NEXT_TYPE_SESSIONS = "sessions"; public static final String NEXT_TYPE_VENDORS = "vendors"; private TracksAdapter mAdapter; private NotifyingAsyncQueryHandler mHandler; private String mNextType; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); final Uri tracksUri = intent.getData(); mNextType = intent.getStringExtra(EXTRA_NEXT_TYPE); mAdapter = new TracksAdapter(getActivity()); setListAdapter(mAdapter); // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; if (NEXT_TYPE_SESSIONS.equals(mNextType)) { // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; AnalyticsUtils.getInstance(getActivity()).trackPageView("/Tracks"); } else if (NEXT_TYPE_VENDORS.equals(mNextType)) { // Only show tracks with at least one vendor projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT; selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0"; AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sandbox"); } // Start background query to load tracks mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mHandler.startQuery(tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_list_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); return root; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } getActivity().startManagingCursor(cursor); mAdapter.setHasAllItem(true); mAdapter.setIsSessions(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType)); mAdapter.changeCursor(cursor); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); final String trackId; if (cursor != null) { trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); } else { trackId = ScheduleContract.Tracks.ALL_TRACK_ID; } final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.putExtra(SessionDetailFragment.EXTRA_TRACK, trackUri); if (NEXT_TYPE_SESSIONS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Sessions.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildSessionsUri(trackId)); } } else if (NEXT_TYPE_VENDORS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Vendors.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildVendorsUri(trackId)); } } ((BaseActivity) getActivity()).openActivityOrFragment(intent); getListView().setItemChecked(position, true); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.os.Bundle; import android.support.v4.app.Fragment; public class TagStreamActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new TagStreamFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; /** * A {@link BaseActivity} that simply contains a single fragment. The intent used to invoke this * activity is forwarded to the fragment as arguments during fragment instantiation. Derived * activities should only need to implement * {@link com.google.android.apps.iosched.ui.BaseSinglePaneActivity#onCreatePane()}. */ public abstract class BaseSinglePaneActivity extends BaseActivity { private Fragment mFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_singlepane_empty); getActivityHelper().setupActionBar(getTitle(), 0); final String customTitle = getIntent().getStringExtra(Intent.EXTRA_TITLE); getActivityHelper().setActionBarTitle(customTitle != null ? customTitle : getTitle()); if (savedInstanceState == null) { mFragment = onCreatePane(); mFragment.setArguments(intentToFragmentArguments(getIntent())); getSupportFragmentManager().beginTransaction() .add(R.id.root_container, mFragment) .commit(); } } /** * Called in <code>onCreate</code> when the fragment constituting this activity is needed. * The returned fragment's arguments will be set to the intent used to invoke this activity. */ protected abstract Fragment onCreatePane(); }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.util.ActivityHelper; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; /** * A base activity that defers common functionality across app activities to an * {@link ActivityHelper}. This class shouldn't be used directly; instead, activities should * inherit from {@link BaseSinglePaneActivity} or {@link BaseMultiPaneActivity}. */ public abstract class BaseActivity extends FragmentActivity { final ActivityHelper mActivityHelper = ActivityHelper.createInstance(this); @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mActivityHelper.onPostCreate(savedInstanceState); } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { return mActivityHelper.onKeyLongPress(keyCode, event) || super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mActivityHelper.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu) { return mActivityHelper.onCreateOptionsMenu(menu) || super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mActivityHelper.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } /** * Returns the {@link ActivityHelper} object associated with this activity. */ protected ActivityHelper getActivityHelper() { return mActivityHelper; } /** * Takes a given intent and either starts a new activity to handle it (the default behavior), * or creates/updates a fragment (in the case of a multi-pane activity) that can handle the * intent. * * Must be called from the main (UI) thread. */ public void openActivityOrFragment(Intent intent) { // Default implementation simply calls startActivity startActivity(intent); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ public static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } /** * Converts a fragment arguments bundle into an intent. */ public static Intent fragmentArgumentsToIntent(Bundle arguments) { Intent intent = new Intent(); if (arguments == null) { return intent; } final Uri data = arguments.getParcelable("_uri"); if (data != null) { intent.setData(data); } intent.putExtras(arguments); intent.removeExtra("_uri"); return intent; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.drawable.ColorDrawable; import android.provider.BaseColumns; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; /** * A {@link android.widget.CursorAdapter} that renders a {@link TracksQuery}. */ public class TracksAdapter extends CursorAdapter { private static final int ALL_ITEM_ID = Integer.MAX_VALUE; private Activity mActivity; private boolean mHasAllItem; private int mPositionDisplacement; private boolean mIsSessions = true; public TracksAdapter(Activity activity) { super(activity, null); mActivity = activity; } public void setHasAllItem(boolean hasAllItem) { mHasAllItem = hasAllItem; mPositionDisplacement = mHasAllItem ? 1 : 0; } public void setIsSessions(boolean isSessions) { mIsSessions = isSessions; } @Override public int getCount() { return super.getCount() + mPositionDisplacement; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (mHasAllItem && position == 0) { if (convertView == null) { convertView = mActivity.getLayoutInflater().inflate( R.layout.list_item_track, parent, false); } // Custom binding for the first item ((TextView) convertView.findViewById(android.R.id.text1)).setText( "(" + mActivity.getResources().getString(mIsSessions ? R.string.all_sessions_title : R.string.all_sandbox_title) + ")"); convertView.findViewById(android.R.id.icon1).setVisibility(View.INVISIBLE); return convertView; } return super.getView(position - mPositionDisplacement, convertView, parent); } @Override public Object getItem(int position) { if (mHasAllItem && position == 0) { return null; } return super.getItem(position - mPositionDisplacement); } @Override public long getItemId(int position) { if (mHasAllItem && position == 0) { return ALL_ITEM_ID; } return super.getItemId(position - mPositionDisplacement); } @Override public boolean isEnabled(int position) { if (mHasAllItem && position == 0) { return true; } return super.isEnabled(position - mPositionDisplacement); } @Override public int getViewTypeCount() { // Add an item type for the "All" view. return super.getViewTypeCount() + 1; } @Override public int getItemViewType(int position) { if (mHasAllItem && position == 0) { return getViewTypeCount() - 1; } return super.getItemViewType(position - mPositionDisplacement); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mActivity.getLayoutInflater().inflate(R.layout.list_item_track, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { final TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText(cursor.getString(TracksQuery.TRACK_NAME)); // Assign track color to visible block final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon1); iconView.setImageDrawable(new ColorDrawable(cursor.getInt(TracksQuery.TRACK_COLOR))); } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ public interface TracksQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, }; String[] PROJECTION_WITH_SESSIONS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.SESSIONS_COUNT, }; String[] PROJECTION_WITH_VENDORS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.VENDORS_COUNT, }; int _ID = 0; int TRACK_ID = 1; int TRACK_NAME = 2; int TRACK_ABSTRACT = 3; int TRACK_COLOR = 4; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * ATTENTION: Consider using the 'ViewPager' widget, available in the * Android Compatibility Package, r3: * * http://developer.android.com/sdk/compatibility-library.html */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.util.MotionEventUtils; import com.google.android.apps.iosched.util.ReflectionUtils; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.Scroller; import java.util.ArrayList; /** * A {@link android.view.ViewGroup} that shows one child at a time, allowing the user to swipe * horizontally to page between other child views. Based on <code>Workspace.java</code> in the * <code>Launcher.git</code> AOSP project. * * An improved version of this UI widget named 'ViewPager' is now available in the * <a href="http://developer.android.com/sdk/compatibility-library.html">Android Compatibility * Package, r3</a>. */ public class Workspace extends ViewGroup { private static final String TAG = "Workspace"; private static final int INVALID_SCREEN = -1; /** * The velocity at which a fling gesture will cause us to snap to the next screen */ private static final int SNAP_VELOCITY = 500; /** * The user needs to drag at least this much for it to be considered a fling gesture. This * reduces the chance of a random twitch sending the user to the next screen. */ // TODO: refactor private static final int MIN_LENGTH_FOR_FLING = 100; private int mDefaultScreen; private boolean mFirstLayout = true; private boolean mHasLaidOut = false; private int mCurrentScreen; private int mNextScreen = INVALID_SCREEN; private Scroller mScroller; private VelocityTracker mVelocityTracker; /** * X position of the active pointer when it was first pressed down. */ private float mDownMotionX; /** * Y position of the active pointer when it was first pressed down. */ private float mDownMotionY; /** * This view's X scroll offset when the active pointer was first pressed down. */ private int mDownScrollX; private final static int TOUCH_STATE_REST = 0; private final static int TOUCH_STATE_SCROLLING = 1; private int mTouchState = TOUCH_STATE_REST; private OnLongClickListener mLongClickListener; private boolean mAllowLongPress = true; private int mTouchSlop; private int mPagingTouchSlop; private int mMaximumVelocity; private static final int INVALID_POINTER = -1; private int mActivePointerId = INVALID_POINTER; private Drawable mSeparatorDrawable; private OnScreenChangeListener mOnScreenChangeListener; private OnScrollListener mOnScrollListener; private boolean mLocked; private int mDeferredScreenChange = -1; private boolean mDeferredScreenChangeFast = false; private boolean mDeferredNotify = false; private boolean mIgnoreChildFocusRequests; private boolean mIsVerbose = false; public interface OnScreenChangeListener { void onScreenChanged(View newScreen, int newScreenIndex); void onScreenChanging(View newScreen, int newScreenIndex); } public interface OnScrollListener { void onScroll(float screenFraction); } /** * Used to inflate the com.google.android.ext.workspace.Workspace from XML. * * @param context The application's context. * @param attrs The attributes set containing the com.google.android.ext.workspace.Workspace's * customization values. */ public Workspace(Context context, AttributeSet attrs) { super(context, attrs); mDefaultScreen = 0; mLocked = false; setHapticFeedbackEnabled(false); initWorkspace(); mIsVerbose = Log.isLoggable(TAG, Log.VERBOSE); } /** * Initializes various states for this workspace. */ private void initWorkspace() { mScroller = new Scroller(getContext()); mCurrentScreen = mDefaultScreen; final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchSlop = configuration.getScaledTouchSlop(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); mPagingTouchSlop = ReflectionUtils.callWithDefault(configuration, "getScaledPagingTouchSlop", mTouchSlop * 2); } /** * Returns the index of the currently displayed screen. */ int getCurrentScreen() { return mCurrentScreen; } /** * Returns the number of screens currently contained in this Workspace. */ int getScreenCount() { int childCount = getChildCount(); if (mSeparatorDrawable != null) { return (childCount + 1) / 2; } return childCount; } View getScreenAt(int index) { if (mSeparatorDrawable == null) { return getChildAt(index); } return getChildAt(index * 2); } int getScrollWidth() { int w = getWidth(); if (mSeparatorDrawable != null) { w += mSeparatorDrawable.getIntrinsicWidth(); } return w; } void handleScreenChangeCompletion(int currentScreen) { mCurrentScreen = currentScreen; View screen = getScreenAt(mCurrentScreen); //screen.requestFocus(); try { ReflectionUtils.tryInvoke(screen, "dispatchDisplayHint", new Class[]{int.class}, View.VISIBLE); invalidate(); } catch (NullPointerException e) { Log.e(TAG, "Caught NullPointerException", e); } notifyScreenChangeListener(mCurrentScreen, true); } void notifyScreenChangeListener(int whichScreen, boolean changeComplete) { if (mOnScreenChangeListener != null) { if (changeComplete) mOnScreenChangeListener.onScreenChanged(getScreenAt(whichScreen), whichScreen); else mOnScreenChangeListener.onScreenChanging(getScreenAt(whichScreen), whichScreen); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } /** * Registers the specified listener on each screen contained in this workspace. * * @param listener The listener used to respond to long clicks. */ @Override public void setOnLongClickListener(OnLongClickListener listener) { mLongClickListener = listener; final int count = getScreenCount(); for (int i = 0; i < count; i++) { getScreenAt(i).setOnLongClickListener(listener); } } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } postInvalidate(); } else if (mNextScreen != INVALID_SCREEN) { // The scroller has finished. handleScreenChangeCompletion(Math.max(0, Math.min(mNextScreen, getScreenCount() - 1))); mNextScreen = INVALID_SCREEN; } } @Override protected void dispatchDraw(Canvas canvas) { boolean restore = false; int restoreCount = 0; // ViewGroup.dispatchDraw() supports many features we don't need: // clip to padding, layout animation, animation listener, disappearing // children, etc. The following implementation attempts to fast-track // the drawing dispatch by drawing only what we know needs to be drawn. boolean fastDraw = mTouchState != TOUCH_STATE_SCROLLING && mNextScreen == INVALID_SCREEN; // If we are not scrolling or flinging, draw only the current screen if (fastDraw) { if (getScreenAt(mCurrentScreen) != null) { drawChild(canvas, getScreenAt(mCurrentScreen), getDrawingTime()); } } else { final long drawingTime = getDrawingTime(); // If we are flinging, draw only the current screen and the target screen if (mNextScreen >= 0 && mNextScreen < getScreenCount() && Math.abs(mCurrentScreen - mNextScreen) == 1) { drawChild(canvas, getScreenAt(mCurrentScreen), drawingTime); drawChild(canvas, getScreenAt(mNextScreen), drawingTime); } else { // If we are scrolling, draw all of our children final int count = getChildCount(); for (int i = 0; i < count; i++) { drawChild(canvas, getChildAt(i), drawingTime); } } } if (restore) { canvas.restoreToCount(restoreCount); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // The children are given the same width and height as the workspace final int count = getChildCount(); for (int i = 0; i < count; i++) { if (mSeparatorDrawable != null && (i & 1) == 1) { // separator getChildAt(i).measure(mSeparatorDrawable.getIntrinsicWidth(), heightMeasureSpec); } else { getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec); } } if (mFirstLayout) { setHorizontalScrollBarEnabled(false); int width = MeasureSpec.getSize(widthMeasureSpec); if (mSeparatorDrawable != null) { width += mSeparatorDrawable.getIntrinsicWidth(); } scrollTo(mCurrentScreen * width, 0); setHorizontalScrollBarEnabled(true); mFirstLayout = false; } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int childLeft = 0; final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != View.GONE) { final int childWidth = child.getMeasuredWidth(); child.layout(childLeft, 0, childLeft + childWidth, child.getMeasuredHeight()); childLeft += childWidth; } } mHasLaidOut = true; if (mDeferredScreenChange >= 0) { snapToScreen(mDeferredScreenChange, mDeferredScreenChangeFast, mDeferredNotify); mDeferredScreenChange = -1; mDeferredScreenChangeFast = false; } } @Override public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { int screen = indexOfChild(child); if (mIgnoreChildFocusRequests && !mScroller.isFinished()) { Log.w(TAG, "Ignoring child focus request: request " + mCurrentScreen + " -> " + screen); return false; } if (screen != mCurrentScreen || !mScroller.isFinished()) { snapToScreen(screen); return true; } return false; } @Override protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { int focusableScreen; if (mNextScreen != INVALID_SCREEN) { focusableScreen = mNextScreen; } else { focusableScreen = mCurrentScreen; } View v = getScreenAt(focusableScreen); if (v != null) { return v.requestFocus(direction, previouslyFocusedRect); } return false; } @Override public boolean dispatchUnhandledMove(View focused, int direction) { if (direction == View.FOCUS_LEFT) { if (getCurrentScreen() > 0) { snapToScreen(getCurrentScreen() - 1); return true; } } else if (direction == View.FOCUS_RIGHT) { if (getCurrentScreen() < getScreenCount() - 1) { snapToScreen(getCurrentScreen() + 1); return true; } } return super.dispatchUnhandledMove(focused, direction); } @Override public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { View focusableSourceScreen = null; if (mCurrentScreen >= 0 && mCurrentScreen < getScreenCount()) { focusableSourceScreen = getScreenAt(mCurrentScreen); } if (direction == View.FOCUS_LEFT) { if (mCurrentScreen > 0) { focusableSourceScreen = getScreenAt(mCurrentScreen - 1); } } else if (direction == View.FOCUS_RIGHT) { if (mCurrentScreen < getScreenCount() - 1) { focusableSourceScreen = getScreenAt(mCurrentScreen + 1); } } if (focusableSourceScreen != null) { focusableSourceScreen.addFocusables(views, direction, focusableMode); } } /** * If one of our descendant views decides that it could be focused now, only pass that along if * it's on the current screen. * * This happens when live folders requery, and if they're off screen, they end up calling * requestFocus, which pulls it on screen. */ @Override public void focusableViewAvailable(View focused) { View current = getScreenAt(mCurrentScreen); View v = focused; ViewParent parent; while (true) { if (v == current) { super.focusableViewAvailable(focused); return; } if (v == this) { return; } parent = v.getParent(); if (parent instanceof View) { v = (View) v.getParent(); } else { return; } } } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* * This method JUST determines whether we want to intercept the motion. * If we return true, onTouchEvent will be called and we do the actual * scrolling there. */ // Begin tracking velocity even before we have intercepted touch events. if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); /* * Shortcut the most recurring case: the user is in the dragging * state and he is moving his finger. We want to intercept this * motion. */ final int action = ev.getAction(); if (mIsVerbose) { Log.v(TAG, "onInterceptTouchEvent: " + (ev.getAction() & MotionEventUtils.ACTION_MASK)); } if (((action & MotionEventUtils.ACTION_MASK) == MotionEvent.ACTION_MOVE) && (mTouchState == TOUCH_STATE_SCROLLING)) { if (mIsVerbose) { Log.v(TAG, "Intercepting touch events"); } return true; } switch (action & MotionEventUtils.ACTION_MASK) { case MotionEvent.ACTION_MOVE: { if (mLocked) { // we're locked on the current screen, don't allow moving break; } /* * Locally do absolute value. mDownMotionX is set to the y value * of the down event. */ final int pointerIndex = MotionEventUtils.findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final float y = MotionEventUtils.getY(ev, pointerIndex); final int xDiff = (int) Math.abs(x - mDownMotionX); final int yDiff = (int) Math.abs(y - mDownMotionY); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > mTouchSlop; boolean yMoved = yDiff > mTouchSlop; if (xMoved || yMoved) { if (xPaged) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; } // Either way, cancel any pending longpress if (mAllowLongPress) { mAllowLongPress = false; // Try canceling the long press. It could also have been scheduled // by a distant descendant, so use the mAllowLongPress flag to block // everything final View currentScreen = getScreenAt(mCurrentScreen); if (currentScreen != null) { currentScreen.cancelLongPress(); } } } break; } case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); // Remember location of down touch mDownMotionX = x; mDownMotionY = y; mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, 0); mAllowLongPress = true; /* * If being flinged and user touches the screen, initiate drag; * otherwise don't. mScroller.isFinished should be false when * being flinged. */ mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_SCROLLING; break; } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_UP: // Release the drag mTouchState = TOUCH_STATE_REST; mAllowLongPress = false; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; case MotionEventUtils.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } /* * The only time we want to intercept motion events is if we are in the * drag mode. */ boolean intercept = mTouchState != TOUCH_STATE_REST; if (mIsVerbose) { Log.v(TAG, "Intercepting touch events: " + Boolean.toString(intercept)); } return intercept; } void onSecondaryPointerUp(MotionEvent ev) { final int pointerIndex = (ev.getAction() & MotionEventUtils.ACTION_POINTER_INDEX_MASK) >> MotionEventUtils.ACTION_POINTER_INDEX_SHIFT; final int pointerId = MotionEventUtils.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. // TODO: Make this decision more intelligent. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mDownMotionX = MotionEventUtils.getX(ev, newPointerIndex); mDownMotionX = MotionEventUtils.getY(ev, newPointerIndex); mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } @Override public void requestChildFocus(View child, View focused) { super.requestChildFocus(child, focused); int screen = indexOfChild(child); if (mSeparatorDrawable != null) { screen /= 2; } if (screen >= 0 && !isInTouchMode()) { snapToScreen(screen); } } @Override public boolean onTouchEvent(MotionEvent ev) { if (mIsVerbose) { Log.v(TAG, "onTouchEvent: " + (ev.getAction() & MotionEventUtils.ACTION_MASK)); } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); final int action = ev.getAction(); switch (action & MotionEventUtils.ACTION_MASK) { case MotionEvent.ACTION_DOWN: // If being flinged and user touches, stop the fling. isFinished // will be false if being flinged. if (!mScroller.isFinished()) { mScroller.abortAnimation(); } // Remember where the motion event started mDownMotionX = ev.getX(); mDownMotionY = ev.getY(); mDownScrollX = getScrollX(); mActivePointerId = MotionEventUtils.getPointerId(ev, 0); break; case MotionEvent.ACTION_MOVE: if (mIsVerbose) { Log.v(TAG, "mTouchState=" + mTouchState); } if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = MotionEventUtils .findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final View lastChild = getChildAt(getChildCount() - 1); final int maxScrollX = lastChild.getRight() - getWidth(); scrollTo(Math.max(0, Math.min(maxScrollX, (int)(mDownScrollX + mDownMotionX - x ))), 0); if (mOnScrollListener != null) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } else if (mTouchState == TOUCH_STATE_REST) { if (mLocked) { // we're locked on the current screen, don't allow moving break; } /* * Locally do absolute value. mLastMotionX is set to the y value * of the down event. */ final int pointerIndex = MotionEventUtils.findPointerIndex(ev, mActivePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final float y = MotionEventUtils.getY(ev, pointerIndex); final int xDiff = (int) Math.abs(x - mDownMotionX); final int yDiff = (int) Math.abs(y - mDownMotionY); boolean xPaged = xDiff > mPagingTouchSlop; boolean xMoved = xDiff > mTouchSlop; boolean yMoved = yDiff > mTouchSlop; if (xMoved || yMoved) { if (xPaged) { // Scroll if the user moved far enough along the X axis mTouchState = TOUCH_STATE_SCROLLING; } // Either way, cancel any pending longpress if (mAllowLongPress) { mAllowLongPress = false; // Try canceling the long press. It could also have been scheduled // by a distant descendant, so use the mAllowLongPress flag to block // everything final View currentScreen = getScreenAt(mCurrentScreen); if (currentScreen != null) { currentScreen.cancelLongPress(); } } } } break; case MotionEvent.ACTION_UP: if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = MotionEventUtils.findPointerIndex(ev, activePointerId); final float x = MotionEventUtils.getX(ev, pointerIndex); final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); //TODO(minsdk8): int velocityX = (int) MotionEventUtils.getXVelocity(velocityTracker, activePointerId); int velocityX = (int) velocityTracker.getXVelocity(); boolean isFling = Math.abs(mDownMotionX - x) > MIN_LENGTH_FOR_FLING; final float scrolledPos = getCurrentScreenFraction(); final int whichScreen = Math.round(scrolledPos); if (isFling && mIsVerbose) { Log.v(TAG, "isFling, whichScreen=" + whichScreen + " scrolledPos=" + scrolledPos + " mCurrentScreen=" + mCurrentScreen + " velocityX=" + velocityX); } if (isFling && velocityX > SNAP_VELOCITY && mCurrentScreen > 0) { // Fling hard enough to move left // Don't fling across more than one screen at a time. final int bound = scrolledPos <= whichScreen ? mCurrentScreen - 1 : mCurrentScreen; snapToScreen(Math.min(whichScreen, bound)); } else if (isFling && velocityX < -SNAP_VELOCITY && mCurrentScreen < getChildCount() - 1) { // Fling hard enough to move right // Don't fling across more than one screen at a time. final int bound = scrolledPos >= whichScreen ? mCurrentScreen + 1 : mCurrentScreen; snapToScreen(Math.max(whichScreen, bound)); } else { snapToDestination(); } } else { performClick(); } mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; // Intentially fall through to cancel case MotionEvent.ACTION_CANCEL: mTouchState = TOUCH_STATE_REST; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } break; case MotionEventUtils.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } return true; } /** * Returns the current scroll position as a float value from 0 to the number of screens. * Fractional values indicate that the user is mid-scroll or mid-fling, and whole values * indicate that the Workspace is currently snapped to a screen. */ float getCurrentScreenFraction() { if (!mHasLaidOut) { return mCurrentScreen; } final int scrollX = getScrollX(); final int screenWidth = getWidth(); return (float) scrollX / screenWidth; } void snapToDestination() { final int screenWidth = getScrollWidth(); final int whichScreen = (getScrollX() + (screenWidth / 2)) / screenWidth; snapToScreen(whichScreen); } void snapToScreen(int whichScreen) { snapToScreen(whichScreen, false, true); } void snapToScreen(int whichScreen, boolean fast, boolean notify) { if (!mHasLaidOut) { // Can't handle scrolling until we are laid out. mDeferredScreenChange = whichScreen; mDeferredScreenChangeFast = fast; mDeferredNotify = notify; return; } if (mIsVerbose) { Log.v(TAG, "Snapping to screen: " + whichScreen); } whichScreen = Math.max(0, Math.min(whichScreen, getScreenCount() - 1)); final int screenDelta = Math.abs(whichScreen - mCurrentScreen); final boolean screenChanging = (mNextScreen != INVALID_SCREEN && mNextScreen != whichScreen) || (mCurrentScreen != whichScreen); mNextScreen = whichScreen; View focusedChild = getFocusedChild(); boolean setTabFocus = false; if (focusedChild != null && screenDelta != 0 && focusedChild == getScreenAt( mCurrentScreen)) { // clearing the focus of the child will cause focus to jump to the tabs, // which will in turn cause snapToScreen to be called again with a different // value. To prevent this, we temporarily disable the OnTabClickListener //if (mTabRow != null) { // mTabRow.setOnTabClickListener(null); //} //focusedChild.clearFocus(); //setTabRow(mTabRow); // restore the listener //setTabFocus = true; } final int newX = whichScreen * getScrollWidth(); final int sX = getScrollX(); final int delta = newX - sX; int duration = screenDelta * 300; awakenScrollBars(duration); if (duration == 0) { duration = Math.abs(delta); } if (fast) { duration = 0; } if (mNextScreen != mCurrentScreen) { // make the current listview hide its filter popup final View screenAt = getScreenAt(mCurrentScreen); if (screenAt != null) { ReflectionUtils.tryInvoke(screenAt, "dispatchDisplayHint", new Class[]{int.class}, View.INVISIBLE); } else { Log.e(TAG, "Screen at index was null. mCurrentScreen = " + mCurrentScreen); return; } // showing the filter popup for the next listview needs to be delayed // until we've fully moved to that listview, since otherwise the // popup will appear at the wrong place on the screen //removeCallbacks(mFilterWindowEnabler); //postDelayed(mFilterWindowEnabler, duration + 10); // NOTE: moved to computeScroll and handleScreenChangeCompletion() } if (!mScroller.isFinished()) { mScroller.abortAnimation(); } mScroller.startScroll(sX, 0, delta, 0, duration); if (screenChanging && notify) { notifyScreenChangeListener(mNextScreen, false); } invalidate(); } @Override protected Parcelable onSaveInstanceState() { final SavedState state = new SavedState(super.onSaveInstanceState()); state.currentScreen = mCurrentScreen; return state; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); if (savedState.currentScreen != -1) { snapToScreen(savedState.currentScreen, true, true); } } /** * @return True is long presses are still allowed for the current touch */ boolean allowLongPress() { return mAllowLongPress; } /** * Register a callback to be invoked when the screen is changed, either programmatically or via * user interaction. Will automatically trigger a callback. * * @param screenChangeListener The callback. */ public void setOnScreenChangeListener(OnScreenChangeListener screenChangeListener) { setOnScreenChangeListener(screenChangeListener, true); } /** * Register a callback to be invoked when the screen is changed, either programmatically or via * user interaction. * * @param screenChangeListener The callback. * @param notifyImmediately Whether to trigger a notification immediately */ public void setOnScreenChangeListener(OnScreenChangeListener screenChangeListener, boolean notifyImmediately) { mOnScreenChangeListener = screenChangeListener; if (mOnScreenChangeListener != null && notifyImmediately) { mOnScreenChangeListener.onScreenChanged(getScreenAt(mCurrentScreen), mCurrentScreen); } } /** * Register a callback to be invoked when this Workspace is mid-scroll or mid-fling, either * due to user interaction or programmatic changes in the current screen index. * * @param scrollListener The callback. * @param notifyImmediately Whether to trigger a notification immediately */ public void setOnScrollListener(OnScrollListener scrollListener, boolean notifyImmediately) { mOnScrollListener = scrollListener; if (mOnScrollListener != null && notifyImmediately) { mOnScrollListener.onScroll(getCurrentScreenFraction()); } } /** * Scrolls to the given screen. */ public void setCurrentScreen(int screenIndex) { snapToScreen(Math.max(0, Math.min(getScreenCount() - 1, screenIndex))); } /** * Scrolls to the given screen fast (no matter how large the scroll distance is) * * @param screenIndex */ public void setCurrentScreenNow(int screenIndex) { setCurrentScreenNow(screenIndex, true); } public void setCurrentScreenNow(int screenIndex, boolean notify) { snapToScreen(Math.max(0, Math.min(getScreenCount() - 1, screenIndex)), true, notify); } /** * Scrolls to the screen adjacent to the current screen on the left, if it exists. This method * is a no-op if the Workspace is currently locked. */ public void scrollLeft() { if (mLocked) { return; } if (mScroller.isFinished()) { if (mCurrentScreen > 0) { snapToScreen(mCurrentScreen - 1); } } else { if (mNextScreen > 0) { snapToScreen(mNextScreen - 1); } } } /** * Scrolls to the screen adjacent to the current screen on the right, if it exists. This method * is a no-op if the Workspace is currently locked. */ public void scrollRight() { if (mLocked) { return; } if (mScroller.isFinished()) { if (mCurrentScreen < getChildCount() - 1) { snapToScreen(mCurrentScreen + 1); } } else { if (mNextScreen < getChildCount() - 1) { snapToScreen(mNextScreen + 1); } } } /** * If set, invocations of requestChildRectangleOnScreen() will be ignored. */ public void setIgnoreChildFocusRequests(boolean mIgnoreChildFocusRequests) { this.mIgnoreChildFocusRequests = mIgnoreChildFocusRequests; } public void markViewSelected(View v) { mCurrentScreen = indexOfChild(v); } /** * Locks the current screen, preventing users from changing screens by swiping. */ public void lockCurrentScreen() { mLocked = true; } /** * Unlocks the current screen, if it was previously locked. See also {@link * Workspace#lockCurrentScreen()}. */ public void unlockCurrentScreen() { mLocked = false; } /** * Sets the resource ID of the separator drawable to use between adjacent screens. */ public void setSeparator(int resId) { if (mSeparatorDrawable != null && resId == 0) { // remove existing separators mSeparatorDrawable = null; int num = getChildCount(); for (int i = num - 2; i > 0; i -= 2) { removeViewAt(i); } requestLayout(); } else if (resId != 0) { // add or update separators if (mSeparatorDrawable == null) { // add int numsep = getChildCount(); int insertIndex = 1; mSeparatorDrawable = getResources().getDrawable(resId); for (int i = 1; i < numsep; i++) { View v = new View(getContext()); v.setBackgroundDrawable(mSeparatorDrawable); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT); v.setLayoutParams(lp); addView(v, insertIndex); insertIndex += 2; } requestLayout(); } else { // update mSeparatorDrawable = getResources().getDrawable(resId); int num = getChildCount(); for (int i = num - 2; i > 0; i -= 2) { getChildAt(i).setBackgroundDrawable(mSeparatorDrawable); } requestLayout(); } } } private static class SavedState extends BaseSavedState { int currentScreen = -1; SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); currentScreen = in.readInt(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(currentScreen); } public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } public void addViewToFront(View v) { mCurrentScreen++; addView(v, 0); } public void removeViewFromFront() { mCurrentScreen--; removeViewAt(0); } public void addViewToBack(View v) { addView(v); } public void removeViewFromBack() { removeViewAt(getChildCount() - 1); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * Custom layout that arranges children in a grid-like manner, optimizing for even horizontal and * vertical whitespace. */ public class DashboardLayout extends ViewGroup { private static final int UNEVEN_GRID_PENALTY_MULTIPLIER = 10; private int mMaxChildWidth = 0; private int mMaxChildHeight = 0; public DashboardLayout(Context context) { super(context, null); } public DashboardLayout(Context context, AttributeSet attrs) { super(context, attrs, 0); } public DashboardLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mMaxChildWidth = 0; mMaxChildHeight = 0; // Measure once to find the maximum child size. int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST); int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.AT_MOST); final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); mMaxChildWidth = Math.max(mMaxChildWidth, child.getMeasuredWidth()); mMaxChildHeight = Math.max(mMaxChildHeight, child.getMeasuredHeight()); } // Measure again for each child to be exactly the same size. childWidthMeasureSpec = MeasureSpec.makeMeasureSpec( mMaxChildWidth, MeasureSpec.EXACTLY); childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( mMaxChildHeight, MeasureSpec.EXACTLY); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } setMeasuredDimension( resolveSize(mMaxChildWidth, widthMeasureSpec), resolveSize(mMaxChildHeight, heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int width = r - l; int height = b - t; final int count = getChildCount(); // Calculate the number of visible children. int visibleCount = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } ++visibleCount; } if (visibleCount == 0) { return; } // Calculate what number of rows and columns will optimize for even horizontal and // vertical whitespace between items. Start with a 1 x N grid, then try 2 x N, and so on. int bestSpaceDifference = Integer.MAX_VALUE; int spaceDifference; // Horizontal and vertical space between items int hSpace = 0; int vSpace = 0; int cols = 1; int rows; while (true) { rows = (visibleCount - 1) / cols + 1; hSpace = ((width - mMaxChildWidth * cols) / (cols + 1)); vSpace = ((height - mMaxChildHeight * rows) / (rows + 1)); spaceDifference = Math.abs(vSpace - hSpace); if (rows * cols != visibleCount) { spaceDifference *= UNEVEN_GRID_PENALTY_MULTIPLIER; } if (spaceDifference < bestSpaceDifference) { // Found a better whitespace squareness/ratio bestSpaceDifference = spaceDifference; // If we found a better whitespace squareness and there's only 1 row, this is // the best we can do. if (rows == 1) { break; } } else { // This is a worse whitespace ratio, use the previous value of cols and exit. --cols; rows = (visibleCount - 1) / cols + 1; hSpace = ((width - mMaxChildWidth * cols) / (cols + 1)); vSpace = ((height - mMaxChildHeight * rows) / (rows + 1)); break; } ++cols; } // Lay out children based on calculated best-fit number of rows and cols. // If we chose a layout that has negative horizontal or vertical space, force it to zero. hSpace = Math.max(0, hSpace); vSpace = Math.max(0, vSpace); // Re-use width/height variables to be child width/height. width = (width - hSpace * (cols + 1)) / cols; height = (height - vSpace * (rows + 1)) / rows; int left, top; int col, row; int visibleIndex = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) { continue; } row = visibleIndex / cols; col = visibleIndex % cols; left = hSpace * (col + 1) + width * col; top = vSpace * (row + 1) + height * row; child.layout(left, top, (hSpace == 0 && col == cols - 1) ? r : (left + width), (vSpace == 0 && row == rows - 1) ? b : (top + height)); ++visibleIndex; } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.FontMetricsInt; import android.graphics.Paint.Style; import android.graphics.Typeface; import android.text.format.Time; import android.util.AttributeSet; import android.view.View; /** * Custom view that draws a vertical time "ruler" representing the chronological * progression of a single day. Usually shown along with {@link BlockView} * instances to give a spatial sense of time. */ public class TimeRulerView extends View { private int mHeaderWidth = 70; private int mHourHeight = 90; private boolean mHorizontalDivider = true; private int mLabelTextSize = 20; private int mLabelPaddingLeft = 8; private int mLabelColor = Color.BLACK; private int mDividerColor = Color.LTGRAY; private int mStartHour = 0; private int mEndHour = 23; public TimeRulerView(Context context) { this(context, null); } public TimeRulerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public TimeRulerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TimeRulerView, defStyle, 0); mHeaderWidth = a.getDimensionPixelSize(R.styleable.TimeRulerView_headerWidth, mHeaderWidth); mHourHeight = a .getDimensionPixelSize(R.styleable.TimeRulerView_hourHeight, mHourHeight); mHorizontalDivider = a.getBoolean(R.styleable.TimeRulerView_horizontalDivider, mHorizontalDivider); mLabelTextSize = a.getDimensionPixelSize(R.styleable.TimeRulerView_labelTextSize, mLabelTextSize); mLabelPaddingLeft = a.getDimensionPixelSize(R.styleable.TimeRulerView_labelPaddingLeft, mLabelPaddingLeft); mLabelColor = a.getColor(R.styleable.TimeRulerView_labelColor, mLabelColor); mDividerColor = a.getColor(R.styleable.TimeRulerView_dividerColor, mDividerColor); mStartHour = a.getInt(R.styleable.TimeRulerView_startHour, mStartHour); mEndHour = a.getInt(R.styleable.TimeRulerView_endHour, mEndHour); a.recycle(); } /** * Return the vertical offset (in pixels) for a requested time (in * milliseconds since epoch). */ public int getTimeVerticalOffset(long timeMillis) { Time time = new Time(UIUtils.CONFERENCE_TIME_ZONE.getID()); time.set(timeMillis); final int minutes = ((time.hour - mStartHour) * 60) + time.minute; return (minutes * mHourHeight) / 60; } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int hours = mEndHour - mStartHour; int width = mHeaderWidth; int height = mHourHeight * hours; setMeasuredDimension(resolveSize(width, widthMeasureSpec), resolveSize(height, heightMeasureSpec)); } private Paint mDividerPaint = new Paint(); private Paint mLabelPaint = new Paint(); @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); final int hourHeight = mHourHeight; final Paint dividerPaint = mDividerPaint; dividerPaint.setColor(mDividerColor); dividerPaint.setStyle(Style.FILL); final Paint labelPaint = mLabelPaint; labelPaint.setColor(mLabelColor); labelPaint.setTextSize(mLabelTextSize); labelPaint.setTypeface(Typeface.DEFAULT_BOLD); labelPaint.setAntiAlias(true); final FontMetricsInt metrics = labelPaint.getFontMetricsInt(); final int labelHeight = Math.abs(metrics.ascent); final int labelOffset = labelHeight + mLabelPaddingLeft; final int right = getRight(); // Walk left side of canvas drawing timestamps final int hours = mEndHour - mStartHour; for (int i = 0; i < hours; i++) { final int dividerY = hourHeight * i; final int nextDividerY = hourHeight * (i + 1); canvas.drawLine(0, dividerY, right, dividerY, dividerPaint); // draw text title for timestamp canvas.drawRect(0, dividerY, mHeaderWidth, nextDividerY, dividerPaint); // TODO: localize these labels better, including handling // 24-hour mode when set in framework. final int hour = mStartHour + i; String label; if (hour == 0) { label = "12am"; } else if (hour <= 11) { label = hour + "am"; } else if (hour == 12) { label = "12pm"; } else { label = (hour - 12) + "pm"; } final float labelWidth = labelPaint.measureText(label); canvas.drawText(label, 0, label.length(), mHeaderWidth - labelWidth - mLabelPaddingLeft, dividerY + labelOffset, labelPaint); } } public int getHeaderWidth() { return mHeaderWidth; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.ScrollView; /** * A custom ScrollView that can notify a scroll listener when scrolled. */ public class ObservableScrollView extends ScrollView { private OnScrollListener mScrollListener; public ObservableScrollView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (mScrollListener != null) { mScrollListener.onScrollChanged(this); } } public boolean isScrollPossible() { return computeVerticalScrollRange() > getHeight(); } public void setOnScrollListener(OnScrollListener listener) { mScrollListener = listener; } public static interface OnScrollListener { public void onScrollChanged(ObservableScrollView view); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.LayerDrawable; import android.text.format.DateUtils; import android.widget.Button; import java.util.TimeZone; /** * Custom view that represents a {@link Blocks#BLOCK_ID} instance, including its * title and time span that it occupies. Usually organized automatically by * {@link BlocksLayout} to match up against a {@link TimeRulerView} instance. */ public class BlockView extends Button { private static final int TIME_STRING_FLAGS = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY | DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_TIME; private final String mBlockId; private final String mTitle; private final long mStartTime; private final long mEndTime; private final boolean mContainsStarred; private final int mColumn; public BlockView(Context context, String blockId, String title, long startTime, long endTime, boolean containsStarred, int column) { super(context); mBlockId = blockId; mTitle = title; mStartTime = startTime; mEndTime = endTime; mContainsStarred = containsStarred; mColumn = column; setText(mTitle); // TODO: turn into color state list with layers? int textColor = Color.WHITE; int accentColor = -1; switch (mColumn) { case 0: accentColor = getResources().getColor(R.color.block_column_1); break; case 1: accentColor = getResources().getColor(R.color.block_column_2); break; case 2: accentColor = getResources().getColor(R.color.block_column_3); break; } LayerDrawable buttonDrawable = (LayerDrawable) context.getResources().getDrawable(R.drawable.btn_block); buttonDrawable.getDrawable(0).setColorFilter(accentColor, PorterDuff.Mode.SRC_ATOP); buttonDrawable.getDrawable(1).setAlpha(mContainsStarred ? 255 : 0); setTextColor(textColor); setBackgroundDrawable(buttonDrawable); } public String getBlockId() { return mBlockId; } public String getBlockTimeString() { TimeZone.setDefault(UIUtils.CONFERENCE_TIME_ZONE); return DateUtils.formatDateTime(getContext(), mStartTime, TIME_STRING_FLAGS); } public long getStartTime() { return mStartTime; } public long getEndTime() { return mEndTime; } public int getColumn() { return mColumn; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * Custom layout that contains and organizes a {@link TimeRulerView} and several * instances of {@link BlockView}. Also positions current "now" divider using * {@link R.id#blocks_now} view when applicable. */ public class BlocksLayout extends ViewGroup { private int mColumns = 3; private TimeRulerView mRulerView; private View mNowView; public BlocksLayout(Context context) { this(context, null); } public BlocksLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BlocksLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BlocksLayout, defStyle, 0); mColumns = a.getInt(R.styleable.TimeRulerView_headerWidth, mColumns); a.recycle(); } private void ensureChildren() { mRulerView = (TimeRulerView) findViewById(R.id.blocks_ruler); if (mRulerView == null) { throw new IllegalStateException("Must include a R.id.blocks_ruler view."); } mRulerView.setDrawingCacheEnabled(true); mNowView = findViewById(R.id.blocks_now); if (mNowView == null) { throw new IllegalStateException("Must include a R.id.blocks_now view."); } mNowView.setDrawingCacheEnabled(true); } /** * Remove any {@link BlockView} instances, leaving only * {@link TimeRulerView} remaining. */ public void removeAllBlocks() { ensureChildren(); removeAllViews(); addView(mRulerView); addView(mNowView); } public void addBlock(BlockView blockView) { blockView.setDrawingCacheEnabled(true); addView(blockView, 1); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { ensureChildren(); mRulerView.measure(widthMeasureSpec, heightMeasureSpec); mNowView.measure(widthMeasureSpec, heightMeasureSpec); final int width = mRulerView.getMeasuredWidth(); final int height = mRulerView.getMeasuredHeight(); setMeasuredDimension(resolveSize(width, widthMeasureSpec), resolveSize(height, heightMeasureSpec)); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { ensureChildren(); final TimeRulerView rulerView = mRulerView; final int headerWidth = rulerView.getHeaderWidth(); final int columnWidth = (getWidth() - headerWidth) / mColumns; rulerView.layout(0, 0, getWidth(), getHeight()); final int count = getChildCount(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() == GONE) continue; if (child instanceof BlockView) { final BlockView blockView = (BlockView) child; final int top = rulerView.getTimeVerticalOffset(blockView.getStartTime()); final int bottom = rulerView.getTimeVerticalOffset(blockView.getEndTime()); final int left = headerWidth + (blockView.getColumn() * columnWidth); final int right = left + columnWidth; child.layout(left, top, right, bottom); } } // Align now view to match current time final View nowView = mNowView; final long now = UIUtils.getCurrentTime(getContext()); final int top = rulerView.getTimeVerticalOffset(now); final int bottom = top + nowView.getMeasuredHeight(); final int left = 0; final int right = getWidth(); nowView.layout(left, top, right, bottom); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.widget; import com.google.android.apps.iosched.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.widget.ImageView; /** * An {@link ImageView} that draws its contents inside a mask and draws a border drawable on top. * This is useful for applying a beveled look to image contents, but is also flexible enough for use * with other desired aesthetics. */ public class BezelImageView extends ImageView { private static final String TAG = "BezelImageView"; private Paint mMaskedPaint; private Paint mCopyPaint; private Rect mBounds; private RectF mBoundsF; private Drawable mBorderDrawable; private Drawable mMaskDrawable; public BezelImageView(Context context) { this(context, null); } public BezelImageView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public BezelImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Attribute initialization final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BezelImageView, defStyle, 0); mMaskDrawable = a.getDrawable(R.styleable.BezelImageView_maskDrawable); if (mMaskDrawable == null) { mMaskDrawable = getResources().getDrawable(R.drawable.bezel_mask); } mMaskDrawable.setCallback(this); mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable); if (mBorderDrawable == null) { mBorderDrawable = getResources().getDrawable(R.drawable.bezel_border); } mBorderDrawable.setCallback(this); a.recycle(); // Other initialization mMaskedPaint = new Paint(); mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); mCopyPaint = new Paint(); } @Override protected boolean setFrame(int l, int t, int r, int b) { final boolean changed = super.setFrame(l, t, r, b); mBounds = new Rect(0, 0, r - l, b - t); mBoundsF = new RectF(mBounds); mBorderDrawable.setBounds(mBounds); mMaskDrawable.setBounds(mBounds); return changed; } @Override protected void onDraw(Canvas canvas) { int sc = canvas.saveLayer(mBoundsF, mCopyPaint, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG); mMaskDrawable.draw(canvas); canvas.saveLayer(mBoundsF, mMaskedPaint, 0); super.onDraw(canvas); canvas.restoreToCount(sc); mBorderDrawable.draw(canvas); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mBorderDrawable.isStateful()) { mBorderDrawable.setState(getDrawableState()); } if (mMaskDrawable.isStateful()) { mMaskDrawable.setState(getDrawableState()); } // TODO: is this the right place to invalidate? invalidate(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * A {@link WebView}-based fragment that shows Google Realtime Search results for a given query, * provided as the {@link TagStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no * search query is provided, the conference hashtag is used as the default query. */ public class TagStreamFragment extends Fragment { private static final String TAG = "TagStreamFragment"; public static final String EXTRA_QUERY = "com.google.android.iosched.extra.QUERY"; public static final String CONFERENCE_HASHTAG = "#io2011"; private String mSearchString; private WebView mWebView; private View mLoadingSpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSearchString = intent.getStringExtra(EXTRA_QUERY); if (TextUtils.isEmpty(mSearchString)) { mSearchString = CONFERENCE_HASHTAG; } if (!mSearchString.startsWith("#")) { mSearchString = "#" + mSearchString; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable() { public void run() { mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); try { mWebView.loadUrl( "http://www.google.com/search?tbs=" + "mbl%3A1&hl=en&source=hp&biw=1170&bih=668&q=" + URLEncoder.encode(mSearchString, "UTF-8") + "&btnG=Search"); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Could not construct the realtime search URL", e); } } }); return root; } public void refresh() { mWebView.reload(); } private WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("javascript")) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }; }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.text.Spannable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; /** * A {@link ListFragment} showing a list of sandbox comapnies. */ public class VendorsFragment extends ListFragment implements NotifyingAsyncQueryHandler.AsyncQueryListener { private static final String STATE_CHECKED_POSITION = "checkedPosition"; private Uri mTrackUri; private Cursor mCursor; private CursorAdapter mAdapter; private int mCheckedPosition = -1; private boolean mHasSetEmptyText = false; private NotifyingAsyncQueryHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments if (mCursor != null) { getActivity().stopManagingCursor(mCursor); mCursor = null; } mCheckedPosition = -1; setListAdapter(null); mHandler.cancelOperation(SearchQuery._TOKEN); mHandler.cancelOperation(VendorsQuery._TOKEN); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri vendorsUri = intent.getData(); final int vendorQueryToken; if (vendorsUri == null) { return; } String[] projection; if (!ScheduleContract.Vendors.isSearchUri(vendorsUri)) { mAdapter = new VendorsAdapter(getActivity()); projection = VendorsQuery.PROJECTION; vendorQueryToken = VendorsQuery._TOKEN; } else { Log.d("VendorsFragment/reloadFromArguments", "A search URL definitely gets passed in."); mAdapter = new SearchAdapter(getActivity()); projection = SearchQuery.PROJECTION; vendorQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Start background query to load vendors mHandler.startQuery(vendorQueryToken, null, vendorsUri, projection, null, null, ScheduleContract.Vendors.DEFAULT_SORT); // If caller launched us with specific track hint, pass it along when // launching vendor details. Also start a query to load the track info. mTrackUri = intent.getParcelableExtra(SessionDetailFragment.EXTRA_TRACK); if (mTrackUri != null) { mHandler.startQuery(TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (savedInstanceState != null) { mCheckedPosition = savedInstanceState.getInt(STATE_CHECKED_POSITION, -1); } if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible when it shouldn't // be visible. setEmptyText(getString(R.string.empty_vendors)); mHasSetEmptyText = true; } } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } if (token == VendorsQuery._TOKEN || token == SearchQuery._TOKEN) { onVendorsOrSearchQueryComplete(cursor); } else if (token == TracksQuery._TOKEN) { onTrackQueryComplete(cursor); } else { cursor.close(); } } /** * Handle {@link VendorsQuery} {@link Cursor}. */ private void onVendorsOrSearchQueryComplete(Cursor cursor) { if (mCursor != null) { // In case cancelOperation() doesn't work and we end up with consecutive calls to this // callback. getActivity().stopManagingCursor(mCursor); mCursor = null; } // TODO(romannurik): stopManagingCursor on detach (throughout app) mCursor = cursor; getActivity().startManagingCursor(mCursor); mAdapter.changeCursor(mCursor); if (mCheckedPosition >= 0 && getView() != null) { getListView().setItemChecked(mCheckedPosition, true); } } /** * Handle {@link TracksQuery} {@link Cursor}. */ private void onTrackQueryComplete(Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } // Use found track to build title-bar ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); String trackName = cursor.getString(TracksQuery.TRACK_NAME); activityHelper.setActionBarTitle(trackName); activityHelper.setActionBarColor(cursor.getInt(TracksQuery.TRACK_COLOR)); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sandbox/Track/" + trackName); } finally { cursor.close(); } } @Override public void onResume() { super.onResume(); getActivity().getContentResolver().registerContentObserver( ScheduleContract.Vendors.CONTENT_URI, true, mVendorChangesObserver); if (mCursor != null) { mCursor.requery(); } } @Override public void onPause() { super.onPause(); getActivity().getContentResolver().unregisterContentObserver(mVendorChangesObserver); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_CHECKED_POSITION, mCheckedPosition); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { // Launch viewer for specific vendor. final Cursor cursor = (Cursor)mAdapter.getItem(position); final String vendorId = cursor.getString(VendorsQuery.VENDOR_ID); final Uri vendorUri = ScheduleContract.Vendors.buildVendorUri(vendorId); ((BaseActivity) getActivity()).openActivityOrFragment(new Intent(Intent.ACTION_VIEW, vendorUri)); getListView().setItemChecked(position, true); mCheckedPosition = position; } public void clearCheckedPosition() { if (mCheckedPosition >= 0) { getListView().setItemChecked(mCheckedPosition, false); mCheckedPosition = -1; } } /** * {@link CursorAdapter} that renders a {@link VendorsQuery}. */ private class VendorsAdapter extends CursorAdapter { public VendorsAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor_oneline, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { ((TextView) view.findViewById(R.id.vendor_name)).setText( cursor.getString(VendorsQuery.NAME)); final boolean starred = cursor.getInt(VendorsQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { ((TextView) view.findViewById(R.id.vendor_name)).setText(cursor .getString(SearchQuery.NAME)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.vendor_location)).setText(styledSnippet); final boolean starred = cursor.getInt(VendorsQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } private ContentObserver mVendorChangesObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (mCursor != null) { mCursor.requery(); } } }; /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} query parameters. */ private interface VendorsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Vendors.VENDOR_ID, ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.VENDOR_LOCATION, ScheduleContract.Vendors.VENDOR_STARRED, }; int _ID = 0; int VENDOR_ID = 1; int NAME = 2; int LOCATION = 3; int STARRED = 4; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { int _TOKEN = 0x2; String[] PROJECTION = { ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_NAME = 0; int TRACK_COLOR = 1; } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} search query * parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Vendors.VENDOR_ID, ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.SEARCH_SNIPPET, ScheduleContract.Vendors.VENDOR_STARRED, }; int _ID = 0; int VENDOR_ID = 1; int NAME = 2; int SEARCH_SNIPPET = 3; int STARRED = 4; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.AnalyticsUtils; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.regex.Pattern; /** * A fragment containing a {@link WebView} pointing to the I/O announcements URL. */ public class BulletinFragment extends Fragment { private static final Pattern sSiteUrlPattern = Pattern.compile("google\\.com\\/events\\/io"); private static final String BULLETIN_URL = "http://www.google.com/events/io/2011/mobile_announcements.html"; private WebView mWebView; private View mLoadingSpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Bulletin"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable() { public void run() { mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); mWebView.loadUrl(BULLETIN_URL); } }); return root; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.refresh_menu_items, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { mWebView.reload(); return true; } return super.onOptionsItemSelected(item); } private WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (sSiteUrlPattern.matcher(url).find()) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }; }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import java.util.List; /** * A {@link BaseActivity} that can contain multiple panes, and has the ability to substitute * fragments for activities when intents are fired using * {@link BaseActivity#openActivityOrFragment(android.content.Intent)}. */ public abstract class BaseMultiPaneActivity extends BaseActivity { /** {@inheritDoc} */ @Override public void openActivityOrFragment(final Intent intent) { final PackageManager pm = getPackageManager(); List<ResolveInfo> resolveInfoList = pm .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resolveInfoList) { final FragmentReplaceInfo fri = onSubstituteFragmentForActivityLaunch( resolveInfo.activityInfo.name); if (fri != null) { final Bundle arguments = intentToFragmentArguments(intent); final FragmentManager fm = getSupportFragmentManager(); try { Fragment fragment = (Fragment) fri.getFragmentClass().newInstance(); fragment.setArguments(arguments); FragmentTransaction ft = fm.beginTransaction(); ft.replace(fri.getContainerId(), fragment, fri.getFragmentTag()); onBeforeCommitReplaceFragment(fm, ft, fragment); ft.commit(); } catch (InstantiationException e) { throw new IllegalStateException( "Error creating new fragment.", e); } catch (IllegalAccessException e) { throw new IllegalStateException( "Error creating new fragment.", e); } return; } } super.openActivityOrFragment(intent); } /** * Callback that's triggered to find out if a fragment can substitute the given activity class. * Base activites should return a {@link FragmentReplaceInfo} if a fragment can act in place * of the given activity class name. */ protected FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { return null; } /** * Called just before a fragment replacement transaction is committed in response to an intent * being fired and substituted for a fragment. */ protected void onBeforeCommitReplaceFragment(FragmentManager fm, FragmentTransaction ft, Fragment fragment) { } /** * A class describing information for a fragment-substitution, used when a fragment can act * in place of an activity. */ protected class FragmentReplaceInfo { private Class mFragmentClass; private String mFragmentTag; private int mContainerId; public FragmentReplaceInfo(Class fragmentClass, String fragmentTag, int containerId) { mFragmentClass = fragmentClass; mFragmentTag = fragmentTag; mContainerId = containerId; } public Class getFragmentClass() { return mFragmentClass; } public String getFragmentTag() { return mFragmentTag; } public int getContainerId() { return mContainerId; } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.text.Spannable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; import static com.google.android.apps.iosched.util.UIUtils.formatSessionSubtitle; /** * A {@link ListFragment} showing a list of sessions. */ public class SessionsFragment extends ListFragment implements NotifyingAsyncQueryHandler.AsyncQueryListener { public static final String EXTRA_SCHEDULE_TIME_STRING = "com.google.android.iosched.extra.SCHEDULE_TIME_STRING"; private static final String STATE_CHECKED_POSITION = "checkedPosition"; private Uri mTrackUri; private Cursor mCursor; private CursorAdapter mAdapter; private int mCheckedPosition = -1; private boolean mHasSetEmptyText = false; private NotifyingAsyncQueryHandler mHandler; private Handler mMessageQueueHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments if (mCursor != null) { getActivity().stopManagingCursor(mCursor); mCursor = null; } mCheckedPosition = -1; setListAdapter(null); mHandler.cancelOperation(SearchQuery._TOKEN); mHandler.cancelOperation(SessionsQuery._TOKEN); mHandler.cancelOperation(TracksQuery._TOKEN); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri sessionsUri = intent.getData(); final int sessionQueryToken; if (sessionsUri == null) { return; } String[] projection; if (!ScheduleContract.Sessions.isSearchUri(sessionsUri)) { mAdapter = new SessionsAdapter(getActivity()); projection = SessionsQuery.PROJECTION; sessionQueryToken = SessionsQuery._TOKEN; } else { mAdapter = new SearchAdapter(getActivity()); projection = SearchQuery.PROJECTION; sessionQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Start background query to load sessions mHandler.startQuery(sessionQueryToken, null, sessionsUri, projection, null, null, ScheduleContract.Sessions.DEFAULT_SORT); // If caller launched us with specific track hint, pass it along when // launching session details. Also start a query to load the track info. mTrackUri = intent.getParcelableExtra(SessionDetailFragment.EXTRA_TRACK); if (mTrackUri != null) { mHandler.startQuery(TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (savedInstanceState != null) { mCheckedPosition = savedInstanceState.getInt(STATE_CHECKED_POSITION, -1); } if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible when it shouldn't // be visible. setEmptyText(getString(R.string.empty_sessions)); mHasSetEmptyText = true; } } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } if (token == SessionsQuery._TOKEN || token == SearchQuery._TOKEN) { onSessionOrSearchQueryComplete(cursor); } else if (token == TracksQuery._TOKEN) { onTrackQueryComplete(cursor); } else { Log.d("SessionsFragment/onQueryComplete", "Query complete, Not Actionable: " + token); cursor.close(); } } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionOrSearchQueryComplete(Cursor cursor) { if (mCursor != null) { // In case cancelOperation() doesn't work and we end up with consecutive calls to this // callback. getActivity().stopManagingCursor(mCursor); mCursor = null; } mCursor = cursor; getActivity().startManagingCursor(mCursor); mAdapter.changeCursor(mCursor); if (mCheckedPosition >= 0 && getView() != null) { getListView().setItemChecked(mCheckedPosition, true); } } /** * Handle {@link TracksQuery} {@link Cursor}. */ private void onTrackQueryComplete(Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } // Use found track to build title-bar ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); String trackName = cursor.getString(TracksQuery.TRACK_NAME); activityHelper.setActionBarTitle(trackName); activityHelper.setActionBarColor(cursor.getInt(TracksQuery.TRACK_COLOR)); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Tracks/" + trackName); } finally { cursor.close(); } } @Override public void onResume() { super.onResume(); mMessageQueueHandler.post(mRefreshSessionsRunnable); getActivity().getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mSessionChangesObserver); if (mCursor != null) { mCursor.requery(); } } @Override public void onPause() { super.onPause(); mMessageQueueHandler.removeCallbacks(mRefreshSessionsRunnable); getActivity().getContentResolver().unregisterContentObserver(mSessionChangesObserver); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_CHECKED_POSITION, mCheckedPosition); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { // Launch viewer for specific session, passing along any track knowledge // that should influence the title-bar. final Cursor cursor = (Cursor)mAdapter.getItem(position); final String sessionId = cursor.getString(cursor.getColumnIndex( ScheduleContract.Sessions.SESSION_ID)); final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.putExtra(SessionDetailFragment.EXTRA_TRACK, mTrackUri); ((BaseActivity) getActivity()).openActivityOrFragment(intent); getListView().setItemChecked(position, true); mCheckedPosition = position; } public void clearCheckedPosition() { if (mCheckedPosition >= 0) { getListView().setItemChecked(mCheckedPosition, false); mCheckedPosition = -1; } } /** * {@link CursorAdapter} that renders a {@link SessionsQuery}. */ private class SessionsAdapter extends CursorAdapter { public SessionsAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { final TextView titleView = (TextView) view.findViewById(R.id.session_title); final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle); titleView.setText(cursor.getString(SessionsQuery.TITLE)); // Format time block this session occupies final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END); final String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = formatSessionSubtitle(blockStart, blockEnd, roomName, context); subtitleView.setText(subtitle); final boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); // Possibly indicate that the session has occurred in the past. UIUtils.setSessionTitleColor(blockStart, blockEnd, titleView, subtitleView); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { ((TextView) view.findViewById(R.id.session_title)).setText(cursor .getString(SearchQuery.TITLE)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.session_subtitle)).setText(styledSnippet); final boolean starred = cursor.getInt(SearchQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } private ContentObserver mSessionChangesObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (mCursor != null) { mCursor.requery(); } } }; private Runnable mRefreshSessionsRunnable = new Runnable() { public void run() { if (mAdapter != null) { // This is used to refresh session title colors. mAdapter.notifyDataSetChanged(); } // Check again on the next quarter hour, with some padding to account for network // time differences. long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000; mMessageQueueHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour); } }; /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Rooms.ROOM_NAME, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int BLOCK_START = 4; int BLOCK_END = 5; int ROOM_NAME = 6; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { int _TOKEN = 0x2; String[] PROJECTION = { ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_NAME = 0; int TRACK_COLOR = 1; } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} search query * parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SEARCH_SNIPPET, ScheduleContract.Sessions.SESSION_STARRED, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int SEARCH_SNIPPET = 3; int STARRED = 4; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; /** * An activity that shows the user's starred sessions and sandbox companies. This activity can be * either single or multi-pane, depending on the device configuration. We want the multi-pane * support that {@link BaseMultiPaneActivity} offers, so we inherit from it instead of * {@link BaseSinglePaneActivity}. */ public class StarredActivity extends BaseMultiPaneActivity { public static final String TAG_SESSIONS = "sessions"; public static final String TAG_VENDORS = "vendors"; private TabHost mTabHost; private TabWidget mTabWidget; private SessionsFragment mSessionsFragment; private VendorsFragment mVendorsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_starred); getActivityHelper().setupActionBar(getTitle(), 0); mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabWidget = (TabWidget) findViewById(android.R.id.tabs); mTabHost.setup(); setupSessionsTab(); setupVendorsTab(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_starred_detail); if (detailContainer != null && detailContainer.getChildCount() > 1) { findViewById(android.R.id.empty).setVisibility(View.GONE); } } /** * Build and add "sessions" tab. */ private void setupSessionsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_sessions); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final Intent intent = new Intent(Intent.ACTION_VIEW, Sessions.CONTENT_STARRED_URI); final FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentByTag("sessions"); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); mSessionsFragment.setArguments(intentToFragmentArguments(intent)); fm.beginTransaction() .add(R.id.fragment_sessions, mSessionsFragment, "sessions") .commit(); } // Sessions content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_SESSIONS) .setIndicator(buildIndicator(R.string.starred_sessions)) .setContent(R.id.fragment_sessions)); } /** * Build and add "vendors" tab. */ private void setupVendorsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_vendors); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final Intent intent = new Intent(Intent.ACTION_VIEW, Vendors.CONTENT_STARRED_URI); final FragmentManager fm = getSupportFragmentManager(); mVendorsFragment = (VendorsFragment) fm.findFragmentByTag("vendors"); if (mVendorsFragment == null) { mVendorsFragment = new VendorsFragment(); mVendorsFragment.setArguments(intentToFragmentArguments(intent)); fm.beginTransaction() .add(R.id.fragment_vendors, mVendorsFragment, "vendors") .commit(); } // Vendors content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_VENDORS) .setIndicator(buildIndicator(R.string.starred_vendors)) .setContent(R.id.fragment_vendors)); } /** * Build a {@link View} to be used as a tab indicator, setting the requested string resource as * its label. */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, mTabWidget, false); indicator.setText(textRes); return indicator; } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (findViewById(R.id.fragment_container_starred_detail) != null) { // The layout we currently have has a detail container, we can add fragments there. findViewById(android.R.id.empty).setVisibility(View.GONE); if (SessionDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_starred_detail); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_starred_detail); } } return null; } private void clearSelectedItems() { if (mSessionsFragment != null) { mSessionsFragment.clearCheckedPosition(); } if (mVendorsFragment != null) { mVendorsFragment.clearCheckedPosition(); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import android.app.SearchManager; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; /** * An activity that shows session and sandbox search results. This activity can be either single * or multi-pane, depending on the device configuration. We want the multi-pane support that * {@link BaseMultiPaneActivity} offers, so we inherit from it instead of * {@link BaseSinglePaneActivity}. */ public class SearchActivity extends BaseMultiPaneActivity { public static final String TAG_SESSIONS = "sessions"; public static final String TAG_VENDORS = "vendors"; private String mQuery; private TabHost mTabHost; private TabWidget mTabWidget; private SessionsFragment mSessionsFragment; private VendorsFragment mVendorsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); mQuery = intent.getStringExtra(SearchManager.QUERY); setContentView(R.layout.activity_search); getActivityHelper().setupActionBar(getTitle(), 0); final CharSequence title = getString(R.string.title_search_query, mQuery); getActivityHelper().setActionBarTitle(title); mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabWidget = (TabWidget) findViewById(android.R.id.tabs); mTabHost.setup(); setupSessionsTab(); setupVendorsTab(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_search_detail); if (detailContainer != null && detailContainer.getChildCount() > 1) { findViewById(android.R.id.empty).setVisibility(View.GONE); } } @Override public void onNewIntent(Intent intent) { setIntent(intent); mQuery = intent.getStringExtra(SearchManager.QUERY); final CharSequence title = getString(R.string.title_search_query, mQuery); getActivityHelper().setActionBarTitle(title); mTabHost.setCurrentTab(0); mSessionsFragment.reloadFromArguments(getSessionsFragmentArguments()); mVendorsFragment.reloadFromArguments(getVendorsFragmentArguments()); } /** * Build and add "sessions" tab. */ private void setupSessionsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_sessions); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentByTag("sessions"); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); mSessionsFragment.setArguments(getSessionsFragmentArguments()); fm.beginTransaction() .add(R.id.fragment_sessions, mSessionsFragment, "sessions") .commit(); } else { mSessionsFragment.reloadFromArguments(getSessionsFragmentArguments()); } // Sessions content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_SESSIONS) .setIndicator(buildIndicator(R.string.starred_sessions)) .setContent(R.id.fragment_sessions)); } /** * Build and add "vendors" tab. */ private void setupVendorsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_vendors); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final FragmentManager fm = getSupportFragmentManager(); mVendorsFragment = (VendorsFragment) fm.findFragmentByTag("vendors"); if (mVendorsFragment == null) { mVendorsFragment = new VendorsFragment(); mVendorsFragment.setArguments(getVendorsFragmentArguments()); fm.beginTransaction() .add(R.id.fragment_vendors, mVendorsFragment, "vendors") .commit(); } else { mVendorsFragment.reloadFromArguments(getVendorsFragmentArguments()); } // Vendors content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_VENDORS) .setIndicator(buildIndicator(R.string.starred_vendors)) .setContent(R.id.fragment_vendors)); } private Bundle getSessionsFragmentArguments() { return intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, Sessions.buildSearchUri(mQuery))); } private Bundle getVendorsFragmentArguments() { return intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, Vendors.buildSearchUri(mQuery))); } /** * Build a {@link View} to be used as a tab indicator, setting the requested string resource as * its label. */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, mTabWidget, false); indicator.setText(textRes); return indicator; } @Override public BaseMultiPaneActivity.FragmentReplaceInfo onSubstituteFragmentForActivityLaunch( String activityClassName) { if (findViewById(R.id.fragment_container_search_detail) != null) { // The layout we currently have has a detail container, we can add fragments there. findViewById(android.R.id.empty).setVisibility(View.GONE); if (SessionDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new BaseMultiPaneActivity.FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_search_detail); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new BaseMultiPaneActivity.FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_search_detail); } } return null; } private void clearSelectedItems() { if (mSessionsFragment != null) { mSessionsFragment.clearCheckedPosition(); } if (mVendorsFragment != null) { mVendorsFragment.clearCheckedPosition(); } } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; import org.apache.http.client.AuthenticationHandler; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.RedirectHandler; import org.apache.http.client.RequestDirector; import org.apache.http.client.UserTokenHandler; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.ConnectionKeepAliveStrategy; import org.apache.http.conn.routing.HttpRoutePlanner; import org.apache.http.entity.InputStreamEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHttpResponse; import org.apache.http.message.BasicStatusLine; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestExecutor; import android.content.Context; import android.content.res.AssetManager; import android.test.AndroidTestCase; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; /** * Stub {@link HttpClient} that will provide a single {@link HttpResponse} to * any incoming {@link HttpRequest}. This single response can be set using * {@link #setResponse(HttpResponse)}. */ class StubHttpClient extends DefaultHttpClient { private static final String TAG = "StubHttpClient"; private HttpResponse mResponse; private HttpRequest mLastRequest; public StubHttpClient() { resetState(); } /** * Set the default {@link HttpResponse} to always return for any * {@link #execute(HttpUriRequest)} calls. */ public void setResponse(HttpResponse currentResponse) { mResponse = currentResponse; } /** * Set the default {@link HttpResponse} to always return for any * {@link #execute(HttpUriRequest)} calls. This is a shortcut instead of * calling {@link #buildResponse(int, String, AndroidTestCase)}. */ public void setResponse(int statusCode, String assetName, AndroidTestCase testCase) throws Exception { setResponse(buildResponse(statusCode, assetName, testCase)); } /** * Return the last {@link HttpRequest} that was requested through * {@link #execute(HttpUriRequest)}, exposed for testing purposes. */ public HttpRequest getLastRequest() { return mLastRequest; } /** * Reset any internal state, usually so this heavy {@link HttpClient} can be * reused across tests. */ public void resetState() { mResponse = buildInternalServerError(); } private static HttpResponse buildInternalServerError() { final StatusLine status = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_INTERNAL_SERVER_ERROR, null); return new BasicHttpResponse(status); } /** * Build a stub {@link HttpResponse}, probably for use with * {@link #setResponse(HttpResponse)}. * * @param statusCode {@link HttpStatus} code to use. * @param assetName Name of asset that should be included as a single * {@link HttpEntity} to be included in the response, loaded * through {@link AssetManager}. */ public static HttpResponse buildResponse(int statusCode, String assetName, AndroidTestCase testCase) throws Exception { final Context testContext = getTestContext(testCase); return buildResponse(statusCode, assetName, testContext); } /** * Exposes method {@code getTestContext()} in {@link AndroidTestCase}, which * is hidden for now. Useful for obtaining access to the test assets. */ public static Context getTestContext(AndroidTestCase testCase) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (Context) AndroidTestCase.class.getMethod("getTestContext").invoke(testCase); } /** * Build a stub {@link HttpResponse}, probably for use with * {@link #setResponse(HttpResponse)}. * * @param statusCode {@link HttpStatus} code to use. * @param assetName Name of asset that should be included as a single * {@link HttpEntity} to be included in the response, loaded * through {@link AssetManager}. */ public static HttpResponse buildResponse(int statusCode, String assetName, Context context) throws IOException { final StatusLine status = new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, null); final HttpResponse response = new BasicHttpResponse(status); if (assetName != null) { final InputStream entity = context.getAssets().open(assetName); response.setEntity(new InputStreamEntity(entity, entity.available())); } return response; } /** {@inheritDoc} */ @Override protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler stateHandler, final HttpParams params) { return new RequestDirector() { /** {@inheritDoc} */ public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { Log.d(TAG, "Intercepted: " + request.getRequestLine().toString()); mLastRequest = request; return mResponse; } }; } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleProvider; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.util.ParserUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.test.AndroidTestCase; import android.test.ProviderTestCase2; import java.io.IOException; import java.lang.reflect.InvocationTargetException; public class SessionsHandlerTest extends ProviderTestCase2<ScheduleProvider> { public SessionsHandlerTest() { super(ScheduleProvider.class, ScheduleContract.CONTENT_AUTHORITY); } public void testLocalHandler() throws Exception { parseBlocks(); parseTracks(); parseRooms(); final ContentResolver resolver = getMockContentResolver(); final XmlPullParser parser = openAssetParser("local-sessions.xml"); new LocalSessionsHandler().parseAndApply(parser, resolver); Cursor cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { assertEquals(2, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("writingreal-timegamesforandroidredux", getString(cursor, Sessions.SESSION_ID)); assertEquals("Writing real-time games for Android redux", getString(cursor, Sessions.TITLE)); assertEquals(6, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274270400000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274295600000L, getLong(cursor, Sessions.BLOCK_END)); assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals("A beginner's guide to Android", getString(cursor, Sessions.TITLE)); assertEquals(4, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274291100000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274294700000L, getLong(cursor, Sessions.BLOCK_END)); } finally { cursor.close(); } final Uri sessionTracks = Sessions.buildTracksDirUri("beginners-guide-android"); cursor = resolver.query(sessionTracks, null, null, null, Tracks.DEFAULT_SORT); try { assertEquals(1, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals("android", getString(cursor, Tracks.TRACK_ID)); assertEquals(-14002535, getInt(cursor, Tracks.TRACK_COLOR)); } finally { cursor.close(); } } public void testRemoteHandler() throws Exception { parseTracks(); parseRooms(); final ContentResolver resolver = getMockContentResolver(); final XmlPullParser parser = openAssetParser("remote-sessions1.xml"); new RemoteSessionsHandler().parseAndApply(parser, resolver); Cursor cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { assertEquals(6, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(6, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274291100000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274294700000L, getLong(cursor, Sessions.BLOCK_END)); assertEquals("http://www.google.com/moderator/#15/e=68f0&t=68f0.45", getString(cursor, Sessions.MODERATOR_URL)); assertTrue(cursor.moveToNext()); assertEquals("writing-real-time-games-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertTrue(cursor.moveToLast()); assertEquals("developing-restful-android-apps", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); } finally { cursor.close(); } final Uri sessionTracks = Sessions.buildTracksDirUri("android-ui-design-patterns"); cursor = resolver.query(sessionTracks, null, null, null, Tracks.DEFAULT_SORT); try { assertEquals(2, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("android-ui-design-patterns", getString(cursor, Sessions.SESSION_ID)); assertEquals("android", getString(cursor, Tracks.TRACK_ID)); assertEquals(-14002535, getInt(cursor, Tracks.TRACK_COLOR)); assertTrue(cursor.moveToNext()); assertEquals("android-ui-design-patterns", getString(cursor, Sessions.SESSION_ID)); assertEquals("enterprise", getString(cursor, Tracks.TRACK_ID)); assertEquals(-15750145, getInt(cursor, Tracks.TRACK_COLOR)); } finally { cursor.close(); } } public void testLocalRemoteUpdate() throws Exception { parseBlocks(); parseTracks(); parseRooms(); // first, insert session data from local source final ContentResolver resolver = getMockContentResolver(); final XmlPullParser parser = openAssetParser("local-sessions.xml"); new LocalSessionsHandler().parseAndApply(parser, resolver); // now, star one of the sessions final Uri sessionUri = Sessions.buildSessionUri("beginners-guide-android"); final ContentValues values = new ContentValues(); values.put(Sessions.STARRED, 1); resolver.update(sessionUri, values, null, null); Cursor cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { assertEquals(2, cursor.getCount()); assertTrue(cursor.moveToNext()); assertEquals("writingreal-timegamesforandroidredux", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(0L, getLong(cursor, Sessions.UPDATED)); // make sure session is starred assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(4, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274291100000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274294700000L, getLong(cursor, Sessions.BLOCK_END)); assertEquals(1, getInt(cursor, Sessions.STARRED)); assertEquals(0L, getLong(cursor, Sessions.UPDATED)); } finally { cursor.close(); } // second, perform remote sync to pull in updates final XmlPullParser parser1 = openAssetParser("remote-sessions1.xml"); new RemoteSessionsHandler().parseAndApply(parser1, resolver); cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { // six sessions from remote sync, plus one original assertEquals(7, cursor.getCount()); // original local-only session is still hanging around assertTrue(cursor.moveToNext()); assertEquals("writingreal-timegamesforandroidredux", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(0L, getLong(cursor, Sessions.UPDATED)); // existing session was updated with remote values, and has star assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(1, getInt(cursor, Sessions.STARRED)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); // make sure session block was updated from remote assertTrue(cursor.moveToNext()); assertEquals("writing-real-time-games-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(6, getInt(cursor, Sessions.ROOM_ID)); assertEquals(2, getInt(cursor, Sessions.ROOM_FLOOR)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1274297400000L, getLong(cursor, Sessions.BLOCK_START)); assertEquals(1274301000000L, getLong(cursor, Sessions.BLOCK_END)); assertEquals("This session is a crash course in Android game development: everything " + "you need to know to get started writing 2D and 3D games, as well as tips, " + "tricks, and benchmarks to help your code reach optimal performance. In " + "addition, we'll discuss hot topics related to game development, including " + "hardware differences across devices, using C++ to write Android games, " + "and the traits of the most popular games on Market.", getString(cursor, Sessions.ABSTRACT)); assertEquals("Proficiency in Java and a solid grasp of Android's fundamental concepts", getString(cursor, Sessions.REQUIREMENTS)); assertEquals("http://www.google.com/moderator/#15/e=68f0&t=68f0.9B", getString(cursor, Sessions.MODERATOR_URL)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); assertTrue(cursor.moveToLast()); assertEquals("developing-restful-android-apps", getString(cursor, Sessions.SESSION_ID)); assertEquals("301", getString(cursor, Sessions.TYPE)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); } finally { cursor.close(); } // third, perform another remote sync final XmlPullParser parser2 = openAssetParser("remote-sessions2.xml"); new RemoteSessionsHandler().parseAndApply(parser2, resolver); cursor = resolver.query(Sessions.CONTENT_URI, null, null, null, Sessions.DEFAULT_SORT); try { // six sessions from remote sync, plus one original assertEquals(7, cursor.getCount()); // original local-only session is still hanging around assertTrue(cursor.moveToNext()); assertEquals("writingreal-timegamesforandroidredux", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(0L, getLong(cursor, Sessions.UPDATED)); // existing session was updated with remote values, and has star assertTrue(cursor.moveToNext()); assertEquals("beginners-guide-android", getString(cursor, Sessions.SESSION_ID)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1, getInt(cursor, Sessions.STARRED)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); // existing session was updated with remote values, and has star assertTrue(cursor.moveToNext()); assertEquals("writing-real-time-games-android", getString(cursor, Sessions.SESSION_ID)); assertEquals("Proficiency in Java and Python and Ruby and Scheme and " + "Bash and Ada and a solid grasp of Android's fundamental concepts", getString(cursor, Sessions.REQUIREMENTS)); assertEquals(0, getInt(cursor, Sessions.STARRED)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1273532584000L, getLong(cursor, Sessions.UPDATED)); // last session should remain unchanged, since updated flag didn't // get touched. the remote spreadsheet said "102401", but we should // still have "301". assertTrue(cursor.moveToLast()); assertEquals("developing-restful-android-apps", getString(cursor, Sessions.SESSION_ID)); assertEquals("301", getString(cursor, Sessions.TYPE)); assertEquals(ParserUtils.BLOCK_TYPE_SESSION, getString(cursor, Sessions.BLOCK_TYPE)); assertEquals(1273186984000L, getLong(cursor, Sessions.UPDATED)); } finally { cursor.close(); } } private void parseBlocks() throws Exception { final XmlPullParser parser = openAssetParser("local-blocks.xml"); new LocalBlocksHandler().parseAndApply(parser, getMockContentResolver()); } private void parseTracks() throws Exception { final XmlPullParser parser = openAssetParser("local-tracks.xml"); new LocalTracksHandler().parseAndApply(parser, getMockContentResolver()); } private void parseRooms() throws Exception { final XmlPullParser parser = openAssetParser("local-rooms.xml"); new LocalRoomsHandler().parseAndApply(parser, getMockContentResolver()); } private String getString(Cursor cursor, String column) { return cursor.getString(cursor.getColumnIndex(column)); } private long getInt(Cursor cursor, String column) { return cursor.getInt(cursor.getColumnIndex(column)); } private long getLong(Cursor cursor, String column) { return cursor.getLong(cursor.getColumnIndex(column)); } private XmlPullParser openAssetParser(String assetName) throws XmlPullParserException, IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Context testContext = getTestContext(this); return ParserUtils.newPullParser(testContext.getResources().getAssets().open(assetName)); } /** * Exposes method {@code getTestContext()} in {@link AndroidTestCase}, which * is hidden for now. Useful for obtaining access to the test assets. */ public static Context getTestContext(AndroidTestCase testCase) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (Context) AndroidTestCase.class.getMethod("getTestContext").invoke(testCase); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.util; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.Context; import android.test.AndroidTestCase; import java.io.IOException; import java.lang.reflect.InvocationTargetException; public class SpreadsheetEntryTest extends AndroidTestCase { public void testParseNormal() throws Exception { final XmlPullParser parser = openAssetParser("spreadsheet-normal.xml"); final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); assertEquals("unexpected columns", 19, entry.size()); assertEquals("Wednesday May 19", entry.get("sessiondate")); assertEquals("10:45am-11:45am", entry.get("sessiontime")); assertEquals("6", entry.get("room")); assertEquals("Android", entry.get("product")); assertEquals("Android", entry.get("track")); assertEquals("101", entry.get("sessiontype")); assertEquals("A beginner's guide to Android", entry.get("sessiontitle")); assertEquals("Android, Mobile, Java", entry.get("tags")); assertEquals("Reto Meier", entry.get("sessionspeakers")); assertEquals("retomeier", entry.get("speakers")); assertEquals("This session will introduce some of the basic concepts involved in " + "Android development. Starting with an overview of the SDK APIs available " + "to developers, we will work through some simple code examples that " + "explore some of the more common user features including using sensors, " + "maps, and geolocation.", entry.get("sessionabstract")); assertEquals("Proficiency in Java and a basic understanding of embedded " + "environments like mobile phones", entry.get("sessionrequirements")); assertEquals("beginners-guide-android", entry.get("sessionlink")); assertEquals("#android1", entry.get("sessionhashtag")); assertEquals("http://www.google.com/moderator/#15/e=68f0&t=68f0.45", entry.get("moderatorlink")); assertEquals( "https://wave.google.com/wave/#restored:wave:googlewave.com!w%252B-Xhdu7ZkBHw", entry.get("wavelink")); assertEquals("https://wave.google.com/wave/#restored:wave:googlewave.com", entry.get("_e8rn7")); assertEquals("w%252B-Xhdu7ZkBHw", entry.get("_dmair")); assertEquals("w+-Xhdu7ZkBHw", entry.get("waveid")); } public void testParseEmpty() throws Exception { final XmlPullParser parser = openAssetParser("spreadsheet-empty.xml"); final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); assertEquals("unexpected columns", 0, entry.size()); } public void testParseEmptyField() throws Exception { final XmlPullParser parser = openAssetParser("spreadsheet-emptyfield.xml"); final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); assertEquals("unexpected columns", 3, entry.size()); assertEquals("Wednesday May 19", entry.get("sessiondate")); assertEquals("", entry.get("sessiontime")); assertEquals("6", entry.get("room")); } public void testParseSingle() throws Exception { final XmlPullParser parser = openAssetParser("spreadsheet-single.xml"); final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); assertEquals("unexpected columns", 1, entry.size()); assertEquals("Wednesday May 19", entry.get("sessiondate")); } private XmlPullParser openAssetParser(String assetName) throws XmlPullParserException, IOException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Context testContext = getTestContext(this); return ParserUtils.newPullParser(testContext.getResources().getAssets().open(assetName)); } /** * Exposes method {@code getTestContext()} in {@link AndroidTestCase}, which * is hidden for now. Useful for obtaining access to the test assets. */ public static Context getTestContext(AndroidTestCase testCase) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { return (Context) AndroidTestCase.class.getMethod("getTestContext").invoke(testCase); } }
Java
package annotations.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value=ElementType.METHOD) @Retention(value= RetentionPolicy.RUNTIME) public @interface StartObject { }
Java
package annotations.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value=ElementType.METHOD) @Retention(value= RetentionPolicy.RUNTIME) public @interface StopObject { }
Java
package annotations.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value=ElementType.TYPE) @Retention(value= RetentionPolicy.RUNTIME) public @interface ControlledObject { String name(); }
Java
package annotations; import java.lang.reflect.Method; import annotations.api.ControlledObject; import annotations.api.StartObject; import annotations.api.StopObject; public class Main { public static void main(String[] args) throws ClassNotFoundException { Class<?> class1 = Class.forName("annotations.Cookies"); if (!class1.isAnnotationPresent(ControlledObject.class)) { System.out.println("Annotation is not presentfor class - " + class1.getCanonicalName()); } else { boolean hasStart = false; boolean hasStop = false; Method[] method = class1.getMethods(); for (Method md : method) { if (md.isAnnotationPresent(StartObject.class)) { hasStart = true; } if (md.isAnnotationPresent(StopObject.class)) { hasStop = true; } if (hasStart && hasStop) { break; } } System.out.println("Start annotaton - " + hasStart + "; Stop annotation - " + hasStop); } } }
Java
package annotations; import annotations.api.ControlledObject; import annotations.api.StartObject; import annotations.api.StopObject; @ControlledObject(name="biscuits") public class Cookies { @StartObject public void createCookie(){ } @StopObject public void stopCookie(){ } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.adapter; import com.google.samples.meetingscheduler.R; import com.google.samples.meetingscheduler.model.AvailableMeetingTime; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; /** * Adapts the Meeting data to the ExpendableListView. * * @author Nicolas Garnier */ public class EventExpandableListAdapter extends BaseExpandableListAdapter { /** * An interface for receiving updates once the user has selected the event * times. */ public interface EventHandler { /** * Handle the event being selected. * * @param startTime Start time of the event. * @param endTime End time of the event. */ public void handleEventSelected(long startTime, long endTime); } /** The Application Context */ private Activity activity; /** The lit of AvailableMeetingTime mapped by Days */ private Map<Date, List<AvailableMeetingTime>> sortedEventsByDays; /** The sorted list of Days with AvailableMeetingTime in them */ private List<Date> sortedDays; /** Inflater used to create Views from layouts */ private LayoutInflater inflater; /** The length of the meeting */ private int meetingLength; private EventHandler handler; /** * Constructs a new EventExpandableListAdapter given the List of Dates * * @param activity The activity of the application * @param availableMeetingTimes All the times for which a meeting is possible * for the attendees */ public EventExpandableListAdapter(Activity activity, List<AvailableMeetingTime> availableMeetingTimes, int meetingLength, EventHandler handler) { this.activity = activity; sortedEventsByDays = sortEventsByDay(availableMeetingTimes); sortedDays = asSortedList(sortedEventsByDays.keySet()); inflater = LayoutInflater.from(activity); this.meetingLength = meetingLength; this.handler = handler; } /** * Sorts a Collection and returns it as a Sorted List. * * @param c the collection to sort * @return The sorted collection as a List */ public static <T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) { List<T> list = new ArrayList<T>(c); java.util.Collections.sort(list); return list; } /** * Return a map of sorted meeting times key'ed by date. * * @param availableMeetingTimes The list of AvailableMeetingTime * @return A map of sorted meeting times key'ed by date. */ private Map<Date, List<AvailableMeetingTime>> sortEventsByDay( List<AvailableMeetingTime> availableMeetingTimes) { Map<Date, List<AvailableMeetingTime>> sortedEventsByDays = new HashMap<Date, List<AvailableMeetingTime>>(); for (AvailableMeetingTime availableMeetingTime : availableMeetingTimes) { GregorianCalendar calendar = new GregorianCalendar(TimeZone.getDefault()); calendar.setTime(availableMeetingTime.start); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.clear(Calendar.HOUR); calendar.clear(Calendar.MINUTE); calendar.clear(Calendar.SECOND); calendar.clear(Calendar.MILLISECOND); Date day = calendar.getTime(); List<AvailableMeetingTime> meetingTimes = sortedEventsByDays.get(day); if (meetingTimes == null) { meetingTimes = new ArrayList<AvailableMeetingTime>(); sortedEventsByDays.put(day, meetingTimes); } meetingTimes.add(availableMeetingTime); } return sortedEventsByDays; } @Override public AvailableMeetingTime getChild(int groupPosition, int childPosition) { return sortedEventsByDays.get(sortedDays.get(groupPosition)).get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public int getChildrenCount(int groupPosition) { try { return sortedEventsByDays.get(sortedDays.get(groupPosition)).size(); } catch (Exception e) { } return 0; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { // Creating the Widget from layout View view = inflater.inflate(R.layout.meeting_time_result_entry, null); // Setting time of meeting final TextView text = (TextView) view.findViewById(R.id.meeting_time_item_text); final Date startTime = getChild(groupPosition, childPosition).start; final Date endTime = getChild(groupPosition, childPosition).end; text.setText(getMeetingDisplayString(startTime, endTime)); // Adding Action to button Button button = (Button) view.findViewById(R.id.meeting_time_create_button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final List<Pair<Date, Date>> calendars = getPossibleMeetingTime(startTime, endTime); if (calendars.size() > 1) { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.choose_meeting_time); builder.setCancelable(true); builder.setNegativeButton(R.string.cancel, null); builder.setItems(getPossibleMeetingTimeDisplay(calendars), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (handler != null) { Pair<Date, Date> meeting = calendars.get(which); handler.handleEventSelected(meeting.first.getTime(), meeting.second.getTime()); } } }); builder.show(); } else { if (handler != null) { handler.handleEventSelected(startTime.getTime(), endTime.getTime()); } } } /** * Get the list of possible meeting time from startDate to endDate for the * preferred meeting length. * * @param startDate Start date to retrieve possible meeting times from. * @param endDate End date to retrieve possible meeting times to. * @return Possible meeting times. */ private List<Pair<Date, Date>> getPossibleMeetingTime(Date startDate, Date endDate) { List<Pair<Date, Date>> result = new ArrayList<Pair<Date, Date>>(); Calendar currentStart = new GregorianCalendar(TimeZone.getDefault()); Calendar currentEnd = new GregorianCalendar(TimeZone.getDefault()); currentStart.setTime(startDate); currentEnd.setTime(startDate); currentEnd.add(Calendar.MINUTE, meetingLength); while (!currentEnd.getTime().after(endDate)) { result.add(new Pair<Date, Date>(currentStart.getTime(), currentEnd.getTime())); currentStart.add(Calendar.MINUTE, 15); currentEnd.add(Calendar.MINUTE, 15); } return result; } /** * Get the list of meeting time display texts for the dialog. * * @param meetings List of meetings to get display for. * @return List of meeting time display text. */ private String[] getPossibleMeetingTimeDisplay(List<Pair<Date, Date>> meetings) { String[] result = new String[meetings.size()]; int i = 0; for (Pair<Date, Date> meeting : meetings) { result[i++] = getMeetingDisplayString(meeting.first, meeting.second); } return result; } }); return view; } @Override public Date getGroup(int groupPosition) { return sortedDays.get(groupPosition); } @Override public int getGroupCount() { return sortedDays.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { View view = inflater.inflate(R.layout.meeting_time_result_group_title, null); TextView title = (TextView) view.findViewById(R.id.meeting_time_group_title); String date = DateUtils .formatDateTime(activity, getGroup(groupPosition).getTime(), DateUtils.FORMAT_SHOW_DATE + DateUtils.FORMAT_SHOW_WEEKDAY + DateUtils.FORMAT_SHOW_YEAR); title.setText(date + " (" + getChildrenCount(groupPosition) + ")"); return view; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } @Override public boolean hasStableIds() { return true; } private String getMeetingDisplayString(Date startDate, Date endDate) { java.text.DateFormat format = DateFormat.getTimeFormat(activity); format.setTimeZone(TimeZone.getDefault()); String dateStart = format.format(startDate); String dateEnd = format.format(endDate); return dateStart + " - " + dateEnd; } }
Java
package com.google.samples.meetingscheduler.adapter; import com.google.samples.meetingscheduler.R; import com.google.samples.meetingscheduler.model.Attendee; import com.google.samples.meetingscheduler.util.AttendeeComparator; import android.content.Context; import android.graphics.Color; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; /** * Adapts the Attendee data to the ListView * * @author Alain Vongsouvanh (alainv@google.com) */ public class SelectableAttendeeAdapter extends ArrayAdapter<Attendee> { /** Inflater used to create Views from layouts */ private LayoutInflater inflater; /** * Constructor. * * @param context Used by super class. * @param items Used by super class. */ public SelectableAttendeeAdapter(Context context, List<Attendee> items) { super(context, R.layout.selectable_attendee, items); inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override /** * Return the view to be drawn on the ListView for the attendee at position. */ public View getView(int position, View convertView, ViewGroup parent) { Attendee item = getItem(position); LinearLayout attendeeView = getView(convertView); setViews(item, attendeeView); return attendeeView; } /** * Get the current view by inflating it with the selectable_attendee layout if * necessary. * * @param convertView The view to convert or inflate. * @return The AttendeeView layout. */ private LinearLayout getView(View convertView) { LinearLayout attendeeView; if (convertView == null) { attendeeView = new LinearLayout(getContext()); inflater.inflate(R.layout.selectable_attendee, attendeeView, true); } else { attendeeView = (LinearLayout) convertView; } return attendeeView; } /** * Set the layout items. * * @param item The attendee from which to read the data. * @param attendeeView The view to populate. */ private void setViews(Attendee item, LinearLayout attendeeView) { setNameView(item, attendeeView); setPhotoView(item, attendeeView); setCheckBoxView(item, attendeeView); } /** * Set the nameView of the layout item with the current attendee name. * * @param item The attendee from which to read the data. * @param attendeeView The view to populate. */ private void setNameView(Attendee item, LinearLayout attendeeView) { TextView nameView = (TextView) attendeeView.findViewById(R.id.attendee_name); nameView.setText(item.name); } /** * Set the photoView of the layout item with the current attendee picture. * * @param item The attendee from which to read the data. * @param attendeeView The view to populate. */ private void setPhotoView(Attendee item, LinearLayout attendeeView) { ImageView photoView = (ImageView) attendeeView.findViewById(R.id.attendee_photo); if (item.photoUri == null) { photoView.setImageResource(R.drawable.attendee_icon); } else { photoView.setImageURI(Uri.parse(item.photoUri)); } } /** * Set the checkBoxView of the layout item with the current attendee selection * state. * * @param item The attendee from which to read the data. * @param attendeeView The view to populate. */ private void setCheckBoxView(Attendee item, LinearLayout attendeeView) { CheckBox checkBoxView = (CheckBox) attendeeView.findViewById(R.id.attendee_checkbox); checkBoxView.setChecked(item.selected); if (checkBoxView.isChecked()) { attendeeView.setBackgroundResource(R.color.selected_attendee_background); } else { attendeeView.setBackgroundColor(Color.TRANSPARENT); } } /** * Sort the array using the AttendeeComparator. */ public void sort() { super.sort(AttendeeComparator.getInstance()); super.notifyDataSetChanged(); } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.util; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.util.DateTime; import com.google.api.services.calendar.Calendar; import com.google.api.services.calendar.Calendar.Freebusy; import com.google.api.services.calendar.model.FreeBusyCalendar; import com.google.api.services.calendar.model.FreeBusyRequest; import com.google.api.services.calendar.model.FreeBusyRequestItem; import com.google.api.services.calendar.model.FreeBusyResponse; import com.google.api.services.calendar.model.TimePeriod; import com.google.samples.meetingscheduler.model.Constants; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Retrieves the busy times from the Google Calendar API. * * @author Alain Vongsouvanh (alainv@google.com) */ public class FreeBusyTimesRetriever { private Calendar service; public FreeBusyTimesRetriever(String accessToken) { this.service = CalendarServiceBuilder.build(accessToken); } /** * Constructor. */ public FreeBusyTimesRetriever(Calendar service) { this.service = service; } /** * Get busy times from the Calendar API. * * @param attendees Attendees to retrieve busy times for. * @param startDate Start date to retrieve busy times from. * @param timeSpan Number of days to retrieve busy times for. * @return Busy times for the selected attendees. * @throws IOException */ public Map<String, List<TimePeriod>> getBusyTimes(List<String> attendees, Date startDate, int timeSpan) throws IOException { Map<String, List<TimePeriod>> result = new HashMap<String, List<TimePeriod>>(); List<FreeBusyRequestItem> requestItems = new ArrayList<FreeBusyRequestItem>(); FreeBusyRequest request = new FreeBusyRequest(); request.setTimeMin(getDateTime(startDate, 0)); request.setTimeMax(getDateTime(startDate, timeSpan)); for (String attendee : attendees) { requestItems.add(new FreeBusyRequestItem().setId(attendee)); } request.setItems(requestItems); FreeBusyResponse busyTimes; try { Freebusy.Query query = service.freebusy().query(request); // Use partial GET to only retrieve needed fields. query.setFields("calendars"); busyTimes = query.execute(); for (Map.Entry<String, FreeBusyCalendar> busyCalendar : busyTimes.getCalendars().entrySet()) { result.put(busyCalendar.getKey(), busyCalendar.getValue().getBusy()); } } catch (IOException e) { Log.e(Constants.TAG, "Exception occured while retrieving busy times: " + e.toString()); if (e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).getResponse(); int statusCode = response.getStatusCode(); if (statusCode == 401) { // The token might have expired, throw the exception to let calling // Activity know. throw e; } } } return result; } /** * Create a new DateTime object initialized at the current day + * {@code daysToAdd}. * * @param startDate The date from which to compute the DateTime. * @param daysToAdd The number of days to add to the result. * * @return The new DateTime object initialized at the current day + * {@code daysToAdd}. */ private DateTime getDateTime(Date startDate, int daysToAdd) { java.util.Calendar date = new GregorianCalendar(); date.setTime(startDate); date.add(java.util.Calendar.DAY_OF_YEAR, daysToAdd); return new DateTime(date.getTime().getTime(), 0); } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.util; import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager; import com.google.samples.meetingscheduler.R; import com.google.samples.meetingscheduler.model.Constants; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import java.io.IOException; /** * OAuthManager let's the entire application retrieve an OAuth 2.0 access token * from the AccountManager. */ public class OAuthManager { /** * An interface for receiving updates once the user has selected the account. */ public interface AuthHandler { /** * Handle the account being selected. * * @param account The selected account or null if none could be found * @param authToken The authorization token or null if access has been * denied. */ public void handleAuth(Account account, String authToken); } /** The chosen account. */ private Account account; /** The most recently fetched auth token or null if none is available. */ private String authToken; /** Singleton instance. */ private static OAuthManager instance; /** * Private constructor. */ private OAuthManager() { } /** * Get the singleton instance of AccountChooser. * * @return The instance of AccountChooser. */ public static OAuthManager getInstance() { if (instance == null) { instance = new OAuthManager(); } return instance; } /** * Returns the current account. * * @return The current account or null if no account has been chosen. */ public Account getAccount() { return account; } /** * Returns the current auth token. Response may be null if no valid auth token * has been fetched. * * @return The current auth token or null if no auth token has been fetched */ public String getAuthToken() { return authToken; } /** * Log-in using the preferred account, prompting the user to choose if no * preferred account is found. * * @param invalidate Whether or not to invalidate the token. * @param activity The activity to use to display the prompt, get the * AcountManager instance and SharedPreference instance. * @param callback The callback to call when an account and token has been * found. */ public void doLogin(boolean invalidate, Activity activity, AuthHandler callback) { if (account != null) { doLogin(account.name, invalidate, activity, callback); } else { SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(activity); doLogin(preference.getString("selected_account_preference", ""), invalidate, activity, callback); } } /** * Log-in using the specified account name. If an empty account name is * provided, a prompt is shown to the user to choose the account to use and * saved in the preferences. * * @param accountName The account name to use. * @param invalidate Whether or not to invalidate the token. * @param activity The activity to use to display the prompt, get the * AcountManager instance and SharedPreference instance. * @param callback The callback to call when an account and token has been * found. */ public void doLogin(String accountName, boolean invalidate, Activity activity, AuthHandler callback) { if (account != null && accountName.equals(account.name)) { if (!invalidate && authToken != null) { callback.handleAuth(account, authToken); } else { if (authToken != null && invalidate) { final AccountManager accountManager = AccountManager.get(activity); accountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken); invalidate = false; } authorize(account, invalidate, activity, callback); } } else { chooseAccount(accountName, invalidate, activity, callback); } } /** * Request authorization to call the Calendar API on behalf of the specified * account. * * @param account The account to request authorization for. * @param invalidate Whether or not to invalidate the token. * @param context The context to use to retrieve the AccountManager. * @param callback The callback to call when a token as been retrieved. */ private void authorize(final Account account, final boolean invalidate, final Activity context, final AuthHandler callback) { final AccountManager accountManager = AccountManager.get(context); accountManager.getAuthToken(account, Constants.OAUTH_SCOPE, true, new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> future) { try { Bundle result = future.getResult(); // AccountManager needs user to grant permission if (result.containsKey(AccountManager.KEY_INTENT)) { Intent intent = (Intent) result.getParcelable(AccountManager.KEY_INTENT); intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivityForResult(intent, Constants.GET_LOGIN); return; } else if (result.containsKey(AccountManager.KEY_AUTHTOKEN)) { Log.e(Constants.TAG, "Got auth token: " + invalidate); authToken = result.getString(AccountManager.KEY_AUTHTOKEN); if (invalidate) { // Invalidate the current token and request a new one. accountManager.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken); authorize(account, false, context, callback); } else { // Return the token to the callback. callback.handleAuth(account, authToken); } } } catch (OperationCanceledException e) { Log.e(Constants.TAG, "Operation Canceled", e); callback.handleAuth(null, null); } catch (IOException e) { Log.e(Constants.TAG, "IOException", e); callback.handleAuth(null, null); } catch (AuthenticatorException e) { Log.e(Constants.TAG, "Authentication Failed", e); callback.handleAuth(null, null); } } }, null /* handler */); } /** * Prompt the user to choose an account if more than one account is found and * none is matching the provided account name. * * @param accountName Account name to look for. * @param invalidate Whether or not to invalidate the autToken. * @param activity The activity to use to display the prompt. * @param callback The callback to call when an account and token has been * found. */ private void chooseAccount(String accountName, final boolean invalidate, final Activity activity, final AuthHandler callback) { final Account[] accounts = new GoogleAccountManager(activity).getAccounts(); if (accounts.length < 1) { callback.handleAuth(null, null); } else if (accounts.length == 1) { gotAccount(accounts[0], invalidate, activity, callback); } else if (accountName != null && accountName.length() > 0) { for (Account account : accounts) { if (account.name.equals(accountName)) { gotAccount(account, invalidate, activity, callback); return; } } } else { // Let the user choose. Log.e(Constants.TAG, "Multiple matching accounts found."); // Build dialog. String[] choices = new String[accounts.length]; for (int i = 0; i < accounts.length; i++) { choices[i] = accounts[i].name; } final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.choose_account_title); builder.setItems(choices, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotAccount(accounts[which], invalidate, activity, callback); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { callback.handleAuth(null, null); } }); builder.show(); } } /** * Save chosen account into the instance and shared preferences. * * @param account Chosen account. * @param invalidate Whether or not to invalidate the auth token. * @param activity Activity to run thread on. * @param callback Method to call when auth token has been retrieved. */ private void gotAccount(Account account, boolean invalidate, Activity activity, AuthHandler callback) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(activity).edit(); editor.putString("selected_account_preference", account.name); editor.commit(); this.account = account; authorize(account, invalidate, activity, callback); } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.util; import com.google.samples.meetingscheduler.model.Attendee; import com.google.samples.meetingscheduler.model.Constants; import android.accounts.Account; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentUris; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Email; import android.provider.ContactsContract.Contacts; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Get the contacts from the phone for the selected account. * * @author Alain Vongsouvanh (alainv@google.com) */ public class AttendeeRetriever { private Activity activity; private Account account; private Attendee currentUser; /** * Construct a new AttendeeRetriever. * * @param activity Activity to run contact's retrieval from. * @param account Account to use. */ public AttendeeRetriever(Activity activity, Account account) { this.activity = activity; this.account = account; this.currentUser = new Attendee("Me (" + account.name + ")", account.name, null); } /** * Get the list of user's contacts. * * @return The list of contacts. */ public List<Attendee> getAttendees() { List<Attendee> result = new ArrayList<Attendee>(); ContentResolver cr = activity.getContentResolver(); Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, new String[] {BaseColumns._ID, Contacts.DISPLAY_NAME, Contacts.IN_VISIBLE_GROUP}, Contacts.IN_VISIBLE_GROUP + " = 1", null, null); try { if (cursor.getCount() > 0) { while (cursor.moveToNext()) { long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID)); String email = getEmail(cr, id); if (email != null) { String name = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME)); String imageUri = getPhotoUri(cr, id); result.add(new Attendee(name + " (" + email + ")", email, imageUri)); } } } else { Log.e(Constants.TAG, "No contacts found."); } } finally { cursor.close(); } Attendee current = getCurrentUser(); current.selected = true; result.add(current); return result; } /** * Get the current user as an attendee. * * @return The current user as an attendee. */ public Attendee getCurrentUser() { return currentUser; } /** * Get the correct email address to use for the current contact. The first * choice is the e-mail having the same domain as the user's, if none is * available, the first GMail address is chosen. * * @param cr ContentResolver to use to get the list of e-mail addresses. * @param id Contact's ID * @return The "best" email address. */ private String getEmail(ContentResolver cr, long id) { Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[] {Email.DATA, Email.IS_PRIMARY}, Email.CONTACT_ID + " = '" + id + "'", null, Email.IS_PRIMARY + " DESC"); String result = null; if (cursor != null) { try { if (cursor.getCount() > 0) { while (cursor.moveToNext()) { String email = cursor.getString(cursor.getColumnIndex(Email.DATA)); if (email.contains("@")) { // Get the first e-mail on the same domain as the uer's. if (isSameDomain(account.name, email)) { result = email; break; } // Else, get the first gmail address. else if (isSameDomain("@gmail.com", email) && result == null) { result = email; } } } // If none of the above has been found, use the first email address. if (result == null) { if (cursor.moveToFirst()) { result = cursor.getString(cursor.getColumnIndex(Email.DATA)); } } } } finally { cursor.close(); } } return result; } /** * Check if two email addresses are of the same domain. * * @param lhs Left-hand side e-mail address. * @param rhs Right-hand side e-mail address. * @return Whether or not 2 email addresses are on the same domain. */ private boolean isSameDomain(String lhs, String rhs) { return lhs.substring(lhs.indexOf('@')).equalsIgnoreCase(rhs.substring(rhs.indexOf('@'))); } /** * Get the contact's Photo URI if it exists. * * @param cr The ContentResolver to use to get the contact's data. * @param id The contact's ID. * * @return The contact's Photo URI or null if none is available. */ private String getPhotoUri(ContentResolver cr, long id) { Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id); Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY); AssetFileDescriptor descriptor = null; try { descriptor = cr.openAssetFileDescriptor(photoUri, "r"); descriptor.close(); return photoUri.toString(); } catch (Exception e) { if (descriptor != null) { try { descriptor.close(); } catch (IOException ex) { } } // The contact has no pictures. return null; } } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.util; import com.google.api.client.util.DateTime; import com.google.api.services.calendar.model.TimePeriod; import com.google.samples.meetingscheduler.model.AvailableMeetingTime; import com.google.samples.meetingscheduler.model.Constants; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Map; import java.util.TimeZone; /** * Compute the common free times from the busy times fetched from the * BusyTimesRetriever. * * @author Alain Vongsouvanh (alainv@google.com) */ public class EventTimesRetriever { /** * The BusyTimesRetriever from which to retrieve the busy time. */ private FreeBusyTimesRetriever busyTimeRetriever; /** * @return the busyTimeRetriever */ public FreeBusyTimesRetriever getBusyTimeRetriever() { return busyTimeRetriever; } /** * @param busyTimeRetriever the busyTimeRetriever to set */ public void setBusyTimeRetriever(FreeBusyTimesRetriever busyTimeRetriever) { this.busyTimeRetriever = busyTimeRetriever; } /** * @return the timeSpan */ public int getTimeSpan() { return timeSpan; } /** * @param timeSpan the timeSpan to set */ public void setTimeSpan(int timeSpan) { this.timeSpan = timeSpan; } /** * @return the useWorkingHours */ public boolean isUseWorkingHours() { return useWorkingHours; } /** * @param useWorkingHours the useWorkingHours to set */ public void setUseWorkingHours(boolean useWorkingHours) { this.useWorkingHours = useWorkingHours; } /** * @return the skipWeekEnds */ public boolean isSkipWeekEnds() { return skipWeekEnds; } /** * @param skipWeekEnds the skipWeekEnds to set */ public void setSkipWeekEnds(boolean skipWeekEnds) { this.skipWeekEnds = skipWeekEnds; } /** * @return the workingHoursStart */ public Calendar getWorkingHoursStart() { return workingHoursStart; } /** * @param workingHoursStart the workingHoursStart to set */ public void setWorkingHoursStart(Calendar workingHoursStart) { this.workingHoursStart = workingHoursStart; } /** * @return the workingHoursEnd */ public Calendar getWorkingHoursEnd() { return workingHoursEnd; } /** * @param workingHoursEnd the workingHoursEnd to set */ public void setWorkingHoursEnd(Calendar workingHoursEnd) { this.workingHoursEnd = workingHoursEnd; } private int timeSpan; private boolean useWorkingHours; private boolean skipWeekEnds; private Calendar workingHoursStart; private Calendar workingHoursEnd; /** * Constructor. * * @param busyTimeRetriever The BusyTimesRetriever to use for fetching busy * times. */ public EventTimesRetriever(FreeBusyTimesRetriever busyTimeRetriever) { this.busyTimeRetriever = busyTimeRetriever; } /* * (non-Javadoc) * * @see com.google.android.apps.meetingscheduler.EventTimeRetriever# * getAvailableMeetingTime(java.util.List, * com.google.android.apps.meetingscheduler.Settings) */ public List<AvailableMeetingTime> getAvailableMeetingTime(List<String> attendees, Date startDate, int timeSpan, int meetingLength) throws IOException { Log.d(Constants.TAG, "Retrieving busy times from " + startDate.toString() + " for " + timeSpan + " days."); Map<String, List<TimePeriod>> busyTimes = busyTimeRetriever.getBusyTimes(attendees, startDate, timeSpan); Log.d(Constants.TAG, "Cleaning busy times from " + startDate.toString() + " for " + timeSpan + " days."); List<TimePeriod> listBusyTimes = cleanBusyTimes(busyTimes, startDate, timeSpan); Log.d(Constants.TAG, "Cleaned busy times: " + listBusyTimes.size()); List<AvailableMeetingTime> result = findAvailableMeetings(listBusyTimes); Log.d(Constants.TAG, "result: " + result.size()); filterMeetingLength(result, meetingLength); splitAvailableMeetings(result); return result; } /** * Add weekends and non-working hours as busy times if requested and merge all * the busy times. * * @param busyTimes The busy times to clean * @param startDate The date from which to start cleaning * @param timeSpan Number of days from startDate to search for available times * * @return A list of cleaned busy times. */ private List<TimePeriod> cleanBusyTimes(Map<String, List<TimePeriod>> busyTimes, Date startDate, int timeSpan) { List<TimePeriod> listBusyTimes = new ArrayList<TimePeriod>(); for (List<TimePeriod> busy : busyTimes.values()) { listBusyTimes.addAll(busy); } addStartAndEndDates(listBusyTimes, startDate, timeSpan); if (this.skipWeekEnds) { addWeekends(listBusyTimes, startDate, timeSpan); } if (this.useWorkingHours) { addWorkingHours(listBusyTimes, startDate, timeSpan); } mergeBusyTimes(listBusyTimes); return listBusyTimes; } /** * Add start and end dates as busy times for boundary. * * @param listBusyTimes List of busy times to add start and end to. * @param startDate Start date. * @param timeSpan Time span. */ private void addStartAndEndDates(List<TimePeriod> listBusyTimes, Date startDate, int timeSpan) { Calendar endDate = new GregorianCalendar(); endDate.setTime(startDate); endDate.add(Calendar.DAY_OF_YEAR, timeSpan); listBusyTimes.add(new TimePeriod().setStart(new DateTime(startDate.getTime(), 0)).setEnd( new DateTime(startDate.getTime(), 0))); listBusyTimes.add(new TimePeriod().setStart(new DateTime(endDate.getTime().getTime(), 0)) .setEnd(new DateTime(endDate.getTime().getTime(), 0))); } /** * Add weekends as busy times to the list of busy times. * * @param busyTimes The list of busy times to which to add the weekends * @param startDate The start date from which * @param timeSpan */ private void addWeekends(List<TimePeriod> busyTimes, Date startDate, int timeSpan) { Calendar date = new GregorianCalendar(TimeZone.getDefault()); date.setTime(startDate); for (int i = 0; i < timeSpan; ++i) { int day = date.get(Calendar.DAY_OF_WEEK); if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) { TimePeriod toAdd = new TimePeriod(); DateUtils.setTime(date, 0, 0, 0, 0); toAdd.setStart(new DateTime(date.getTime())); DateUtils.setTime(date, 23, 59, 59, 999); toAdd.setEnd(new DateTime(date.getTime())); busyTimes.add(toAdd); } date.add(Calendar.DAY_OF_YEAR, 1); } } /** * Add non-working hours as busy times to the list of busy times. * * @param busyTimes The busy times to which to add the non-working hours * @param startDate The start date from which to start adding busy times * @param timeSpan The number of day for which to add busy times */ private void addWorkingHours(List<TimePeriod> busyTimes, Date startDate, int timeSpan) { Calendar current = new GregorianCalendar(TimeZone.getDefault()); current.setTime(startDate); DateUtils.setTime(current, this.workingHoursStart); if (current.getTime().after(startDate)) { TimePeriod toAdd = new TimePeriod(); toAdd.setStart(new DateTime(startDate.getTime())); toAdd.setEnd(new DateTime(current.getTime())); busyTimes.add(toAdd); } for (int i = 0; i < timeSpan; ++i) { DateUtils.setTime(current, this.workingHoursEnd); TimePeriod toAdd = new TimePeriod(); toAdd.setStart(new DateTime(current.getTime())); current.add(Calendar.DAY_OF_YEAR, 1); DateUtils.setTime(current, this.workingHoursStart); toAdd.setEnd(new DateTime(current.getTime())); busyTimes.add(toAdd); } } /** * Merge the overlapping busy times, e.g 9:00-10:00 and 10:00-12:00 will * become one 9:00-12:00 busy time. * * @param busyTimes The busy times to merge. */ private void mergeBusyTimes(List<TimePeriod> busyTimes) { sortBusyTime(busyTimes); // Merge every busy slots. for (int i = 0; i < busyTimes.size(); ++i) { TimePeriod current = busyTimes.get(i); for (int j = i + 1; j < busyTimes.size();) { TimePeriod next = busyTimes.get(j); if (current.getEnd().getValue() - next.getStart().getValue() >= 0) { if (current.getEnd().getValue() - next.getEnd().getValue() < 0) { current.setEnd(next.getEnd()); } busyTimes.remove(j); } else { break; } } } } /** * Find the available meetings from the list of busy times. The busy times are * considered to be on the same day, sorted and merged. * * @param busyTimes The busy times from which to compute the available meeting * @return The available meetings time from 00:00 to 23:59 of the same day. */ private List<AvailableMeetingTime> findAvailableMeetings(List<TimePeriod> busyTimes) { List<AvailableMeetingTime> result = new ArrayList<AvailableMeetingTime>(); for (int i = 0; i < busyTimes.size() - 1;) { AvailableMeetingTime tmp = new AvailableMeetingTime(); tmp.start = new Date(busyTimes.get(i).getEnd().getValue()); tmp.end = new Date(busyTimes.get(++i).getStart().getValue()); result.add(tmp); } return result; } /** * Sort a list of busy times by start time. * * @param busyTime The list of busy times to sort. */ private void sortBusyTime(List<TimePeriod> busyTime) { Collections.sort(busyTime, new Comparator<TimePeriod>() { @Override public int compare(TimePeriod lhs, TimePeriod rhs) { long compare = lhs.getStart().getValue() - rhs.getStart().getValue(); if (compare == 0) { compare = lhs.getEnd().getValue() - rhs.getEnd().getValue(); } return (int) compare; } }); } /** * Split multiple day-meeting times into multiple one-day meeting times. * * @param meetings The busy times to clean. */ private void splitAvailableMeetings(List<AvailableMeetingTime> meetings) { for (int i = 0; i < meetings.size();) { AvailableMeetingTime current = meetings.get(i); if (!DateUtils.isSameDay(current.start, current.end)) { List<AvailableMeetingTime> splitted = splitMeetingTimes(current.start, current.end); meetings.remove(i); meetings.addAll(i, splitted); i += splitted.size(); } else ++i; } } /** * Split a busy time into a set of busy time, each for one day. * * @param startDate Start date to start splitting busy times from. * @param endDate End date to split busy times until. * @return Splitted busy times. */ private List<AvailableMeetingTime> splitMeetingTimes(Date startDate, Date endDate) { List<AvailableMeetingTime> result = new ArrayList<AvailableMeetingTime>(); Calendar currentDay = new GregorianCalendar(); currentDay.setTime(startDate); DateUtils.setTime(currentDay, 23, 59, 59, 999); result.add(new AvailableMeetingTime(startDate, currentDay.getTime())); while (true) { DateUtils.setTime(currentDay, 0, 0, 0, 0); currentDay.add(Calendar.DAY_OF_YEAR, 1); Date currentStart = currentDay.getTime(); if (DateUtils.isSameDay(currentStart, endDate)) { break; } DateUtils.setTime(currentDay, 23, 59, 59, 999); result.add(new AvailableMeetingTime(currentStart, currentDay.getTime())); } result.add(new AvailableMeetingTime(currentDay.getTime(), endDate)); return result; } /** * Filter the meetings which length are less than {@code length}. * * @param meetings The meetings to filter. * @param length The minimum length of the meetings. */ private void filterMeetingLength(List<AvailableMeetingTime> meetings, int length) { for (int i = 0; i < meetings.size();) { int meetingLength = getMeetingLength(meetings.get(i)); if (meetingLength >= length) ++i; else meetings.remove(i); } } /** * Compute the length of the {@code meeting} in minutes. * * @param meeting The meeting from which to compute the length. * @return The length of the meeting in minutes. */ private int getMeetingLength(AvailableMeetingTime meeting) { long difference = meeting.end.getTime() - meeting.start.getTime(); return (int) difference / 60000; } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.util; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; /** * Provides utility functions to manipulate dates and date times. * * @since 2.2 * @author Alain Vongsouvanh (alainv@google.com) */ public class DateUtils { /** * Check if two dates are on the same day. * * @param lhs * @param rhs * @return True if {@code lhs} and {@code rhs} are on the same day. */ public static boolean isSameDay(Date lhs, Date rhs) { return isSameDay(lhs, rhs, TimeZone.getDefault()); } /** * Check if two dates are on the same day. * * @param lhs * @param rhs * @return True if {@code lhs} and {@code rhs} are on the same day. */ public static boolean isSameDay(Date lhs, Date rhs, TimeZone timeZone) { Calendar clhs = new GregorianCalendar(timeZone); Calendar crhs = new GregorianCalendar(timeZone); clhs.setTime(lhs); crhs.setTime(rhs); return clhs.get(Calendar.DAY_OF_YEAR) == crhs.get(Calendar.DAY_OF_YEAR) && clhs.get(Calendar.YEAR) == crhs.get(Calendar.YEAR); } /** * Parse a string formatted as "HH.MM" and returns a Calendar object set with * the time. * * @param time The string to parse * @return The newly created Calendar object with the parsed time. */ public static Calendar getCalendar(String time) { return getCalendar(time, TimeZone.getDefault()); } /** * Parse a string formatted as "HH.MM" and returns a Calendar object set with * the time. * * @param time The string to parse * @return The newly created Calendar object with the parsed time. */ public static Calendar getCalendar(String time, TimeZone timeZone) { Calendar calendar = new GregorianCalendar(timeZone); String[] timeComponents = time.split(":"); setTime(calendar, Integer.parseInt(timeComponents[0]), Integer.parseInt(timeComponents[1]), 0, 0); return calendar; } /** * Set the time of the {@code calendar}. * * @param calendar The calendar to which to set the time * @param hour The hour to set * @param minute The minute to set * @param second The second to set * @param millisecond The millisecond to set */ public static void setTime(Calendar calendar, int hour, int minute, int second, int millisecond) { calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, second); calendar.set(Calendar.MILLISECOND, millisecond); } /** * Set the time from {@code source} to {@code target} and not modify the date. * * @param target The Calendar object to which set the time. * @param source The Calendar object from which to read the time. */ public static void setTime(Calendar target, Calendar source) { target.set(Calendar.HOUR_OF_DAY, source.get(Calendar.HOUR_OF_DAY)); target.set(Calendar.MINUTE, source.get(Calendar.MINUTE)); target.set(Calendar.SECOND, source.get(Calendar.SECOND)); target.set(Calendar.MILLISECOND, source.get(Calendar.MILLISECOND)); } }
Java
package com.google.samples.meetingscheduler.util; import com.google.samples.meetingscheduler.model.Attendee; import java.util.Comparator; /** * Comparator used to sort a list of attendees. The attendees are sorted * alphabetically and from selected to unselected. * * @author Alain Vongsouvanh (alainv@google.com) */ public class AttendeeComparator implements Comparator<Attendee> { /** * Comparator instance to avoid allocating a new one each time it is used. */ private static final AttendeeComparator instance = new AttendeeComparator(); /** * Private constructor. */ private AttendeeComparator() { } /** * Retrieve comparator instance. * * @return The Comparator instance. */ public static AttendeeComparator getInstance() { return instance; } @Override public int compare(Attendee lhs, Attendee rhs) { if (lhs.selected == rhs.selected) return lhs.name.compareToIgnoreCase(rhs.name); else // Put selected on top. return rhs.selected.compareTo(lhs.selected); } }
Java
// Copyright 2011 Google Inc. All Rights Reserved. package com.google.samples.meetingscheduler.util; import com.google.api.client.extensions.android2.AndroidHttp; import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.json.JsonHttpRequest; import com.google.api.client.http.json.JsonHttpRequestInitializer; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.services.calendar.Calendar; import com.google.api.services.calendar.CalendarRequest; /** * @author alainv * */ public class CalendarServiceBuilder { /** * Builds a Calendar service object. * * @param accessToken Access token to use to authorize requests. * @return Calendar service object. */ public static Calendar build(String accessToken) { HttpTransport transport = AndroidHttp.newCompatibleTransport(); JacksonFactory jsonFactory = new JacksonFactory(); GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(accessToken); Calendar service = Calendar.builder(transport, jsonFactory).setApplicationName("Google-Meeting-Scheduler/1.0") .setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() { @Override public void initialize(JsonHttpRequest request) { CalendarRequest calendarRequest = (CalendarRequest) request; // TODO: Get an API key from Google's APIs Console: // https://code.google.com/apis/console. calendarRequest.setKey("<INPUT_YOUR_API_KEY>"); } }).setHttpRequestInitializer(accessProtectedResource).build(); return service; } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.model; import java.io.Serializable; /** * Represent an attendee or a potential attendee to a meeting. * * @author Nicolas Garnier */ public class Attendee implements Serializable { /** For serialization purposes */ private static final long serialVersionUID = 1L; /** Photo of the participant */ public String photoUri; /** Display name of the participant */ public String name; /** Email of the calendar of the participant */ public String email; /** Is the attendee selected? */ public Boolean selected; /** * Default Constructor. */ public Attendee() { } /** * Constructor that initializes the attributes. * * @param name The name of the attendee * @param email The email of the calendar of the attendee * @param photoUri The photo URI of the attendee */ public Attendee(String name, String email, String photoUri) { this.name = name; this.email = email; this.photoUri = photoUri; this.selected = false; } @Override public String toString() { return name; } }
Java
// Copyright 2011 Google Inc. All Rights Reserved. package com.google.samples.meetingscheduler.model; /** * Constants used by the Meeting Scheduler application. * * @author Alain Vongsouvanh (alainv@google.com) */ public class Constants { /** * Should be used by all log statements */ public static final String TAG = "Meeting Scheduler"; public static final String VERSION = "1.0"; /** * onActivityResult request codes: */ public static final int GET_LOGIN = 0; public static final int AUTHENTICATED = 1; public static final int CREATE_EVENT = 2; /** * The type of account that we can use for API operations. */ public static final String ACCOUNT_TYPE = "com.google"; /** * The name of the service to authorize for. */ public static final String OAUTH_SCOPE = "oauth2:https://www.googleapis.com/auth/calendar"; /** * Preference keys. */ public static final String SELECTED_ACCOUNT_PREFERENCE = "selected_account_preference"; public static final String MEETING_LENGTH_PREFERENCE = "meeting_length_preference"; public static final String TIME_SPAN_PREFERENCE = "time_span_preference"; public static final String SKIP_WEEKENDS_PREFERENCE = "skip_weekends_preference"; public static final String USE_WORKING_HOURS_PREFERENCE = "use_working_hours_preference"; public static final String WORKING_HOURS_START_PREFERENCE = "working_hours_start_preference"; public static final String WORKING_HOURS_END_PREFERENCE = "working_hours_end_preference"; }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.model; import java.io.Serializable; import java.util.Date; /** * Available meeting times. * * @author Nicolas Garnier */ public class AvailableMeetingTime implements Serializable, Comparable<AvailableMeetingTime> { /** For Serialization purposes */ private static final long serialVersionUID = 1L; /** The start time of the event */ public Date start; /** The end time of the event */ public Date end; /** * Default Constructor. */ public AvailableMeetingTime() { } /** * Constructor which initializes the start and end Date. * * @param start The Start date of the event * @param end The End date of the event */ public AvailableMeetingTime(Date start, Date end) { this.start = start; this.end = end; } @Override public int compareTo(AvailableMeetingTime another) { int compare = start.compareTo(another.start); if (compare == 0) { return end.compareTo(another.end); } else { return compare; } } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.activity; import com.google.samples.meetingscheduler.R; import com.google.samples.meetingscheduler.adapter.SelectableAttendeeAdapter; import com.google.samples.meetingscheduler.model.Attendee; import com.google.samples.meetingscheduler.model.Constants; import com.google.samples.meetingscheduler.util.AttendeeRetriever; import com.google.samples.meetingscheduler.util.OAuthManager; import android.accounts.Account; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Filter.FilterListener; import android.widget.ListView; import android.widget.Toast; import java.io.NotSerializableException; import java.util.ArrayList; import java.util.List; /** * Activity Screen where the user selects the meeting attendees. * * @author Alain Vongsouvanh (alainv@google.com) */ public class SelectAttendeesActivity extends Activity { /** List of attendees that can be selected. */ private List<Attendee> attendees = new ArrayList<Attendee>(); /** ArrayAdapter for the attendees. */ private SelectableAttendeeAdapter attendeeAdapter; /** UI Attributes. */ private Handler handler = new Handler(); private ProgressDialog progressBar; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // Creating main layout setContentView(R.layout.select_attendees); // Custom title bar if (customTitleSupported) { getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.app_title_select_attendees); } // Adding action to the button addFindMeetingButtonListener(); setAttendeeListView(); } /** * Add the OnClickListner to the findMeetingButton. */ private void addFindMeetingButtonListener() { Button findMeetingButton = (Button) findViewById(R.id.find_time_button); findMeetingButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { List<String> selectedAttendees = getSelectedAttendees(); if (selectedAttendees.size() > 0) { Log.i(Constants.TAG, "Find meeting button pressed - about to launch SelectMeeting activity"); // the results are called on widgetActivityCallback try { startActivity(SelectMeetingTimeActivity.createViewIntent(getApplicationContext(), selectedAttendees)); } catch (NotSerializableException e) { Log.e(Constants.TAG, "Intent is not run because of a NotSerializableException. " + "Probably the selectedAttendees list which is not serializable."); } Log.i(Constants.TAG, "Find meeting button pressed - successfully launched SelectMeeting activity"); } else { Toast toast = Toast.makeText(getApplicationContext(), "You must select at least 1 attendee", 1000); toast.show(); } } }); } /** * Populate the list of attendees into the activity's ListView. */ private void setAttendeeListView() { final ListView attendeeListView = (ListView) findViewById(R.id.attendee_list); initializeTextFilter(attendeeListView); attendeeAdapter = new SelectableAttendeeAdapter(this, attendees); attendeeAdapter.sort(); attendeeListView.setAdapter(attendeeAdapter); // Adding click event to attendees Widgets attendeeListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // We use position -1 to ignore the header. Attendee attendee = (Attendee) attendeeListView.getItemAtPosition(position); attendee.selected = !attendee.selected; attendeeAdapter.sort(); } }); } /** * Retrieve the list of attendees from the phone's Contacts database. */ private void retrieveAttendees() { // Retrieves the attendees on a separate thread. new Thread(new Runnable() { @Override public void run() { AttendeeRetriever attendeeRetriever = new AttendeeRetriever(SelectAttendeesActivity.this, OAuthManager.getInstance() .getAccount()); final List<Attendee> newAttendees = attendeeRetriever.getAttendees(); // Update the progress bar handler.post(new Runnable() { @Override public void run() { if (newAttendees != null) { attendees.clear(); attendees.addAll(newAttendees); attendeeAdapter.sort(); attendeeAdapter.notifyDataSetChanged(); } Log.d(Constants.TAG, "Got attendees, dismissing progress bar"); if (progressBar != null) { progressBar.dismiss(); Log.d(Constants.TAG, "Progress bar should have been dismissed"); } } }); } }).start(); // Show a progress bar while the attendees are retrieved from the phone's // database. progressBar = ProgressDialog.show(this, null, getString(R.string.retrieve_contacts_wait_text), true); } /** * Add on text changed listener to filter the attendee list view. * * @param view ListView to add the edit text to. */ private void initializeTextFilter(ListView view) { EditText editText = (EditText) getLayoutInflater().inflate(R.layout.attendees_text_filter, null); editText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (attendeeAdapter != null) { attendeeAdapter.getFilter().filter(s, new FilterListener() { @Override /** * Sort the array once the filter has been completed. */ public void onFilterComplete(int count) { attendeeAdapter.sort(); } }); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); view.addHeaderView(editText); } /** * Returns the list of currently selected attendees. * * @return the list of currently selected attendees */ private List<String> getSelectedAttendees() { List<String> selectedAttendees = new ArrayList<String>(); if (attendees != null) { for (Attendee attendee : attendees) { if (attendee.selected) { selectedAttendees.add(attendee.email); } } } return selectedAttendees; } /** * Initialize the contents of the Activity's options menu. */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.settings, menu); return true; } /** * Called whenever an item in the options menu is selected. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.menu.settings: startActivity(PreferencesActivity.createViewIntent(getApplicationContext())); return true; default: return super.onOptionsItemSelected(item); } } /** * Update the settings text whenever this activity resumes */ @Override protected void onResume() { super.onResume(); getAccount(); } /** * Prompt user to choose an account and retrieve attendees from phone's * database. */ private void getAccount() { OAuthManager.getInstance().doLogin(false, this, new OAuthManager.AuthHandler() { @Override public void handleAuth(Account account, String authToken) { if (account != null) { retrieveAttendees(); } } }); } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.activity; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.samples.meetingscheduler.R; import com.google.samples.meetingscheduler.adapter.EventExpandableListAdapter; import com.google.samples.meetingscheduler.model.AvailableMeetingTime; import com.google.samples.meetingscheduler.model.Constants; import com.google.samples.meetingscheduler.util.DateUtils; import com.google.samples.meetingscheduler.util.EventTimesRetriever; import com.google.samples.meetingscheduler.util.FreeBusyTimesRetriever; import com.google.samples.meetingscheduler.util.OAuthManager; import android.accounts.Account; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.ExpandableListView; import android.widget.Toast; import java.io.IOException; import java.io.NotSerializableException; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import java.util.List; /** * Activity Screen where the user selects the meeting time between the meeting * times proposed. * * @author Nicolas Garnier */ public class SelectMeetingTimeActivity extends Activity { /** The constant to store the selectedAttendees list in an intent */ private static final String SELECTED_ATTENDEES = "SELECTED_ATTENDEES"; /** The constant to store an error message on result. */ public static final String MESSAGE = "MESSAGE"; /** UI attributes. */ private Handler handler = new Handler(); private ProgressDialog progressBar = null; /** The date from which to start to look for available meeting times */ private Calendar startDate; private int timeSpan; private int meetingLength; private List<String> selectedAttendees; private List<AvailableMeetingTime> availableMeetingTimes; /** * Called when the activity is first created. */ @SuppressWarnings("unchecked") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // Creating main layout setContentView(R.layout.select_meeting_time); // Custom title bar if (customTitleSupported) { getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.app_title_select_time); } // Getting the selectedAttendees list from the intent Intent intent = getIntent(); selectedAttendees = (List<String>) intent.getSerializableExtra(SELECTED_ATTENDEES); availableMeetingTimes = new ArrayList<AvailableMeetingTime>(); // Today at midnight. startDate = Calendar.getInstance(); startDate.set(Calendar.HOUR_OF_DAY, 0); startDate.clear(java.util.Calendar.HOUR); startDate.clear(java.util.Calendar.MINUTE); startDate.clear(java.util.Calendar.SECOND); startDate.clear(java.util.Calendar.MILLISECOND); initializeFindMoreButton(); getAuthToken(); } /** * Returns an Intent that will display this Activity. * * @param context The application Context * @param selectedAttendees The list of selected Attendees. Should be of a * Serializable List type * @return An intent that will display this Activity * @throws NotSerializableException If the {@code selectedAttendees} is not * serializable */ public static Intent createViewIntent(Context context, List<String> selectedAttendees) throws NotSerializableException { Intent intent = new Intent(context, SelectMeetingTimeActivity.class); if (!(selectedAttendees instanceof Serializable)) { Log.e(Constants.TAG, "List<Attendee> selectedAttendees is not serializable"); throw new NotSerializableException(); } intent.putExtra(SELECTED_ATTENDEES, (Serializable) selectedAttendees); Log.e(Constants.TAG, "Successfully serialized List<Attendee> selectedAttendees in the intent"); intent.setClass(context, SelectMeetingTimeActivity.class); return intent; } /** * Called when sub activity returns. */ @Override public void onActivityResult(int requestCode, int resultCode, final Intent results) { super.onActivityResult(requestCode, resultCode, results); switch (requestCode) { case Constants.CREATE_EVENT: if (resultCode == RESULT_OK) { Toast.makeText(this, getString(R.string.event_creation_success), Toast.LENGTH_SHORT) .show(); } else if (resultCode == RESULT_FIRST_USER && results != null) { Toast.makeText( this, getString(R.string.event_creation_failure) + ": " + results.getStringExtra(CreateEventActivity.MESSAGE), Toast.LENGTH_LONG).show(); } break; } } /** * Set the "Find More" button onClick's action. */ private void initializeFindMoreButton() { Button findMore = (Button) findViewById(R.id.find_more_meeting_time_button); findMore.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (OAuthManager.getInstance().getAuthToken() != null) { findMeetingTimes(5); } else getAuthToken(); } }); } /** * Authenticates into the Calendar API using the selected account. */ private void getAuthToken() { OAuthManager authManager = OAuthManager.getInstance(); if (authManager.getAuthToken() != null) { findMeetingTimes(5); } else { authManager.doLogin(false, this, new OAuthManager.AuthHandler() { @Override public void handleAuth(Account account, String authToken) { onActivityResult(Constants.AUTHENTICATED, RESULT_OK, null); } }); } } /** * Set preferences for EventTimesRetriever. */ private void setPreferences(EventTimesRetriever eventTimeRetriever) { if (eventTimeRetriever != null) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); eventTimeRetriever.setSkipWeekEnds(preferences.getBoolean(Constants.SKIP_WEEKENDS_PREFERENCE, true)); eventTimeRetriever.setUseWorkingHours(preferences.getBoolean( Constants.USE_WORKING_HOURS_PREFERENCE, true)); eventTimeRetriever.setWorkingHoursStart(DateUtils.getCalendar(preferences.getString( Constants.WORKING_HOURS_START_PREFERENCE, getString(R.string.working_hours_start_default_value)))); eventTimeRetriever.setWorkingHoursEnd(DateUtils.getCalendar(preferences.getString( Constants.WORKING_HOURS_END_PREFERENCE, getString(R.string.working_hours_end_default_value)))); timeSpan = Integer.parseInt(preferences.getString(Constants.TIME_SPAN_PREFERENCE, getString(R.string.time_span_default_value))); meetingLength = Integer.parseInt(preferences.getString(Constants.MEETING_LENGTH_PREFERENCE, getString(R.string.meeting_length_default_value))); } } /** * Find available meeting times. * * @param tryNumber Number of try. */ private void findMeetingTimes(final int tryNumber) { if (progressBar == null) { // Show a progress bar while the meeting times are computed. progressBar = ProgressDialog.show(this, null, getString(R.string.find_meeting_time_wait_text), true); } // Retrieves the common free time on a separate thread. new Thread(new Runnable() { @Override public void run() { boolean done = true; try { // Calculating the available meeting times from the selectedAttendees // and the settings final EventTimesRetriever eventTimeRetriever = new EventTimesRetriever(new FreeBusyTimesRetriever(OAuthManager.getInstance() .getAuthToken())); setPreferences(eventTimeRetriever); final List<AvailableMeetingTime> newTimes = eventTimeRetriever.getAvailableMeetingTime(selectedAttendees, startDate.getTime(), timeSpan, meetingLength); // Update the list of available meeting times. handler.post(new Runnable() { @Override public void run() { populateMeetingTimes(newTimes); // Set "find more" action to retrieve next meeting times. startDate.add(Calendar.DAY_OF_YEAR, timeSpan); } }); } catch (final IOException e) { if (e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).getResponse(); int statusCode = response.getStatusCode(); try { response.ignore(); } catch (IOException e1) { e1.printStackTrace(); } if (statusCode == 401 && (tryNumber - 1) > 0) { done = false; Log.d(Constants.TAG, "Got 401, refreshing token."); OAuthManager.getInstance().doLogin(true, SelectMeetingTimeActivity.this, new OAuthManager.AuthHandler() { @Override public void handleAuth(Account account, String authToken) { findMeetingTimes(tryNumber - 1); } }); } } if (done) { handler.post(new Runnable() { @Override public void run() { Toast.makeText(SelectMeetingTimeActivity.this, getString(R.string.available_time_retrieval_failure) + ": " + e.getMessage(), Toast.LENGTH_LONG).show(); } }); } } if (done) { // Update the progress bar handler.post(new Runnable() { @Override public void run() { if (progressBar != null) { progressBar.dismiss(); progressBar = null; } } }); } } }).start(); } /** * Displays the available meeting times on the screen. * * @param newTimes The meeting times to display. */ private void populateMeetingTimes(List<AvailableMeetingTime> newTimes) { availableMeetingTimes.addAll(newTimes); // Adding the available meeting times to the UI ExpandableListView meetingListContainer = (ExpandableListView) findViewById(R.id.meeting_list); meetingListContainer.setAdapter(new EventExpandableListAdapter(this, availableMeetingTimes, meetingLength, new EventExpandableListAdapter.EventHandler() { @Override public void handleEventSelected(long startTime, long endTime) { try { startActivityForResult(CreateEventActivity.createViewIntent( SelectMeetingTimeActivity.this, selectedAttendees, startTime, endTime), Constants.CREATE_EVENT); } catch (NotSerializableException e) { Log.e(Constants.TAG, "Intent is not run because of a NotSerializableException. " + "Probably the selectedAttendees list which is not serializable."); } } })); } }
Java
/* * Copyright (c) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.samples.meetingscheduler.activity; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.util.DateTime; import com.google.api.services.calendar.Calendar; import com.google.api.services.calendar.model.Event; import com.google.api.services.calendar.model.EventAttendee; import com.google.api.services.calendar.model.EventDateTime; import com.google.samples.meetingscheduler.R; import com.google.samples.meetingscheduler.model.Constants; import com.google.samples.meetingscheduler.util.CalendarServiceBuilder; import com.google.samples.meetingscheduler.util.OAuthManager; import android.accounts.Account; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import java.io.IOException; import java.io.NotSerializableException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Activity displaying a UI to edit event's Title, Description and Location. * Clicking on "Create event" send a request to the API to create the events * with the specified attendees on the user's primary calendar. * * @since 2.2 * @author Alain Vongsouvanh (alainv@google.com) */ public class CreateEventActivity extends Activity { /** The constant to store the selectedAttendees list in an intent */ private static final String SELECTED_ATTENDEES = "SELECTED_ATTENDEES"; private static final String START_DATE = "START_DATE"; private static final String END_DATE = "END_DATE"; /** The constant to store an error message on result. */ public static final String MESSAGE = "MESSAGE"; /** UI attributes. */ private Handler handler = new Handler(); private ProgressDialog progressBar = null; /** Class attributes retrieved from the intent. */ List<String> selectedAttendees; private DateTime startDate; private DateTime endDate; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); // Creating main layout setContentView(R.layout.set_event_details); // Custom title bar if (customTitleSupported) { getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.app_title_set_event_details); } getParameters(); setSaveButtonAction(); } /** * Set action when the Save Button is clicked. */ private void setSaveButtonAction() { Button saveButton = (Button) findViewById(R.id.save_event_button); saveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final String title = getString(R.id.event_title_text); final String where = getString(R.id.event_where_text); final String description = getString(R.id.event_description_text); final boolean sendEventNotifications = getBoolean(R.id.send_event_notifications_checkbox); if (OAuthManager.getInstance().getAuthToken() == null) { OAuthManager.getInstance().doLogin(false, CreateEventActivity.this, new OAuthManager.AuthHandler() { @Override public void handleAuth(Account account, String authToken) { createEvent(title, where, description, sendEventNotifications, 5); } }); } else { createEvent(title, where, description, sendEventNotifications, 5); } } private String getString(int viewId) { EditText view = (EditText) findViewById(viewId); if (view != null) return view.getText().toString(); else return null; } private boolean getBoolean(int viewId) { CheckBox view = (CheckBox) findViewById(viewId); if (view != null) return view.isChecked(); else return false; } }); } /** * Send a request to the Calendar API to create an event wit the specified * parameters. * * @param title Event's title. * @param where Event's location. * @param description Event's description * @param sendEventNotifications Whether or not to send a notification to * attendees. */ private void createEvent(final String title, final String where, final String description, final boolean sendEventNotifications, final int tryNumber) { // Show a progress bar while the common free times are computed. if (progressBar == null) { progressBar = ProgressDialog.show(CreateEventActivity.this, null, CreateEventActivity.this.getString(R.string.create_event_wait_text), true); } // Try creating the event on a separate thread. new Thread(new Runnable() { @Override public void run() { boolean done = true; try { Calendar service = CalendarServiceBuilder.build(OAuthManager.getInstance().getAuthToken()); Event newEvent = new Event(); List<EventAttendee> attendees = new ArrayList<EventAttendee>(); newEvent.setSummary(title); newEvent.setLocation(where); newEvent.setDescription(description); newEvent.setStart(new EventDateTime().setDateTime(startDate)); newEvent.setEnd(new EventDateTime().setDateTime(endDate)); for (String attendee : selectedAttendees) { attendees.add(new EventAttendee().setEmail(attendee)); } newEvent.setAttendees(attendees); service.events().insert("primary", newEvent).setSendNotifications(sendEventNotifications) .execute(); setResult(RESULT_OK); } catch (IOException e) { if (e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).getResponse(); int statusCode = response.getStatusCode(); try { response.ignore(); } catch (IOException e1) { e1.printStackTrace(); } if (statusCode == 401 && (tryNumber - 1) > 0) { done = false; Log.d(Constants.TAG, "Got 401, refreshing token."); OAuthManager.getInstance().doLogin(true, CreateEventActivity.this, new OAuthManager.AuthHandler() { @Override public void handleAuth(Account account, String authToken) { createEvent(title, where, description, sendEventNotifications, tryNumber - 1); } }); } } if (done) { Intent data = new Intent(); data.putExtra(MESSAGE, e.getMessage()); setResult(RESULT_FIRST_USER, data); } } if (done) { // Update the progress bar handler.post(new Runnable() { @Override public void run() { if (progressBar != null) { progressBar.dismiss(); progressBar = null; } CreateEventActivity.this.finish(); } }); } } }).start(); } /** * Get the parameters passed into this activity. */ @SuppressWarnings("unchecked") private void getParameters() { // Getting the selectedAttendees list from the intent final Intent intent = getIntent(); selectedAttendees = (List<String>) intent.getSerializableExtra(SELECTED_ATTENDEES); // Default values are "now" and "now + 1hour". startDate = new DateTime(intent.getLongExtra(START_DATE, java.util.Calendar.getInstance() .getTimeInMillis()), 0); endDate = new DateTime(intent.getLongExtra(END_DATE, java.util.Calendar.getInstance() .getTimeInMillis() + 3600000), 0); } /** * Returns an Intent that will display this Activity. * * @param context The application Context * @param selectedAttendees The list of selected Attendees. Should be of a * Serializable List type * @param startDate The start date of the event to create * @param endDate The end date of the event to create * @return An intent that will display this Activity * @throws NotSerializableException If the {@code selectedAttendees} is not * serializable */ public static Intent createViewIntent(Context context, List<String> selectedAttendees, long startDate, long endDate) throws NotSerializableException { Intent intent = new Intent(context, SelectMeetingTimeActivity.class); if (!(selectedAttendees instanceof Serializable)) { Log.e(Constants.TAG, "List<Attendee> selectedAttendees is not serializable"); throw new NotSerializableException(); } intent.putExtra(SELECTED_ATTENDEES, (Serializable) selectedAttendees); intent.putExtra(START_DATE, startDate); intent.putExtra(END_DATE, endDate); intent.setClass(context, CreateEventActivity.class); return intent; } }
Java
// Copyright 2011 Google Inc. All Rights Reserved. package com.google.samples.meetingscheduler.activity; import com.google.samples.meetingscheduler.R; import com.google.samples.meetingscheduler.model.Constants; import com.google.samples.meetingscheduler.util.OAuthManager; import com.google.samples.meetingscheduler.util.OAuthManager.AuthHandler; import android.accounts.Account; import android.app.Dialog; import android.app.TimePickerDialog; import android.app.TimePickerDialog.OnTimeSetListener; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.text.format.DateFormat; import android.widget.TimePicker; /** * Activity showing the user's preferences. * * @author Alain Vongsouvanh (alainv@google.com) */ public class PreferencesActivity extends PreferenceActivity { /** Sub-dialog IDs. */ private final int WORKING_HOURS_START_ID = 0; private final int WORKING_HOURS_END_ID = 1; private SharedPreferences preferences; /** * Returns an Intent that will display this Activity. * * @param context The application Context * @return An intent that will display this Activity */ public static Intent createViewIntent(Context context) { Intent intent = new Intent(context, PreferencesActivity.class); intent.setClass(context, PreferencesActivity.class); return intent; } /** * Initialize this activity */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); preferences = PreferenceManager.getDefaultSharedPreferences(this); final Preference selectedAccountPref = getPreferenceScreen().findPreference(Constants.SELECTED_ACCOUNT_PREFERENCE); String selectedAccount = preferences.getString(Constants.SELECTED_ACCOUNT_PREFERENCE, null); if (selectedAccount != null && selectedAccount.length() > 0) { selectedAccountPref.setSummary(selectedAccount); } selectedAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { OAuthManager.getInstance().doLogin("", true, PreferencesActivity.this, new AuthHandler() { @Override public void handleAuth(Account account, String authToken) { if (account != null) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(PreferencesActivity.this).edit(); editor.putString(Constants.SELECTED_ACCOUNT_PREFERENCE, account.name); editor.commit(); selectedAccountPref.setSummary(account.name); } } }); return true; } }); setWorkingHoursDialog(Constants.WORKING_HOURS_START_PREFERENCE, WORKING_HOURS_START_ID); setWorkingHoursDialog(Constants.WORKING_HOURS_END_PREFERENCE, WORKING_HOURS_END_ID); } /** * Called when showDialog is called to create and show TimePickerDialogs. */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case WORKING_HOURS_START_ID: return createTimePickerDialog(Constants.WORKING_HOURS_START_PREFERENCE, getString(R.string.working_hours_start_default_value)); case WORKING_HOURS_END_ID: return createTimePickerDialog(Constants.WORKING_HOURS_END_PREFERENCE, getString(R.string.working_hours_end_default_value)); } return null; } /** * Set working hour start & end preferences click action. * * @param key Preference's key. * @param dialogID Preference dialog's ID. */ private void setWorkingHoursDialog(String key, final int dialogID) { getPreferenceScreen().findPreference(key).setOnPreferenceClickListener( new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { showDialog(dialogID); return true; } }); } /** * Create a time picker dialog to select working hours preference. * * @param key Preference key. * @param defaultValue Default value to use. * @return TimePickerDialog. */ private Dialog createTimePickerDialog(final String key, String defaultValue) { String workingHoursString = preferences.getString(key, defaultValue); String[] workingHours = workingHoursString.split(":"); return new TimePickerDialog(this, new OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(PreferencesActivity.this).edit(); editor.putString(key, hourOfDay + ":" + minute); editor.commit(); } }, Integer.parseInt(workingHours[0]), Integer.parseInt(workingHours[1]), DateFormat.is24HourFormat(this)); } }
Java
package org.naba.mdlwr.data; public class InputData { private String username; private String password; private String serviceId; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getServiceId() { return serviceId; } public void setServiceId(String serviceId) { this.serviceId = serviceId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
Java
package org.naba.mdlwr.data; import java.util.Date; public class OutputData { private String title; private String description; private Date publishDate; private String originalSource; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getOriginalSource() { return originalSource; } public void setOriginalSource(String originalSource) { this.originalSource = originalSource; } public Date getPublishDate() { return publishDate; } public void setPublishDate(Date publishDate) { this.publishDate = publishDate; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
Java
package org.naba.mdlwr.endpoint; import org.naba.mdlwr.data.*; import org.naba.mdlwr.pojo.*; import org.springframework.remoting.jaxrpc.ServletEndpointSupport; public class SpringWSEndPoint extends ServletEndpointSupport implements ITestSpringWS { private ITestSpringWS springWS; protected void onInit() { this.springWS = (ITestSpringWS) getWebApplicationContext().getBean("springWS"); } public OutputData fetchContent(InputData in) { return springWS.fetchContent(in); } }
Java
package org.naba.mdlwr.pojo; import org.naba.mdlwr.data.*; public interface ITestSpringWS { public OutputData fetchContent(InputData in); }
Java
package org.naba.mdlwr.pojo; import org.naba.mdlwr.data.*; import java.util.Date; public class TestSpringWS implements ITestSpringWS { public OutputData fetchContent(InputData in) { OutputData out = new OutputData(); out.setTitle("Title here"); out.setDescription("Description here"); out.setPublishDate(new Date()); out.setOriginalSource("www.eramuslim.com"); return out; } }
Java
package com.ecomcs.annuaire; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.net.MalformedURLException; import java.net.URL; import java.security.GeneralSecurityException; import com.google.appengine.api.oauth.OAuthService; import com.google.appengine.api.oauth.OAuthServiceFactory; import com.google.appengine.api.users.User; import com.google.gdata.client.contacts.ContactsService; import com.google.gdata.client.http.AuthSubUtil; import com.google.gdata.data.PlainTextConstruct; import com.google.gdata.data.contacts.ContactEntry; import com.google.gdata.data.contacts.ContactFeed; import com.google.gdata.data.extensions.Email; import com.google.gdata.data.extensions.ExtendedProperty; import com.google.gdata.data.extensions.PhoneNumber; import com.google.gdata.util.AuthenticationException; import com.google.gdata.util.Namespaces; import com.google.gdata.util.PreconditionFailedException; import com.google.gdata.util.ServiceException; public class GoogleConnector { ContactsService myService; String connectorUser = "admin.apps@mf-world.com"; String connectorPasswordUser = "password007"; String domainName = "mf-world.com"; public GoogleConnector() throws AuthenticationException{ System.out.println("ok"); System.out.println("la"); /* User user = null; try { OAuthService oauth = OAuthServiceFactory.getOAuthService(); user = oauth.getCurrentUser(); } catch (Exception e) { // The consumer made an invalid OAuth request, used an access token that was // revoked, or did not provide OAuth information. // ... } this.myService = new ContactsService("annuaire-exampleApp-1"); this.myService.set */ this.myService = new ContactsService("annuaire-exampleApp-1"); String next = "http://localhost:8888/annuaire"; String scope = "http://www.google.com/m8/feeds/"; boolean secure = false; boolean session = true; String authSubLogin = AuthSubUtil.getRequestUrl(next, scope, secure, session); System.out.println(authSubLogin); String token = AuthSubUtil.getTokenFromReply(authSubLogin); System.out.println(token); String sessionToken = null; try { sessionToken = AuthSubUtil.exchangeForSessionToken(token, null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (GeneralSecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.myService.setAuthSubToken(sessionToken, null); /* this.myService = new ContactsService("annuaire-exampleApp-1"); this.myService.setUserCredentials(this.connectorUser, this.connectorPasswordUser); */ /* } catch (AuthenticationException e) { e.printStackTrace(); }*/ } void createSharedContact(String name, String note, String contactEmail){ ContactEntry contact = new ContactEntry(); contact.setTitle(new PlainTextConstruct(name)); contact.setContent(new PlainTextConstruct(note)); Email email = new Email(); email.setAddress(contactEmail); email.setRel("http://schemas.google.com/g/2005#home"); email.setPrimary(true); contact.addEmailAddress(email); ExtendedProperty favouritecar = new ExtendedProperty(); favouritecar.setName("favourite car"); favouritecar.setValue("Toyota Supra mk4 TwinTurbo"); contact.addExtendedProperty(favouritecar); URL postUrl = null; try { postUrl = new URL("https://www.google.com/m8/feeds/contacts/"+this.domainName+"/full"); } catch (MalformedURLException e) { e.printStackTrace(); } ContactEntry back = null; try { back = this.myService.insert(postUrl, contact); } catch (Exception e) { e.printStackTrace(); } System.out.println(); System.out.println(back.getContent()); } public void showSharedContact(){ URL feedUrl = null; try { feedUrl = new URL("https://www.google.com/m8/feeds/contacts/"+this.domainName+"/full"); } catch (MalformedURLException e) { e.printStackTrace(); } ContactFeed resultFeed = null; try { resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class); } catch (Exception e) { e.printStackTrace(); } System.out.println(resultFeed.getTitle().getPlainText()); System.out.println("Numbers of contact(s) : "+ resultFeed.getEntries().size()); for (int i = 0; i < resultFeed.getEntries().size(); i++) { ContactEntry entry = resultFeed.getEntries().get(i); System.out.println(entry.getTitle().getPlainText()); for(int j = 0; j<entry.getEmailAddresses().size(); j++){ System.out.println(entry.getEmailAddresses().get(j).getAddress()); } for(int j = 0; j<entry.getPhoneNumbers().size(); j++){ System.out.println(entry.getPhoneNumbers().get(j).getPhoneNumber()); } } } /* public void showDomainContact(){ URL feedUrl = null; try { feedUrl = new URL("https://www.google.com/m8/feeds/profiles/domain/"+this.domainName+"/full"); } catch (MalformedURLException e) { e.printStackTrace(); } ContactFeed resultFeed = null; try { resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class); } catch (Exception e) { e.printStackTrace(); } System.out.println(resultFeed.getTitle().getPlainText()); System.out.println("Numbers of contact(s) : "+ resultFeed.getEntries().size()); for (int i = 0; i < resultFeed.getEntries().size(); i++) { ContactEntry entry = resultFeed.getEntries().get(i); System.out.println(entry.getTitle().getPlainText()); for(int j = 0; j<entry.getEmailAddresses().size(); j++){ System.out.println(entry.getEmailAddresses().get(j).getAddress()); } for(int j = 0; j<entry.getPhoneNumbers().size(); j++){ System.out.println(entry.getPhoneNumbers().get(j).getPhoneNumber()); } } }*/ public void showDomainContact(PrintWriter out){ URL feedUrl = null; try { feedUrl = new URL("https://www.google.com/m8/feeds/profiles/domain/"+this.domainName+"/full"); } catch (MalformedURLException e) { e.printStackTrace(); } ContactFeed resultFeed = null; try { resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class); } catch (Exception e) { e.printStackTrace(); } out.println(resultFeed.getTitle().getPlainText()); out.println("Numbers of contact(s) : "+ resultFeed.getEntries().size()); for (int i = 0; i < resultFeed.getEntries().size(); i++) { ContactEntry entry = resultFeed.getEntries().get(i); out.println(entry.getTitle().getPlainText()); /*for(int j = 0; j<entry.getEmailAddresses().size(); j++){ out.println(entry.getEmailAddresses().get(j).getAddress()); } for(int j = 0; j<entry.getPhoneNumbers().size(); j++){ out.println(entry.getPhoneNumbers().get(j).getPhoneNumber()); }*/ } } /* public void findProfile(String userAdress){ URL feedUrl = null; try { feedUrl = new URL("https://www.google.com/m8/feeds/profiles/domain/"+this.domainName+"/full"); } catch (MalformedURLException e) { e.printStackTrace(); } ContactFeed resultFeed = null; try { resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class); } catch (IOException | ServiceException e) { e.printStackTrace(); } for (int i = 0; i < resultFeed.getEntries().size(); i++) { ContactEntry entry = resultFeed.getEntries().get(i); for(int j = 0; j<entry.getEmailAddresses().size(); j++){ if (entry.getEmailAddresses().get(j).getAddress().equals(userAdress)){ System.out.println(entry.getTitle().getPlainText()); System.out.println(entry.getLinks().get(0).getHref()); } } } } */ public ContactEntry getDomainContact(String userAdress){ URL feedUrl = null; try { feedUrl = new URL("https://www.google.com/m8/feeds/profiles/domain/"+this.domainName+"/full"); } catch (MalformedURLException e) { e.printStackTrace(); } ContactFeed resultFeed = null; try { resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class); } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < resultFeed.getEntries().size(); i++) { ContactEntry entry = resultFeed.getEntries().get(i); for(int j = 0; j<entry.getEmailAddresses().size(); j++){ if (entry.getEmailAddresses().get(j).getAddress().equals(userAdress)){ return entry; } } } return null; } public ContactEntry getSharedContact(String userAdress){ URL feedUrl = null; try { feedUrl = new URL("https://www.google.com/m8/feeds/contacts/"+this.domainName+"/full"); } catch (MalformedURLException e) { e.printStackTrace(); } ContactFeed resultFeed = null; try { resultFeed = this.myService.getFeed(feedUrl, ContactFeed.class); } catch (Exception e) { e.printStackTrace(); } /* for (int i = 0; i < resultFeed.getEntries().size(); i++) { ContactEntry entry = resultFeed.getEntries().get(i); System.out.println(entry.getTitle().getPlainText()); System.out.println(entry.getEmailAddresses().get(0).getAddress()); }*/ for (int i = 0; i < resultFeed.getEntries().size(); i++) { ContactEntry entry = resultFeed.getEntries().get(i); for(int j = 0; j<entry.getEmailAddresses().size(); j++){ if (entry.getEmailAddresses().get(j).getAddress().equals(userAdress)){ return entry; } } } return null; } public void updateDomainContactPhoneNumber(ContactEntry entryToUpdate, String number) throws ServiceException, IOException { PhoneNumber phoneNumber = new PhoneNumber(); phoneNumber.setPhoneNumber(number); phoneNumber.setRel(Namespaces.inflate("work")); entryToUpdate.addPhoneNumber(phoneNumber); entryToUpdate.getStatus().setIndexed(false); URL editUrl = new URL(entryToUpdate.getEditLink().getHref()); ContactEntry contactEntry = null; try { contactEntry = myService.update(editUrl, entryToUpdate); } catch (PreconditionFailedException e) { e.printStackTrace(); } } public void updateSharedContactPhoneNumber(ContactEntry entryToUpdate, String number) throws ServiceException, IOException { PhoneNumber phoneNumber = new PhoneNumber(); phoneNumber.setPhoneNumber(number); phoneNumber.setRel(Namespaces.inflate("work")); entryToUpdate.addPhoneNumber(phoneNumber); //entryToUpdate.getStatus().setIndexed(false); URL editUrl = new URL(entryToUpdate.getEditLink().getHref()); ContactEntry contactEntry = null; try { contactEntry = myService.update(editUrl, entryToUpdate); } catch (PreconditionFailedException e) { e.printStackTrace(); } } }
Java
package com.ecomcs.annuaire; import java.io.IOException; import javax.servlet.http.*; import com.google.gdata.util.AuthenticationException; //@SuppressWarnings("serial") public class AnnuaireServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/plain"); resp.getWriter().println("Hello, world"); GoogleConnector connector; try { connector = new GoogleConnector(); connector.showDomainContact(resp.getWriter()); } catch (Exception e) { e.printStackTrace(); } } }
Java
package annotationtablemodel; import javax.swing.SwingUtilities; /** * * @author Dmitry */ public class AnnotationTableModel { /** * @param args the command line arguments */ public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MainDialog dialog=new MainDialog(); dialog.setVisible(true); } }); } }
Java
package annotationtablemodel; import annotationtablemodel.suppx.ems.annotatedtable.annotations.AnnotatedTableField; import annotationtablemodel.suppx.ems.annotatedtable.annotations.AnnotatedTableFieldType; /** * @author Dmitry Savchenko */ public class User { public static final int NAME=0; public static final int HEIGHT=1; @AnnotatedTableField(column="Name", id=NAME) private String name; @AnnotatedTableField(column="Height", id=HEIGHT) private int height; public int getHeight() { return height; } public String getHeightStringValue(){ return ""+height+" см."; } public void setHeight(int height) { this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Java
package annotationtablemodel.suppx.ems.annotatedtable; /** * * @author Dmitry */ public enum COLUMNTYPE { STRING, INTEGER, DOUBLE, BOOLEAN, CURRENCY, PERCENT, DATE, TIMESTAMP, NULL }
Java
package annotationtablemodel.suppx.ems.annotatedtable; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; /** * @author Dmitry Savchenko */ public class AnnotatedTableModel<T> extends AbstractTableModel { private ClassData classData; private ColumnData[] visibleColumns = null; private List<T> data; public AnnotatedTableModel(Class<T> clazz) throws NoSuchMethodException, Exception { setClass(clazz); } final public void setClass(Class clazz) throws NoSuchMethodException, Exception { ClassData cData = new ClassData(); cData.setClazz(clazz); classData = cData; setVisibleColumns(getDefaultAllVisibleColumns(classData)); } private static int[] getDefaultAllVisibleColumns(ClassData classData) { int size = classData.getColumns().size(); int[] columnIds = new int[size]; for (int i = 0; i < size; i++) { columnIds[i] = classData.getColumns().get(i).getId(); } return columnIds; } public void setVisibleColumns(int... visibleColumnsIds) { visibleColumns = new ColumnData[visibleColumnsIds.length]; for (int i = 0; i < visibleColumnsIds.length; i++) { visibleColumns[i] = classData.getColumnDataById(visibleColumnsIds[i]); } } public void setData(List<T>data){ if(data==null){ this.data=new ArrayList<T>(0); }else{ this.data=data; } } @Override public String getColumnName(int column) { return visibleColumns[column].getColumnName(); } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { return visibleColumns.length; } @Override public Object getValueAt(int rowIndex, int columnIndex) { Object record = data.get(rowIndex); ColumnData column = visibleColumns[columnIndex]; String value = null; if (column.getVisualFormatter() != null) { try { value = (String) column.getVisualFormatter().invoke(record); } catch (Exception ex) { ex.printStackTrace(); } } else { try { Object object = column.getGetter().invoke(record); if (object != null) { value = object.toString(); } else { value = "NULL"; } } catch (Exception ex) { ex.printStackTrace(); } } return value; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { } }
Java
package annotationtablemodel.suppx.ems.annotatedtable; import annotationtablemodel.suppx.ems.annotatedtable.annotations.AnnotatedTableField; import annotationtablemodel.suppx.ems.annotatedtable.annotations.AnnotatedTableFieldType; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * @author Dmitry Savchenko */ public class ClassData { private Class clazz = null; private List<ColumnData> columns = null; private Map<Integer, ColumnData> columnMap = new TreeMap<Integer, ColumnData>(); public Class getClazz() { return clazz; } public void setClazz(Class clazz) throws NoSuchMethodException, Exception { this.clazz = clazz; columns = processClass(clazz); } public List<ColumnData> getColumns() { return columns; } public ColumnData getColumnDataById(int id){ return columnMap.get(id); } private List<ColumnData> processClass(Class cd) throws NoSuchMethodException, Exception { List<ColumnData> tColumns = new ArrayList<ColumnData>(10); Class tClazz = cd; Class currentClass = tClazz; while (currentClass != null) { java.lang.reflect.Field[] fields = currentClass.getDeclaredFields(); for (java.lang.reflect.Field f : fields) { AnnotatedTableField fieldAnnotation = f.getAnnotation(AnnotatedTableField.class); if (fieldAnnotation != null) { tColumns.add(processField(fieldAnnotation, f, currentClass)); } } currentClass = currentClass.getSuperclass(); } return tColumns; } private static String makeFirstLetterBig(String string) { if (string == null || string.length() == 0) { return ""; } String firstLetter = String.valueOf(string.charAt(0)).toUpperCase(); return firstLetter + string.substring(1); } private static COLUMNTYPE resolveColumnType(Class columnType) throws Exception { String typeName = columnType.getName(); if ("int".equals(typeName) || "java.lang.Integer".equals(typeName)) { return COLUMNTYPE.INTEGER; } else if ("float".equals(typeName) || "java.lang.Float".equals(typeName) || "double".equals(typeName) || "java.lang.Double".equals(typeName)) { return COLUMNTYPE.DOUBLE; } else if ("java.lang.String".equals(typeName)) { return COLUMNTYPE.STRING; } else if ("java.utils.Date".equals(typeName)) { return COLUMNTYPE.DATE; } else if ("java.sql.Timestamp".equals(typeName)) { return COLUMNTYPE.TIMESTAMP; } else if ("boolean".equals(typeName) || "java.lang.Boolean".equals(typeName)) { return COLUMNTYPE.BOOLEAN; } throw new Exception("Do not know field type [" + typeName + "]"); } private ColumnData processField(AnnotatedTableField fieldAnnotation, Field field, Class clazz) throws NoSuchMethodException, Exception { ColumnData column = new ColumnData(); String fieldName = field.getName(); Class fieldType = field.getType(); String getterMethodName = "get" + makeFirstLetterBig(fieldName); Method getter = clazz.getMethod(getterMethodName); String setterMethodName = "set" + makeFirstLetterBig(fieldName); Method setter = clazz.getMethod(setterMethodName, fieldType); String getterStringValueName = "get" + makeFirstLetterBig(fieldName)+"StringValue"; Method getterStringValue =null; try{ getterStringValue = clazz.getMethod(getterStringValueName); }catch(NoSuchMethodException nsme){ } column.setVisualFormatter(getterStringValue); column.setColumnName(fieldAnnotation.column()); column.setId(fieldAnnotation.id()); AnnotatedTableFieldType typeAnnotation = field.getAnnotation(AnnotatedTableFieldType.class); if (typeAnnotation!=null && typeAnnotation.getType() != COLUMNTYPE.NULL) { column.setColumnType(typeAnnotation.getType()); } else { column.setColumnType(resolveColumnType(fieldType)); } columnMap.put(fieldAnnotation.id(), column); column.setGetter(getter); column.setSetter(setter); return column; } }
Java
package annotationtablemodel.suppx.ems.annotatedtable; import javax.swing.JTable; /** * @author Dmitry Savchenko */ public class AnnotatedTable extends JTable{ public AnnotatedTable() { init(); } private void init() { } public static AnnotatedTable createAnnotatedTable(Class clazz) throws Exception{ AnnotatedTable table=new AnnotatedTable(); table.setModel(createAnnotatedTableModel(clazz)); return table; } public static AnnotatedTableModel createAnnotatedTableModel(Class clazz) throws NoSuchMethodException, Exception{ return new AnnotatedTableModel(clazz); } }
Java
package annotationtablemodel.suppx.ems.annotatedtable.annotations; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * * @author Dmitry */ @Retention(RetentionPolicy.RUNTIME) public @interface AnnotatedTableField { String column(); int id(); }
Java
package annotationtablemodel.suppx.ems.annotatedtable.annotations; import annotationtablemodel.suppx.ems.annotatedtable.COLUMNTYPE; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * @author Dmitry */ @Retention(RetentionPolicy.RUNTIME) public @interface AnnotatedTableFieldType { COLUMNTYPE getType() default COLUMNTYPE.NULL; }
Java
package annotationtablemodel.suppx.ems.annotatedtable; import java.lang.reflect.Method; /** * @author Dmitry Savchenko */ public class ColumnData { private String columnName; private int id; private Method setter; private Method getter; private Method visualFormatter; private COLUMNTYPE columnType; public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public Method getGetter() { return getter; } public void setGetter(Method getter) { this.getter = getter; } public Method getSetter() { return setter; } public void setSetter(Method setter) { this.setter = setter; } public COLUMNTYPE getColumnType() { return columnType; } public void setColumnType(COLUMNTYPE type) { this.columnType = type; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Method getVisualFormatter() { return visualFormatter; } public void setVisualFormatter(Method visualFormatter) { this.visualFormatter = visualFormatter; } }
Java
package annotationtablemodel; import annotationtablemodel.suppx.ems.annotatedtable.AnnotatedTableModel; import java.awt.BorderLayout; import java.util.ArrayList; import java.util.List; import javax.swing.JDialog; import javax.swing.JTable; /** * @author Dmitry Savchenko */ public class MainDialog extends JDialog { public MainDialog() { init(); } private void init() { AnnotatedTableModel model = null; try { model = new AnnotatedTableModel(User.class); } catch (Exception ex) { ex.printStackTrace(); } model.setData(getUsers()); model.fireTableDataChanged(); JTable table = new JTable(model); add(table.getTableHeader(), BorderLayout.NORTH); add(table); pack(); setLocationRelativeTo(null); } private List<User> getUsers() { List<User> users = new ArrayList<User>(); User user = new User(); user.setName("Роберт"); user.setHeight(185); users.add(user); user = new User(); user.setName("Джон"); user.setHeight(180); users.add(user); return users; } }
Java
package com.soladhoc.annonces.client.place; public class NameTokens { public static final String main = "main"; public static final String oauth = "oauth"; public static final String annonce = "annonce"; public static final String listannonces = "listannonces"; public static String getMain() { return main; } public static String getOauth() { return oauth; } public static String getAnnonce() { return annonce; } public static String getListannonces() { return listannonces; } }
Java
package com.soladhoc.annonces.client.place; import com.google.inject.BindingAnnotation; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.METHOD; import java.lang.annotation.Retention; import static java.lang.annotation.RetentionPolicy.RUNTIME; @BindingAnnotation @Target({ FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public @interface DefaultPlace { }
Java
package com.soladhoc.annonces.client.place; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.i18n.client.NumberFormat; public interface Defaults { String DATE_TIME_PATTERN = "dd.MM.yyyy HH:mm:ss.SSS Z"; // TODO Replace with user setting DateTimeFormat DATE_FORMAT = DateTimeFormat.getFormat("dd.MM.yyyy"); DateTimeFormat TIME_FORMAT = DateTimeFormat.getFormat("HH:mm"); NumberFormat NUMBER_FORMAT = NumberFormat.getFormat("#0.00"); }
Java
package com.soladhoc.annonces.client.place; import com.gwtplatform.mvp.client.proxy.PlaceManagerImpl; import com.gwtplatform.mvp.client.proxy.PlaceRequest; import com.soladhoc.annonces.client.place.DefaultPlace; import com.google.inject.Inject; import com.google.gwt.event.shared.EventBus; import com.gwtplatform.mvp.client.proxy.TokenFormatter; public class ClientPlaceManager extends PlaceManagerImpl { private final PlaceRequest defaultPlaceRequest; @Inject public ClientPlaceManager(final EventBus eventBus, final TokenFormatter tokenFormatter, @DefaultPlace final String defaultPlaceNameToken) { super(eventBus, tokenFormatter); this.defaultPlaceRequest = new PlaceRequest(defaultPlaceNameToken); } @Override public void revealDefaultPlace() { revealPlace(defaultPlaceRequest, false); } }
Java
package com.soladhoc.annonces.client.gin; import com.google.inject.Provides; import com.google.inject.Singleton; import com.gwtplatform.mvp.client.gin.AbstractPresenterModule; import com.gwtplatform.mvp.client.gin.DefaultModule; import com.soladhoc.annonces.client.place.ClientPlaceManager; import com.soladhoc.annonces.client.place.DefaultPlace; import com.soladhoc.annonces.client.place.NameTokens; import com.soladhoc.annonces.client.ui.AnnoncePresenter; import com.soladhoc.annonces.client.ui.AnnonceView; import com.soladhoc.annonces.client.ui.MainPagePresenter; import com.soladhoc.annonces.client.ui.MainPageView; import com.soladhoc.annonces.client.ui.OAuthPresenter; import com.soladhoc.annonces.client.ui.OAuthView; import com.soladhoc.annonces.shared.service.AnnonceRequestFactory; import com.soladhoc.annonces.shared.service.AnnonceRequestFactory.AnnonceService; public class ClientModule extends AbstractPresenterModule { @Override protected void configure() { install(new DefaultModule(ClientPlaceManager.class)); bindPresenter(MainPagePresenter.class, MainPagePresenter.MyView.class, MainPageView.class, MainPagePresenter.MyProxy.class); bindConstant().annotatedWith(DefaultPlace.class).to(NameTokens.annonce); bindPresenter(OAuthPresenter.class, OAuthPresenter.MyView.class, OAuthView.class, OAuthPresenter.MyProxy.class); bindPresenter(AnnoncePresenter.class, AnnoncePresenter.MyView.class, AnnonceView.class, AnnoncePresenter.MyProxy.class); // bind(AuthFilter.class).in(Singleton.class); bind(AnnonceRequestFactory.class).in(Singleton.class); } @Provides AnnonceService providesAnnonceService(AnnonceRequestFactory requestFactory){ return requestFactory.annonceService(); } }
Java
package com.soladhoc.annonces.client.gin; import com.google.gwt.event.shared.EventBus; import com.google.gwt.inject.client.AsyncProvider; import com.google.gwt.inject.client.GinModules; import com.google.gwt.inject.client.Ginjector; import com.gwtplatform.dispatch.client.gin.DispatchAsyncModule; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.soladhoc.annonces.client.resources.Resources; import com.soladhoc.annonces.client.ui.AnnoncePresenter; import com.soladhoc.annonces.client.ui.AnnoncesListPresenter; import com.soladhoc.annonces.client.ui.MainPagePresenter; import com.soladhoc.annonces.client.ui.OAuthPresenter; @GinModules({ DispatchAsyncModule.class, ClientModule.class }) public interface ClientGinjector extends Ginjector { EventBus getEventBus(); PlaceManager getPlaceManager(); Resources getResources(); AsyncProvider<MainPagePresenter> getMainPagePresenter(); AsyncProvider<OAuthPresenter> getOAuthPresenter(); AsyncProvider<AnnoncePresenter> getAnnoncePresenter(); AsyncProvider<AnnoncesListPresenter> getAnnoncesListPresenter(); }
Java
package com.soladhoc.annonces.client.event; import com.gwtplatform.dispatch.annotation.GenEvent; import com.gwtplatform.dispatch.annotation.Order; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; @GenEvent public class AnnonceAction { public static enum Action { DETAIL, EDIT, DELETE, ADD } @Order(1) AnnonceProxy annonce; @Order(2) Action action; }
Java
package com.soladhoc.annonces.client.view; import java.util.ArrayList; import com.gwtplatform.mvp.client.HasUiHandlers; import com.gwtplatform.mvp.client.View; import com.soladhoc.annonces.client.ui.AnnoncesUiHandlers; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; public interface AnnonceListView extends View, HasUiHandlers<AnnoncesUiHandlers> { void updateAnnonces(ArrayList<AnnonceProxy> annonceList); }
Java
package com.soladhoc.annonces.client.view; import java.util.ArrayList; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Widget; import com.soladhoc.annonces.client.resources.Resources; import com.soladhoc.annonces.client.view.ui.AnnonceCellTable; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; public class AnnonceListViewDesktop extends AbstractAnnonceListView { public AnnonceListViewDesktop(Widget widget, Resources resources) { super(widget, resources); } interface AnnonceUi extends UiBinder<Widget, AnnonceListViewDesktop> { } private static AnnonceUi uiBinder = GWT.create(AnnonceUi.class); @Override public void updateAnnonces(ArrayList<AnnonceProxy> annonceList) { // TODO Auto-generated method stub } @Override Widget initUI() { return uiBinder.createAndBindUi(this); } @UiField(provided=true) AnnonceCellTable annonces; }
Java
package com.soladhoc.annonces.client.view; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Widget; import com.gwtplatform.mvp.client.ViewWithUiHandlers; import com.soladhoc.annonces.client.AnnoncesAdhoc; import com.soladhoc.annonces.client.resources.Resources; import com.soladhoc.annonces.client.ui.AnnoncesUiHandlers; public abstract class AbstractAnnonceListView extends ViewWithUiHandlers<AnnoncesUiHandlers> implements AnnonceListView { final Widget widget; final Resources resources; public AbstractAnnonceListView(Widget widget, Resources resources) { this.widget = initUI(); this.resources = AnnoncesAdhoc.ginjector.getResources(); } abstract Widget initUI(); @Override public Widget asWidget() { return widget; } }
Java
package com.soladhoc.annonces.client.view.ui; import com.google.gwt.safehtml.shared.SafeHtml; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; public abstract class AnnonceTextRenderer extends AnnonceRenderer { @Override public SafeHtml render(AnnonceProxy activity) { String value = getValue(activity); return toSafeHtml(value); } protected abstract String getValue(AnnonceProxy annonce); }
Java
package com.soladhoc.annonces.client.view.ui; import com.google.gwt.cell.client.AbstractSafeHtmlCell; import com.google.gwt.cell.client.Cell; import com.google.gwt.cell.client.ValueUpdater; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.text.shared.SafeHtmlRenderer; import com.soladhoc.annonces.server.domain.Annonce; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; public class AnnonceCell extends AbstractSafeHtmlCell<AnnonceProxy> { private final AnnonceCellTable annoncesTable; public AnnonceCell(AnnonceCellTable annoncesTable, SafeHtmlRenderer<AnnonceProxy> renderer) { super(renderer, "click"); this.annoncesTable = annoncesTable; } @Override public void onBrowserEvent(Cell.Context context, Element parent, AnnonceProxy value, NativeEvent event, ValueUpdater<AnnonceProxy> valueUpdater) { super.onBrowserEvent(context, parent, value, event, valueUpdater); if ("click".equals(event.getType())) { annoncesTable.onDetail(value); } } @Override protected void render(Cell.Context context, SafeHtml data, SafeHtmlBuilder sb) { if (data != null) { sb.append(data); } } }
Java
package com.soladhoc.annonces.client.view.ui; import com.google.gwt.cell.client.Cell; import com.google.gwt.text.shared.SafeHtmlRenderer; import com.google.gwt.user.cellview.client.Column; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; public class AnnonceColumn extends Column<AnnonceProxy, AnnonceProxy> { public AnnonceColumn(Cell<AnnonceProxy> cell) { super(cell); } public AnnonceColumn(AnnonceCellTable annoncesTable, SafeHtmlRenderer<AnnonceProxy> renderer) { super(new AnnonceCell(annoncesTable, renderer)); } @Override public AnnonceProxy getValue(AnnonceProxy object) { return object; } }
Java
package com.soladhoc.annonces.client.view.ui; import com.google.gwt.text.shared.AbstractSafeHtmlRenderer; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; public abstract class AnnonceRenderer extends AbstractSafeHtmlRenderer<AnnonceProxy> { }
Java
package com.soladhoc.annonces.client.view.ui; import static com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy.DISABLED; import java.util.List; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.cellview.client.CellTable; import com.soladhoc.annonces.client.event.AnnonceAction; import com.soladhoc.annonces.client.event.AnnonceActionEvent; import com.soladhoc.annonces.client.event.AnnonceActionEvent.AnnonceActionHandler; import com.soladhoc.annonces.client.ui.FormatUtils; import com.soladhoc.annonces.server.domain.Annonce; import com.soladhoc.annonces.shared.proxy.AnnonceKeyProvider; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; public class AnnonceCellTable extends CellTable<AnnonceProxy> implements AnnonceActionEvent.HasAnnonceActionHandlers { // -------------------------------------------------------- private members private final AnnonceCellTableResources resources; // ----------------------------------------------------------- constructors public AnnonceCellTable(final AnnonceCellTableResources resources) { super(Integer.MAX_VALUE, resources, new AnnonceKeyProvider()); this.resources = resources; setRowCount(0); setKeyboardSelectionPolicy(DISABLED); addColumns(); } // -------------------------------------------------------------- gui setup private void addColumns() { // Column #0: Name AnnonceColumn titleColumn = new AnnonceColumn(this, new AnnonceTextRenderer() { @Override protected String getValue(AnnonceProxy annonce) { return annonce.getTitle(); } }); addColumnStyleName(0, resources.cellTableStyle().titleColumn()); addColumn(titleColumn, "Title"); // Column #1: Description AnnonceColumn descriptionColumn = new AnnonceColumn(this, new AnnonceTextRenderer() { @Override protected String getValue(AnnonceProxy annonce) { return annonce.getTitle(); } }); addColumnStyleName(1, resources.cellTableStyle().descriptionColumn()); addColumn(descriptionColumn, "Description"); // Column #2: Due Date AnnonceColumn dueDateColumn = new AnnonceColumn(this, new AnnonceTextRenderer() { @Override public String getValue(AnnonceProxy annonce) { return FormatUtils.date(annonce.getCreationDate()); } }); addColumnStyleName(2, resources.cellTableStyle().creationDateColumn()); addColumn(dueDateColumn, "Due Date"); // Column #3: Finished AnnonceColumn publishedColumn = new AnnonceColumn(this, new AnnonceRenderer() { @Override public SafeHtml render(AnnonceProxy annonce) { String entity = annonce.getPublished() ? "&#9745;" : "&#9744;"; return new SafeHtmlBuilder().appendHtmlConstant(entity).toSafeHtml(); } }); addColumnStyleName(3, resources.cellTableStyle().publishedColumn()); addColumn(publishedColumn, "Published"); } public void update(List<AnnonceProxy> annonces) { if (annonces != null) { setRowData(0, annonces); setRowCount(annonces.size()); } } // --------------------------------------------------------- event handling @Override public HandlerRegistration addAnnonceActionHandler(AnnonceActionHandler handler) { return addHandler(handler, AnnonceActionEvent.getType()); } void onDetail(AnnonceProxy annonce) { AnnonceActionEvent.fire(this, annonce, AnnonceAction.Action.DETAIL); } }
Java
package com.soladhoc.annonces.client.view.ui; import com.google.gwt.user.cellview.client.CellTable; public interface AnnonceCellTableResources extends CellTable.Resources { public interface AnnonceCellTableStyle extends CellTable.Style { String titleColumn(); String textColumn(); String creationDateColumn(); String ownerColumn(); String descriptionColumn(); String publishedColumn(); } @Override @Source("annonceCellTable.css") AnnonceCellTableStyle cellTableStyle(); }
Java
package com.soladhoc.annonces.client; import com.google.gwt.core.client.EntryPoint; import com.soladhoc.annonces.client.gin.ClientGinjector; import com.google.gwt.core.client.GWT; import com.gwtplatform.mvp.client.DelayedBindRegistry; public class AnnoncesAdhoc implements EntryPoint { public static final ClientGinjector ginjector = GWT.create(ClientGinjector.class); @Override public void onModuleLoad() { // This is required for Gwt-Platform proxy's generator DelayedBindRegistry.bind(ginjector); ginjector.getPlaceManager().revealCurrentPlace(); } }
Java
package com.soladhoc.annonces.client.resources; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.resources.client.ImageResource.ImageOptions; import com.google.gwt.resources.client.ImageResource.RepeatStyle; //@formatter:off public interface Resources extends ClientBundle { // ----------------------------------------------------------------- images ImageResource arrow(); ImageResource logo(); @ImageOptions(repeatStyle = RepeatStyle.Horizontal) ImageResource header(); // -------------------------------------------------------------------- CSS @Source("desktop.css") DesktopResource desktop(); public interface DesktopResource extends CssResource { @ClassName("selected") String selected(); } @Source("tablet.css") TabletResource tablet(); public interface TabletResource extends CssResource { } @Source("mobile.css") MobileResource mobile(); public interface MobileResource extends CssResource { @ClassName("hidden") String hidden(); @ClassName("visible") String visible(); } }
Java
package com.soladhoc.annonces.client.ui; import java.util.Date; import com.soladhoc.annonces.client.place.Defaults; public final class FormatUtils { private FormatUtils() { } public static String date(Date date) { if (date != null) { return Defaults.DATE_FORMAT.format(date); } return ""; } }
Java
package com.soladhoc.annonces.client.ui; import com.gwtplatform.mvp.client.ViewImpl; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Button; public class OAuthView extends ViewImpl implements OAuthPresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, OAuthView> { } @Inject public OAuthView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } @UiField Button googleAuthButton; @Override public HasClickHandlers getAuthButton() { return this.googleAuthButton; } }
Java
package com.soladhoc.annonces.client.ui; import com.google.api.gwt.oauth2.client.Auth; import com.google.api.gwt.oauth2.client.AuthRequest; import com.google.api.gwt.oauth2.client.Callback; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.HasClickHandlers; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.client.Window; import com.google.inject.Inject; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.client.proxy.RevealRootContentEvent; import com.soladhoc.annonces.client.place.NameTokens; public class OAuthPresenter extends Presenter<OAuthPresenter.MyView, OAuthPresenter.MyProxy> { // Use the implementation of Auth intended to be used in the GWT client app. private static final Auth AUTH = Auth.get(); private static String authToken = null; public interface MyView extends View { HasClickHandlers getAuthButton(); } @ProxyCodeSplit @NameToken(NameTokens.oauth) public interface MyProxy extends ProxyPlace<OAuthPresenter> { } @Inject public OAuthPresenter(final EventBus eventBus, final MyView view, final MyProxy proxy) { super(eventBus, view, proxy); } @Override protected void revealInParent() { RevealRootContentEvent.fire(this, this); } @Override protected void onBind() { super.onBind(); this.registerHandler(getView().getAuthButton().addClickHandler( new ClickHandler() { /** * Calling login() will display a popup to the user the * first time it is called. Once the user has granted access * to the application, subsequent calls to login() will not * display the popup, and will immediately result in the * callback being given the token to use. */ @Override public void onClick(ClickEvent event) { AuthRequest req = new AuthRequest(GOOGLE_AUTH_URL, GOOGLE_CLIENT_ID) .withScopes(BUZZ_READONLY_SCOPE); AUTH.login(req, new Callback<String, Throwable>() { @Override public void onSuccess(String token) { Window.alert("Got an OAuth token:\n" + token); OAuthPresenter.this.authToken = token; } @Override public void onFailure(Throwable caught) { Window.alert("Error:\n" + caught.getMessage()); } }); } })); } private static final String GOOGLE_AUTH_URL = "https://accounts.google.com/o/oauth2/auth"; // This app's personal client ID assigned by the Google APIs Console // (http://code.google.com/apis/console). private static final String GOOGLE_CLIENT_ID = "957665152265-39reeckut5d28rkh2dh2lie443d9u58v.apps.googleusercontent.com"; // The auth scope being requested. This scope will allow the application to // read Buzz activities, comments, etc., as if it was the user. private static final String BUZZ_READONLY_SCOPE = "https://www.googleapis.com/auth/buzz.readonly"; }
Java
package com.soladhoc.annonces.client.ui; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.client.ui.Button; import com.google.inject.Inject; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.PlaceRequest; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.client.proxy.RevealContentEvent; import com.soladhoc.annonces.client.place.NameTokens; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; import com.soladhoc.annonces.shared.service.AnnonceRequestFactory; import com.soladhoc.annonces.shared.service.AnnonceRequestFactory.AnnonceService; public class AnnoncePresenter extends Presenter<AnnoncePresenter.MyView, AnnoncePresenter.MyProxy> { final AnnonceRequestFactory requestFactory; public interface MyView extends View { void setTitle(String title); String getTitle(); void setText(String text); String getText(); Button getSaveButton(); void setError(String text); } @ProxyCodeSplit @NameToken(NameTokens.annonce) public interface MyProxy extends ProxyPlace<AnnoncePresenter> { } @Inject public AnnoncePresenter(final EventBus eventBus, final MyView view, final MyProxy proxy, final AnnonceRequestFactory requestFactory) { super(eventBus, view, proxy); this.requestFactory = requestFactory; } @Override protected void revealInParent() { RevealContentEvent.fire(this, MainPagePresenter.CENTRAL_SLOT_TYPE, this); } @Override protected void onBind() { super.onBind(); this.registerHandler(getView().getSaveButton().addClickHandler( new ClickHandler() { @Override public void onClick(ClickEvent event) { AnnoncePresenter.this.saveAnnonce(); } } )); } private void saveAnnonce(){ getView().setError(""); String title = getView().getTitle(); String text = getView().getText(); // save annonce AnnonceService reqCtx = this.requestFactory.annonceService(); AnnonceProxy annonceProxy = reqCtx.create(AnnonceProxy.class); annonceProxy.setTitle(title); annonceProxy.setText(text); reqCtx.save(annonceProxy); } @Override public void prepareFromRequest(PlaceRequest request) { getView().setTitle(request.getParameter("title", "title")); super.prepareFromRequest(request); } }
Java
package com.soladhoc.annonces.client.ui; import com.gwtplatform.mvp.client.UiHandlers; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; public interface AnnoncesUiHandlers extends UiHandlers { void onDetail(AnnonceProxy annonce); }
Java
package com.soladhoc.annonces.client.ui; import com.google.gwt.event.shared.EventBus; import com.google.gwt.event.shared.GwtEvent.Type; import com.google.inject.Inject; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.View; import com.gwtplatform.mvp.client.annotations.ContentSlot; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.annotations.ProxyEvent; import com.gwtplatform.mvp.client.proxy.LockInteractionEvent; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.client.proxy.RevealContentHandler; import com.gwtplatform.mvp.client.proxy.RevealRootContentEvent; import com.soladhoc.annonces.client.place.NameTokens; public class MainPagePresenter extends Presenter<MainPagePresenter.MyView, MainPagePresenter.MyProxy> { public interface MyView extends View { void showLoading(boolean visible); } @ContentSlot public static final Type<RevealContentHandler<?>> CENTRAL_SLOT_TYPE = new Type<RevealContentHandler<?>>(); @ProxyCodeSplit @NameToken(NameTokens.main) public interface MyProxy extends ProxyPlace<MainPagePresenter> { } @Inject public MainPagePresenter(final EventBus eventBus, final MyView view, final MyProxy proxy) { super(eventBus, view, proxy); } @Override protected void revealInParent() { RevealRootContentEvent.fire(this, this); } @Override protected void onBind() { super.onBind(); } /** * We display a short lock message whenever navigation is in progress. * * @param event The {@link LockInteractionEvent}. */ @ProxyEvent public void onLockInteraction(LockInteractionEvent event) { getView().showLoading(event.shouldLock()); } }
Java
package com.soladhoc.annonces.client.ui; import java.util.ArrayList; import com.google.gwt.event.shared.EventBus; import com.google.inject.Inject; import com.google.web.bindery.requestfactory.shared.Receiver; import com.google.web.bindery.requestfactory.shared.Request; import com.gwtplatform.mvp.client.Presenter; import com.gwtplatform.mvp.client.annotations.NameToken; import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.gwtplatform.mvp.client.proxy.PlaceRequest; import com.gwtplatform.mvp.client.proxy.ProxyPlace; import com.gwtplatform.mvp.client.proxy.RevealContentEvent; import com.soladhoc.annonces.client.place.NameTokens; import com.soladhoc.annonces.client.view.AnnonceListView; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; import com.soladhoc.annonces.shared.service.AnnonceRequestFactory.AnnonceService; public class AnnoncesListPresenter extends Presenter<AnnonceListView, AnnoncesListPresenter.MyProxy> implements AnnoncesUiHandlers { private int RANGE = 10; private final PlaceManager placeManager; private final AnnonceService service; @ProxyCodeSplit @NameToken(NameTokens.listannonces) public interface MyProxy extends ProxyPlace<AnnoncesListPresenter> { } @Inject public AnnoncesListPresenter(final EventBus eventBus, final AnnonceListView view, final MyProxy proxy, final PlaceManager placeManager, final AnnonceService annonceService) { super(eventBus, view, proxy); this.placeManager = placeManager; this.service = annonceService; getView().setUiHandlers(this); } @Override protected void revealInParent() { RevealContentEvent .fire(this, MainPagePresenter.CENTRAL_SLOT_TYPE, this); } @Override protected void onBind() { super.onBind(); } @Override public void onDetail(AnnonceProxy annonce) { if (annonce != null) { PlaceRequest request = new PlaceRequest(NameTokens.annonce).with( "title", annonce.getTitle()); placeManager.revealPlace(request); } } @Override protected void onReset() { final ArrayList<AnnonceProxy> annonceList = new ArrayList<AnnonceProxy>(); Request<AnnonceProxy> request = service.fetchRange( 0, RANGE); request.fire(new Receiver<AnnonceProxy>() { @Override public void onSuccess(AnnonceProxy response) { annonceList.add(response); } }); getView().updateAnnonces(annonceList); } }
Java
package com.soladhoc.annonces.client.ui; import com.google.gwt.cell.client.AbstractCell; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.cellview.client.CellList; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.gwtplatform.mvp.client.ViewImpl; import com.google.gwt.user.client.ui.VerticalPanel; public class MainPageView extends ViewImpl implements MainPagePresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, MainPageView> { } @Inject public MainPageView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } @UiField(provided=true) CellList<Object> cellList = new CellList<Object>(new AbstractCell<Object>(){ @Override public void render(Context context, Object value, SafeHtmlBuilder sb) { // TODO } }); @UiField Label loadingMessage; @UiField VerticalPanel layoutPanel; @Override public void showLoading(boolean visible) { loadingMessage.setVisible(visible); } }
Java
package com.soladhoc.annonces.client.ui; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.RichTextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.gwtplatform.mvp.client.ViewImpl; public class AnnonceView extends ViewImpl implements AnnoncePresenter.MyView { private final Widget widget; public interface Binder extends UiBinder<Widget, AnnonceView> { } @Inject public AnnonceView(final Binder binder) { widget = binder.createAndBindUi(this); } @Override public Widget asWidget() { return widget; } @UiField TextBox title; @UiField RichTextArea text; @UiField Button saveButton; @Override public void setTitle(String title) { this.title.setText(title); } @Override public void setText(String text) { this.text.setText(text); } @Override public String getTitle() { return title.getTitle(); } @Override public String getText() { return title.getText(); } @Override public Button getSaveButton() { return this.saveButton; } @Override public void setError(String text) { // TODO Auto-generated method stub } }
Java
package com.soladhoc.annonces.shared.service; import com.google.web.bindery.requestfactory.shared.Request; import com.google.web.bindery.requestfactory.shared.RequestContext; import com.google.web.bindery.requestfactory.shared.RequestFactory; import com.google.web.bindery.requestfactory.shared.Service; import com.soladhoc.annonces.server.locator.DaoServiceLocator; import com.soladhoc.annonces.server.service.AnnonceDao; import com.soladhoc.annonces.shared.proxy.AnnonceProxy; public interface AnnonceRequestFactory extends RequestFactory { @Service(value = AnnonceDao.class, locator = DaoServiceLocator.class) public interface AnnonceService extends RequestContext { Request<AnnonceProxy> save(AnnonceProxy editable); Request<AnnonceProxy> fetch(Long id); Request<AnnonceProxy> fetchRange(int first, int range); } AnnonceService annonceService(); }
Java