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; 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.service.SyncService; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.DetachableResultReceiver; import com.google.android.apps.iosched.util.EulaHelper; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; /** * Front-door {@link Activity} that displays high-level features the schedule application offers to * users. Depending on whether the device is a phone or an Android 3.0+ tablet, different layouts * will be used. For example, on a phone, the primary content is a {@link DashboardFragment}, * whereas on a tablet, both a {@link DashboardFragment} and a {@link TagStreamFragment} are * displayed. */ public class HomeActivity extends BaseActivity { private static final String TAG = "HomeActivity"; private TagStreamFragment mTagStreamFragment; private SyncStatusUpdaterFragment mSyncStatusUpdaterFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!EulaHelper.hasAcceptedEula(this)) { EulaHelper.showEula(false, this); } AnalyticsUtils.getInstance(this).trackPageView("/Home"); setContentView(R.layout.activity_home); getActivityHelper().setupActionBar(null, 0); FragmentManager fm = getSupportFragmentManager(); mTagStreamFragment = (TagStreamFragment) fm.findFragmentById(R.id.fragment_tag_stream); mSyncStatusUpdaterFragment = (SyncStatusUpdaterFragment) fm .findFragmentByTag(SyncStatusUpdaterFragment.TAG); if (mSyncStatusUpdaterFragment == null) { mSyncStatusUpdaterFragment = new SyncStatusUpdaterFragment(); fm.beginTransaction().add(mSyncStatusUpdaterFragment, SyncStatusUpdaterFragment.TAG).commit(); triggerRefresh(); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupHomeActivity(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.refresh_menu_items, menu); super.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { triggerRefresh(); return true; } return super.onOptionsItemSelected(item); } private void triggerRefresh() { final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, SyncService.class); intent.putExtra(SyncService.EXTRA_STATUS_RECEIVER, mSyncStatusUpdaterFragment.mReceiver); startService(intent); if (mTagStreamFragment != null) { mTagStreamFragment.refresh(); } } private void updateRefreshStatus(boolean refreshing) { getActivityHelper().setRefreshActionButtonCompatState(refreshing); } /** * A non-UI fragment, retained across configuration changes, that updates its activity's UI * when sync status changes. */ public static class SyncStatusUpdaterFragment extends Fragment implements DetachableResultReceiver.Receiver { public static final String TAG = SyncStatusUpdaterFragment.class.getName(); private boolean mSyncing = false; private DetachableResultReceiver mReceiver; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mReceiver = new DetachableResultReceiver(new Handler()); mReceiver.setReceiver(this); } /** {@inheritDoc} */ public void onReceiveResult(int resultCode, Bundle resultData) { HomeActivity activity = (HomeActivity) getActivity(); if (activity == null) { return; } switch (resultCode) { case SyncService.STATUS_RUNNING: { mSyncing = true; break; } case SyncService.STATUS_FINISHED: { mSyncing = false; break; } case SyncService.STATUS_ERROR: { // Error happened down in SyncService, show as toast. mSyncing = false; final String errorText = getString(R.string.toast_sync_error, resultData .getString(Intent.EXTRA_TEXT)); Toast.makeText(activity, errorText, Toast.LENGTH_LONG).show(); break; } } activity.updateRefreshStatus(mSyncing); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ((HomeActivity) getActivity()).updateRefreshStatus(mSyncing); } } }
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. */ 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. */ /** * 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.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 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.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 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; 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.ui; import android.os.Bundle; import android.support.v4.app.Fragment; public class BulletinActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new BulletinFragment(); } @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.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.ParserUtils; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; 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.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; /** * Shows a {@link WebView} with a map of the conference venue. */ public class MapFragment extends Fragment { private static final String TAG = "MapFragment"; /** * When specified, will automatically point the map to the requested room. */ public static final String EXTRA_ROOM = "com.google.android.iosched.extra.ROOM"; private static final String MAP_JSI_NAME = "MAP_CONTAINER"; private static final String MAP_URL = "http://www.google.com/events/io/2011/embed.html"; private static boolean CLEAR_CACHE_ON_LOAD = false; private WebView mWebView; private View mLoadingSpinner; private boolean mMapInitialized = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Map"); } @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.setWebChromeClient(mWebChromeClient); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable() { public void run() { // Initialize web view if (CLEAR_CACHE_ON_LOAD) { mWebView.clearCache(true); } mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); mWebView.loadUrl(MAP_URL); mWebView.addJavascriptInterface(mMapJsiImpl, MAP_JSI_NAME); } }); 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 void runJs(String js) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Loading javascript:" + js); } mWebView.loadUrl("javascript:" + js); } /** * Helper method to escape JavaScript strings. Useful when passing strings to a WebView via * "javascript:" calls. */ private static String escapeJsString(String s) { if (s == null) { return ""; } return s.replace("'", "\\'").replace("\"", "\\\""); } public void panLeft(float screenFraction) { runJs("IoMap.panLeft('" + screenFraction + "');"); } /** * I/O Conference Map JavaScript interface. */ private interface MapJsi { void openContentInfo(String test); void onMapReady(); } private WebChromeClient mWebChromeClient = new WebChromeClient() { public void onConsoleMessage(String message, int lineNumber, String sourceID) { Log.i(TAG, "JS Console message: (" + sourceID + ": " + lineNumber + ") " + message); } }; 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 void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Log.e(TAG, "Error " + errorCode + ": " + description); Toast.makeText(view.getContext(), "Error " + errorCode + ": " + description, Toast.LENGTH_LONG).show(); super.onReceivedError(view, errorCode, description, failingUrl); } }; private MapJsi mMapJsiImpl = new MapJsi() { public void openContentInfo(String roomId) { final String possibleTrackId = ParserUtils.translateTrackIdAlias(roomId); final Intent intent; if (ParserUtils.LOCAL_TRACK_IDS.contains(possibleTrackId)) { // This is a track; open up the sandbox for the track, since room IDs that are // track IDs are sandbox areas in the map. Uri trackVendorsUri = ScheduleContract.Tracks.buildVendorsUri(possibleTrackId); intent = new Intent(Intent.ACTION_VIEW, trackVendorsUri); } else { Uri roomUri = Rooms.buildSessionsDirUri(roomId); intent = new Intent(Intent.ACTION_VIEW, roomUri); } getActivity().runOnUiThread(new Runnable() { public void run() { ((BaseActivity) getActivity()).openActivityOrFragment(intent); } }); } public void onMapReady() { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "onMapReady"); } final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); String showRoomId = null; if (!mMapInitialized && intent.hasExtra(EXTRA_ROOM)) { showRoomId = intent.getStringExtra(EXTRA_ROOM); } if (showRoomId != null) { runJs("IoMap.showLocationById('" + escapeJsString(showRoomId) + "');"); } mMapInitialized = 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.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables; import com.google.android.apps.iosched.provider.ScheduleDatabase.VendorsSearchColumns; import com.google.android.apps.iosched.service.SyncService; import com.google.android.apps.iosched.util.SelectionBuilder; import android.app.Activity; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.BaseColumns; import android.util.Log; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Provider that stores {@link ScheduleContract} data. Data is usually inserted * by {@link SyncService}, and queried by various {@link Activity} instances. */ public class ScheduleProvider extends ContentProvider { private static final String TAG = "ScheduleProvider"; private static final boolean LOGV = Log.isLoggable(TAG, Log.VERBOSE); private ScheduleDatabase mOpenHelper; private static final UriMatcher sUriMatcher = buildUriMatcher(); private static final int BLOCKS = 100; private static final int BLOCKS_BETWEEN = 101; private static final int BLOCKS_ID = 102; private static final int BLOCKS_ID_SESSIONS = 103; private static final int TRACKS = 200; private static final int TRACKS_ID = 201; private static final int TRACKS_ID_SESSIONS = 202; private static final int TRACKS_ID_VENDORS = 203; private static final int ROOMS = 300; private static final int ROOMS_ID = 301; private static final int ROOMS_ID_SESSIONS = 302; private static final int SESSIONS = 400; private static final int SESSIONS_STARRED = 401; private static final int SESSIONS_SEARCH = 402; private static final int SESSIONS_AT = 403; private static final int SESSIONS_ID = 404; private static final int SESSIONS_ID_SPEAKERS = 405; private static final int SESSIONS_ID_TRACKS = 406; private static final int SPEAKERS = 500; private static final int SPEAKERS_ID = 501; private static final int SPEAKERS_ID_SESSIONS = 502; private static final int VENDORS = 600; private static final int VENDORS_STARRED = 601; private static final int VENDORS_SEARCH = 603; private static final int VENDORS_ID = 604; private static final int SEARCH_SUGGEST = 800; private static final String MIME_XML = "text/xml"; /** * Build and return a {@link UriMatcher} that catches all {@link Uri} * variations supported by this {@link ContentProvider}. */ private static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = ScheduleContract.CONTENT_AUTHORITY; matcher.addURI(authority, "blocks", BLOCKS); matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN); matcher.addURI(authority, "blocks/*", BLOCKS_ID); matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS); matcher.addURI(authority, "tracks", TRACKS); matcher.addURI(authority, "tracks/*", TRACKS_ID); matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS); matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS); matcher.addURI(authority, "rooms", ROOMS); matcher.addURI(authority, "rooms/*", ROOMS_ID); matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS); matcher.addURI(authority, "sessions", SESSIONS); matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED); matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH); matcher.addURI(authority, "sessions/at/*", SESSIONS_AT); matcher.addURI(authority, "sessions/*", SESSIONS_ID); matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS); matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS); matcher.addURI(authority, "speakers", SPEAKERS); matcher.addURI(authority, "speakers/*", SPEAKERS_ID); matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS); matcher.addURI(authority, "vendors", VENDORS); matcher.addURI(authority, "vendors/starred", VENDORS_STARRED); matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH); matcher.addURI(authority, "vendors/*", VENDORS_ID); matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST); return matcher; } @Override public boolean onCreate() { final Context context = getContext(); mOpenHelper = new ScheduleDatabase(context); return true; } /** {@inheritDoc} */ @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: return Blocks.CONTENT_TYPE; case BLOCKS_BETWEEN: return Blocks.CONTENT_TYPE; case BLOCKS_ID: return Blocks.CONTENT_ITEM_TYPE; case BLOCKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS: return Tracks.CONTENT_TYPE; case TRACKS_ID: return Tracks.CONTENT_ITEM_TYPE; case TRACKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS_ID_VENDORS: return Vendors.CONTENT_TYPE; case ROOMS: return Rooms.CONTENT_TYPE; case ROOMS_ID: return Rooms.CONTENT_ITEM_TYPE; case ROOMS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case SESSIONS_SEARCH: return Sessions.CONTENT_TYPE; case SESSIONS_AT: return Sessions.CONTENT_TYPE; case SESSIONS_ID: return Sessions.CONTENT_ITEM_TYPE; case SESSIONS_ID_SPEAKERS: return Speakers.CONTENT_TYPE; case SESSIONS_ID_TRACKS: return Tracks.CONTENT_TYPE; case SPEAKERS: return Speakers.CONTENT_TYPE; case SPEAKERS_ID: return Speakers.CONTENT_ITEM_TYPE; case SPEAKERS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case VENDORS: return Vendors.CONTENT_TYPE; case VENDORS_STARRED: return Vendors.CONTENT_TYPE; case VENDORS_SEARCH: return Vendors.CONTENT_TYPE; case VENDORS_ID: return Vendors.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** {@inheritDoc} */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (LOGV) Log.v(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { default: { // Most cases are handled with simple SelectionBuilder final SelectionBuilder builder = buildExpandedSelection(uri, match); return builder.where(selection, selectionArgs).query(db, projection, sortOrder); } case SEARCH_SUGGEST: { final SelectionBuilder builder = new SelectionBuilder(); // Adjust incoming query to become SQL text match selectionArgs[0] = selectionArgs[0] + "%"; builder.table(Tables.SEARCH_SUGGEST); builder.where(selection, selectionArgs); builder.map(SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_TEXT_1); projection = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_QUERY }; final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT); return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit); } } } /** {@inheritDoc} */ @Override public Uri insert(Uri uri, ContentValues values) { if (LOGV) Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { db.insertOrThrow(Tables.BLOCKS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID)); } case TRACKS: { db.insertOrThrow(Tables.TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID)); } case ROOMS: { db.insertOrThrow(Tables.ROOMS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID)); } case SESSIONS: { db.insertOrThrow(Tables.SESSIONS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID)); } case SESSIONS_ID_SPEAKERS: { db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID)); } case SESSIONS_ID_TRACKS: { db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID)); } case SPEAKERS: { db.insertOrThrow(Tables.SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID)); } case VENDORS: { db.insertOrThrow(Tables.VENDORS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID)); } case SEARCH_SUGGEST: { db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values); getContext().getContentResolver().notifyChange(uri, null); return SearchSuggest.CONTENT_URI; } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** {@inheritDoc} */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).update(db, values); getContext().getContentResolver().notifyChange(uri, null); return retVal; } /** {@inheritDoc} */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "delete(uri=" + uri + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).delete(db); getContext().getContentResolver().notifyChange(uri, null); return retVal; } /** * Apply the given set of {@link ContentProviderOperation}, executing inside * a {@link SQLiteDatabase} transaction. All changes will be rolled back if * any single one fails. */ @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.beginTransaction(); try { final int numOperations = operations.size(); final ContentProviderResult[] results = new ContentProviderResult[numOperations]; for (int i = 0; i < numOperations; i++) { results[i] = operations.get(i).apply(this, results, i); } db.setTransactionSuccessful(); return results; } finally { db.endTransaction(); } } /** * Build a simple {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually enough to support {@link #insert}, * {@link #update}, and {@link #delete} operations. */ private SelectionBuilder buildSimpleSelection(Uri uri) { final SelectionBuilder builder = new SelectionBuilder(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .where(Blocks.BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case SEARCH_SUGGEST: { return builder.table(Tables.SEARCH_SUGGEST); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** * Build an advanced {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually only used by {@link #query}, since it * performs table joins useful for {@link Cursor} data. */ private SelectionBuilder buildExpandedSelection(Uri uri, int match) { final SelectionBuilder builder = new SelectionBuilder(); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_BETWEEN: { final List<String> segments = uri.getPathSegments(); final String startTime = segments.get(2); final String endTime = segments.get(3); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_START + ">=?", startTime) .where(Blocks.BLOCK_START + "<=?", endTime); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS) .map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT) .map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case TRACKS_ID_SESSIONS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId); } case TRACKS_ID_VENDORS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Qualified.VENDORS_TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case ROOMS_ID_SESSIONS: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS); } case SESSIONS_STARRED: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.SESSION_STARRED + "=1"); } case SESSIONS_SEARCH: { final String query = Sessions.getSearchQuery(uri); return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS) .map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(SessionsSearchColumns.BODY + " MATCH ?", query); } case SESSIONS_AT: { final List<String> segments = uri.getPathSegments(); final String time = segments.get(2); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.BLOCK_START + "<=?", time) .where(Sessions.BLOCK_END + ">=?", time); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS) .mapToTable(Speakers._ID, Tables.SPEAKERS) .mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS) .where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS) .mapToTable(Tracks._ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case SPEAKERS_ID_SESSIONS: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS); } case VENDORS_STARRED: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_STARRED + "=1"); } case VENDORS_SEARCH: { final String query = Vendors.getSearchQuery(uri); return builder.table(Tables.VENDORS_SEARCH_JOIN_VENDORS_TRACKS) .map(Vendors.SEARCH_SNIPPET, Subquery.VENDORS_SNIPPET) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.VENDOR_ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(VendorsSearchColumns.BODY + " MATCH ?", query); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { final int match = sUriMatcher.match(uri); switch (match) { default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } private interface Subquery { String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String BLOCK_CONTAINS_STARRED = "(SELECT MAX(" + Qualified.SESSIONS_STARRED + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID + ") FROM " + Tables.SESSIONS_TRACKS + " WHERE " + Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM " + Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')"; String VENDORS_SNIPPET = "snippet(" + Tables.VENDORS_SEARCH + ",'{','}','\u2026')"; } /** * {@link ScheduleContract} fields that are fully qualified with a specific * parent {@link Tables}. Used when needed to work around SQL ambiguity. */ private interface Qualified { String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID; String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID; String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.TRACK_ID; String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SESSION_ID; String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SPEAKER_ID; String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID; String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID; @SuppressWarnings("hiding") String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED; String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID; String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID; } }
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.provider; import com.google.android.apps.iosched.util.ParserUtils; import android.app.SearchManager; import android.graphics.Color; import android.net.Uri; import android.provider.BaseColumns; import android.text.format.DateUtils; import java.util.List; /** * Contract class for interacting with {@link ScheduleProvider}. Unless * otherwise noted, all time-based fields are milliseconds since epoch and can * be compared against {@link System#currentTimeMillis()}. * <p> * The backing {@link android.content.ContentProvider} assumes that {@link Uri} are generated * using stronger {@link String} identifiers, instead of {@code int} * {@link BaseColumns#_ID} values, which are prone to shuffle during sync. */ public class ScheduleContract { /** * Special value for {@link SyncColumns#UPDATED} indicating that an entry * has never been updated, or doesn't exist yet. */ public static final long UPDATED_NEVER = -2; /** * Special value for {@link SyncColumns#UPDATED} indicating that the last * update time is unknown, usually when inserted from a local file source. */ public static final long UPDATED_UNKNOWN = -1; public interface SyncColumns { /** Last time this entry was updated or synchronized. */ String UPDATED = "updated"; } interface BlocksColumns { /** Unique string identifying this block of time. */ String BLOCK_ID = "block_id"; /** Title describing this block of time. */ String BLOCK_TITLE = "block_title"; /** Time when this block starts. */ String BLOCK_START = "block_start"; /** Time when this block ends. */ String BLOCK_END = "block_end"; /** Type describing this block. */ String BLOCK_TYPE = "block_type"; } interface TracksColumns { /** Unique string identifying this track. */ String TRACK_ID = "track_id"; /** Name describing this track. */ String TRACK_NAME = "track_name"; /** Color used to identify this track, in {@link Color#argb} format. */ String TRACK_COLOR = "track_color"; /** Body of text explaining this track in detail. */ String TRACK_ABSTRACT = "track_abstract"; } interface RoomsColumns { /** Unique string identifying this room. */ String ROOM_ID = "room_id"; /** Name describing this room. */ String ROOM_NAME = "room_name"; /** Building floor this room exists on. */ String ROOM_FLOOR = "room_floor"; } interface SessionsColumns { /** Unique string identifying this session. */ String SESSION_ID = "session_id"; /** Difficulty level of the session. */ String SESSION_LEVEL = "session_level"; /** Title describing this track. */ String SESSION_TITLE = "session_title"; /** Body of text explaining this session in detail. */ String SESSION_ABSTRACT = "session_abstract"; /** Requirements that attendees should meet. */ String SESSION_REQUIREMENTS = "session_requirements"; /** Kewords/tags for this session. */ String SESSION_KEYWORDS = "session_keywords"; /** Hashtag for this session. */ String SESSION_HASHTAG = "session_hashtag"; /** Slug (short name) for this session. */ String SESSION_SLUG = "session_slug"; /** Full URL to session online. */ String SESSION_URL = "session_url"; /** Link to Moderator for this session. */ String SESSION_MODERATOR_URL = "session_moderator_url"; /** Full URL to YouTube. */ String SESSION_YOUTUBE_URL = "session_youtube_url"; /** Full URL to PDF. */ String SESSION_PDF_URL = "session_pdf_url"; /** Full URL to speakermeter/external feedback URL. */ String SESSION_FEEDBACK_URL = "session_feedback_url"; /** Full URL to official session notes. */ String SESSION_NOTES_URL = "session_notes_url"; /** User-specific flag indicating starred status. */ String SESSION_STARRED = "session_starred"; } interface SpeakersColumns { /** Unique string identifying this speaker. */ String SPEAKER_ID = "speaker_id"; /** Name of this speaker. */ String SPEAKER_NAME = "speaker_name"; /** Profile photo of this speaker. */ String SPEAKER_IMAGE_URL = "speaker_image_url"; /** Company this speaker works for. */ String SPEAKER_COMPANY = "speaker_company"; /** Body of text describing this speaker in detail. */ String SPEAKER_ABSTRACT = "speaker_abstract"; /** Full URL to the speaker's profile. */ String SPEAKER_URL = "speaker_url"; } interface VendorsColumns { /** Unique string identifying this vendor. */ String VENDOR_ID = "vendor_id"; /** Name of this vendor. */ String VENDOR_NAME = "vendor_name"; /** Location or city this vendor is based in. */ String VENDOR_LOCATION = "vendor_location"; /** Body of text describing this vendor. */ String VENDOR_DESC = "vendor_desc"; /** Link to vendor online. */ String VENDOR_URL = "vendor_url"; /** Body of text describing the product of this vendor. */ String VENDOR_PRODUCT_DESC = "vendor_product_desc"; /** Link to vendor logo. */ String VENDOR_LOGO_URL = "vendor_logo_url"; /** User-specific flag indicating starred status. */ String VENDOR_STARRED = "vendor_starred"; } public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched"; private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); private static final String PATH_BLOCKS = "blocks"; private static final String PATH_AT = "at"; private static final String PATH_BETWEEN = "between"; private static final String PATH_TRACKS = "tracks"; private static final String PATH_ROOMS = "rooms"; private static final String PATH_SESSIONS = "sessions"; private static final String PATH_STARRED = "starred"; private static final String PATH_SPEAKERS = "speakers"; private static final String PATH_VENDORS = "vendors"; private static final String PATH_EXPORT = "export"; private static final String PATH_SEARCH = "search"; private static final String PATH_SEARCH_SUGGEST = "search_suggest_query"; /** * Blocks are generic timeslots that {@link Sessions} and other related * events fall into. */ public static class Blocks implements BlocksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.block"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.block"; /** Count of {@link Sessions} inside given block. */ public static final String SESSIONS_COUNT = "sessions_count"; /** * Flag indicating that at least one {@link Sessions#SESSION_ID} inside * this block has {@link Sessions#SESSION_STARRED} set. */ public static final String CONTAINS_STARRED = "contains_starred"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, " + BlocksColumns.BLOCK_END + " ASC"; /** Build {@link Uri} for requested {@link #BLOCK_ID}. */ public static Uri buildBlockUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #BLOCK_ID}. */ public static Uri buildSessionsUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references any {@link Blocks} that occur * between the requested time boundaries. */ public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) { return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath( String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build(); } /** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */ public static String getBlockId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #BLOCK_ID} that will always match the requested * {@link Blocks} details. */ public static String generateBlockId(long startTime, long endTime) { startTime /= DateUtils.SECOND_IN_MILLIS; endTime /= DateUtils.SECOND_IN_MILLIS; return ParserUtils.sanitizeId(startTime + "-" + endTime); } } /** * Tracks are overall categories for {@link Sessions} and {@link Vendors}, * such as "Android" or "Enterprise." */ public static class Tracks implements TracksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.track"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.track"; /** Count of {@link Sessions} inside given track. */ public static final String SESSIONS_COUNT = "sessions_count"; /** Count of {@link Vendors} inside given track. */ public static final String VENDORS_COUNT = "vendors_count"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + " ASC"; /** "All tracks" ID. */ public static final String ALL_TRACK_ID = "all"; /** Build {@link Uri} for requested {@link #TRACK_ID}. */ public static Uri buildTrackUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #TRACK_ID}. */ public static Uri buildSessionsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references any {@link Vendors} associated with * the requested {@link #TRACK_ID}. */ public static Uri buildVendorsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build(); } /** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */ public static String getTrackId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #TRACK_ID} that will always match the requested * {@link Tracks} details. */ public static String generateTrackId(String title) { return ParserUtils.sanitizeId(title); } } /** * Rooms are physical locations at the conference venue. */ public static class Rooms implements RoomsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.room"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.room"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, " + RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #ROOM_ID}. */ public static Uri buildRoomUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #ROOM_ID}. */ public static Uri buildSessionsDirUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */ public static String getRoomId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #ROOM_ID} that will always match the requested * {@link Rooms} details. */ public static String generateRoomId(String room) { return ParserUtils.sanitizeId(room); } } /** * Each session is a block of time that has a {@link Tracks}, a * {@link Rooms}, and zero or more {@link Speakers}. */ public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build(); public static final Uri CONTENT_STARRED_URI = CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.session"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.session"; public static final String BLOCK_ID = "block_id"; public static final String ROOM_ID = "room_id"; public static final String SEARCH_SNIPPET = "search_snippet"; // TODO: shortcut primary track to offer sub-sorting here /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC," + SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #SESSION_ID}. */ public static Uri buildSessionUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).build(); } /** * Build {@link Uri} that references any {@link Speakers} associated * with the requested {@link #SESSION_ID}. */ public static Uri buildSpeakersDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build(); } /** * Build {@link Uri} that references any {@link Tracks} associated with * the requested {@link #SESSION_ID}. */ public static Uri buildTracksDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build(); } public static Uri buildSessionsAtDirUri(long time) { return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time)) .build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */ public static String getSessionId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } /** * Generate a {@link #SESSION_ID} that will always match the requested * {@link Sessions} details. */ public static String generateSessionId(String title) { return ParserUtils.sanitizeId(title); } } /** * Speakers are individual people that lead {@link Sessions}. */ public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.speaker"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.speaker"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #SPEAKER_ID}. */ public static Uri buildSpeakerUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #SPEAKER_ID}. */ public static Uri buildSessionsDirUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */ public static String getSpeakerId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #SPEAKER_ID} that will always match the requested * {@link Speakers} details. */ public static String generateSpeakerId(String speakerLdap) { return ParserUtils.sanitizeId(speakerLdap); } } /** * Each vendor is a company appearing at the conference that may be * associated with a specific {@link Tracks}. */ public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build(); public static final Uri CONTENT_STARRED_URI = CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.vendor"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.vendor"; /** {@link Tracks#TRACK_ID} that this vendor belongs to. */ public static final String TRACK_ID = "track_id"; public static final String SEARCH_SNIPPET = "search_snippet"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = VendorsColumns.VENDOR_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #VENDOR_ID}. */ public static Uri buildVendorUri(String vendorId) { return CONTENT_URI.buildUpon().appendPath(vendorId).build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */ public static String getVendorId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } /** * Generate a {@link #VENDOR_ID} that will always match the requested * {@link Vendors} details. */ public static String generateVendorId(String companyLogo) { return ParserUtils.sanitizeId(companyLogo); } } public static class SearchSuggest { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build(); public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1 + " COLLATE NOCASE ASC"; } private ScheduleContract() { } }
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.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleContract.VendorsColumns; import android.app.SearchManager; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log; /** * Helper for managing {@link SQLiteDatabase} that stores data for * {@link ScheduleProvider}. */ public class ScheduleDatabase extends SQLiteOpenHelper { private static final String TAG = "ScheduleDatabase"; private static final String DATABASE_NAME = "schedule.db"; // NOTE: carefully update onUpgrade() when bumping database versions to make // sure user data is saved. private static final int VER_LAUNCH = 21; private static final int VER_SESSION_FEEDBACK_URL = 22; private static final int VER_SESSION_NOTES_URL_SLUG = 23; private static final int DATABASE_VERSION = VER_SESSION_NOTES_URL_SLUG; interface Tables { String BLOCKS = "blocks"; String TRACKS = "tracks"; String ROOMS = "rooms"; String SESSIONS = "sessions"; String SPEAKERS = "speakers"; String SESSIONS_SPEAKERS = "sessions_speakers"; String SESSIONS_TRACKS = "sessions_tracks"; String VENDORS = "vendors"; String SESSIONS_SEARCH = "sessions_search"; String VENDORS_SEARCH = "vendors_search"; String SEARCH_SUGGEST = "search_suggest"; String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String VENDORS_JOIN_TRACKS = "vendors " + "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id"; String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers " + "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id"; String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers " + "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks " + "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id"; String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks " + "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search " + "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String VENDORS_SEARCH_JOIN_VENDORS_TRACKS = "vendors_search " + "LEFT OUTER JOIN vendors ON vendors_search.vendor_id=vendors.vendor_id " + "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id"; } private interface Triggers { String SESSIONS_SEARCH_INSERT = "sessions_search_insert"; String SESSIONS_SEARCH_DELETE = "sessions_search_delete"; String SESSIONS_SEARCH_UPDATE = "sessions_search_update"; String VENDORS_SEARCH_INSERT = "vendors_search_insert"; String VENDORS_SEARCH_DELETE = "vendors_search_delete"; } public interface SessionsSpeakers { String SESSION_ID = "session_id"; String SPEAKER_ID = "speaker_id"; } public interface SessionsTracks { String SESSION_ID = "session_id"; String TRACK_ID = "track_id"; } interface SessionsSearchColumns { String SESSION_ID = "session_id"; String BODY = "body"; } interface VendorsSearchColumns { String VENDOR_ID = "vendor_id"; String BODY = "body"; } /** Fully-qualified field names. */ private interface Qualified { String SESSIONS_SEARCH_SESSION_ID = Tables.SESSIONS_SEARCH + "." + SessionsSearchColumns.SESSION_ID; String VENDORS_SEARCH_VENDOR_ID = Tables.VENDORS_SEARCH + "." + VendorsSearchColumns.VENDOR_ID; String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID + "," + SessionsSearchColumns.BODY + ")"; String VENDORS_SEARCH = Tables.VENDORS_SEARCH + "(" + VendorsSearchColumns.VENDOR_ID + "," + VendorsSearchColumns.BODY + ")"; } /** {@code REFERENCES} clauses. */ private interface References { String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")"; String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")"; String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")"; String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")"; String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")"; String VENDOR_ID = "REFERENCES " + Tables.VENDORS + "(" + Vendors.VENDOR_ID + ")"; } private interface Subquery { /** * Subquery used to build the {@link SessionsSearchColumns#BODY} string * used for indexing {@link Sessions} content. */ String SESSIONS_BODY = "(new." + Sessions.SESSION_TITLE + "||'; '||new." + Sessions.SESSION_ABSTRACT + "||'; '||" + "coalesce(new." + Sessions.SESSION_KEYWORDS + ", '')" + ")"; /** * Subquery used to build the {@link VendorsSearchColumns#BODY} string * used for indexing {@link Vendors} content. */ String VENDORS_BODY = "(new." + Vendors.VENDOR_NAME + "||'; '||new." + Vendors.VENDOR_DESC + "||'; '||new." + Vendors.VENDOR_PRODUCT_DESC + ")"; } public ScheduleDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Tables.BLOCKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + BlocksColumns.BLOCK_ID + " TEXT NOT NULL," + BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL," + BlocksColumns.BLOCK_START + " INTEGER NOT NULL," + BlocksColumns.BLOCK_END + " INTEGER NOT NULL," + BlocksColumns.BLOCK_TYPE + " TEXT," + "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TracksColumns.TRACK_ID + " TEXT NOT NULL," + TracksColumns.TRACK_NAME + " TEXT," + TracksColumns.TRACK_COLOR + " INTEGER," + TracksColumns.TRACK_ABSTRACT + " TEXT," + "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.ROOMS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + RoomsColumns.ROOM_ID + " TEXT NOT NULL," + RoomsColumns.ROOM_NAME + " TEXT," + RoomsColumns.ROOM_FLOOR + " TEXT," + "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SessionsColumns.SESSION_ID + " TEXT NOT NULL," + Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + "," + Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + "," + SessionsColumns.SESSION_LEVEL + " TEXT," + SessionsColumns.SESSION_TITLE + " TEXT," + SessionsColumns.SESSION_ABSTRACT + " TEXT," + SessionsColumns.SESSION_REQUIREMENTS + " TEXT," + SessionsColumns.SESSION_KEYWORDS + " TEXT," + SessionsColumns.SESSION_HASHTAG + " TEXT," + SessionsColumns.SESSION_SLUG + " TEXT," + SessionsColumns.SESSION_URL + " TEXT," + SessionsColumns.SESSION_MODERATOR_URL + " TEXT," + SessionsColumns.SESSION_YOUTUBE_URL + " TEXT," + SessionsColumns.SESSION_PDF_URL + " TEXT," + SessionsColumns.SESSION_FEEDBACK_URL + " TEXT," + SessionsColumns.SESSION_NOTES_URL + " TEXT," + SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0," + "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL," + SpeakersColumns.SPEAKER_NAME + " TEXT," + SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT," + SpeakersColumns.SPEAKER_COMPANY + " TEXT," + SpeakersColumns.SPEAKER_ABSTRACT + " TEXT," + SpeakersColumns.SPEAKER_URL+ " TEXT," + "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + "," + "UNIQUE (" + SessionsSpeakers.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID + "," + "UNIQUE (" + SessionsTracks.SESSION_ID + "," + SessionsTracks.TRACK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.VENDORS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + VendorsColumns.VENDOR_ID + " TEXT NOT NULL," + Vendors.TRACK_ID + " TEXT " + References.TRACK_ID + "," + VendorsColumns.VENDOR_NAME + " TEXT," + VendorsColumns.VENDOR_LOCATION + " TEXT," + VendorsColumns.VENDOR_DESC + " TEXT," + VendorsColumns.VENDOR_URL + " TEXT," + VendorsColumns.VENDOR_PRODUCT_DESC + " TEXT," + VendorsColumns.VENDOR_LOGO_URL + " TEXT," + VendorsColumns.VENDOR_STARRED + " INTEGER," + "UNIQUE (" + VendorsColumns.VENDOR_ID + ") ON CONFLICT REPLACE)"); createSessionsSearch(db); createVendorsSearch(db); db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)"); } /** * Create triggers that automatically build {@link Tables#SESSIONS_SEARCH} * as values are changed in {@link Tables#SESSIONS}. */ private static void createSessionsSearch(SQLiteDatabase db) { // Using the "porter" tokenizer for simple stemming, so that // "frustration" matches "frustrated." db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSearchColumns.BODY + " TEXT NOT NULL," + SessionsSearchColumns.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE," + "tokenize=porter)"); // TODO: handle null fields in body, which cause trigger to fail // TODO: implement update trigger, not currently exercised db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_INSERT + " AFTER INSERT ON " + Tables.SESSIONS + " BEGIN INSERT INTO " + Qualified.SESSIONS_SEARCH + " " + " VALUES(new." + Sessions.SESSION_ID + ", " + Subquery.SESSIONS_BODY + ");" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SEARCH + " " + " WHERE " + Qualified.SESSIONS_SEARCH_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_UPDATE + " AFTER UPDATE ON " + Tables.SESSIONS + " BEGIN UPDATE sessions_search SET " + SessionsSearchColumns.BODY + " = " + Subquery.SESSIONS_BODY + " WHERE session_id = old.session_id" + "; END;"); } /** * Create triggers that automatically build {@link Tables#VENDORS_SEARCH} as * values are changed in {@link Tables#VENDORS}. */ private static void createVendorsSearch(SQLiteDatabase db) { // Using the "porter" tokenizer for simple stemming, so that // "frustration" matches "frustrated." db.execSQL("CREATE VIRTUAL TABLE " + Tables.VENDORS_SEARCH + " USING fts3(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + VendorsSearchColumns.BODY + " TEXT NOT NULL," + VendorsSearchColumns.VENDOR_ID + " TEXT NOT NULL " + References.VENDOR_ID + "," + "UNIQUE (" + VendorsSearchColumns.VENDOR_ID + ") ON CONFLICT REPLACE," + "tokenize=porter)"); // TODO: handle null fields in body, which cause trigger to fail // TODO: implement update trigger, not currently exercised db.execSQL("CREATE TRIGGER " + Triggers.VENDORS_SEARCH_INSERT + " AFTER INSERT ON " + Tables.VENDORS + " BEGIN INSERT INTO " + Qualified.VENDORS_SEARCH + " " + " VALUES(new." + Vendors.VENDOR_ID + ", " + Subquery.VENDORS_BODY + ");" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.VENDORS_SEARCH_DELETE + " AFTER DELETE ON " + Tables.VENDORS + " BEGIN DELETE FROM " + Tables.VENDORS_SEARCH + " " + " WHERE " + Qualified.VENDORS_SEARCH_VENDOR_ID + "=old." + Vendors.VENDOR_ID + ";" + " END;"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion); // NOTE: This switch statement is designed to handle cascading database // updates, starting at the current version and falling through to all // future upgrade cases. Only use "break;" when you want to drop and // recreate the entire database. int version = oldVersion; switch (version) { case VER_LAUNCH: // Version 22 added column for session feedback URL. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_FEEDBACK_URL + " TEXT"); version = VER_SESSION_FEEDBACK_URL; case VER_SESSION_FEEDBACK_URL: // Version 23 added columns for session official notes URL and slug. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_NOTES_URL + " TEXT"); db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_SLUG + " TEXT"); version = VER_SESSION_NOTES_URL_SLUG; } Log.d(TAG, "after upgrade logic, at version " + version); if (version != DATABASE_VERSION) { Log.w(TAG, "Destroying old data during upgrade"); db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_INSERT); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_DELETE); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.VENDORS_SEARCH_INSERT); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.VENDORS_SEARCH_DELETE); db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS_SEARCH); db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST); onCreate(db); } } }
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 android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import java.util.ArrayList; /** * A <em>really</em> dumb implementation of the {@link Menu} interface, that's only useful for our * old-actionbar purposes. See <code>com.android.internal.view.menu.MenuBuilder</code> in AOSP for * a more complete implementation. */ public class SimpleMenu implements Menu { private Context mContext; private Resources mResources; private ArrayList<SimpleMenuItem> mItems; public SimpleMenu(Context context) { mContext = context; mResources = context.getResources(); mItems = new ArrayList<SimpleMenuItem>(); } public Context getContext() { return mContext; } public Resources getResources() { return mResources; } public MenuItem add(CharSequence title) { return addInternal(0, 0, title); } public MenuItem add(int titleRes) { return addInternal(0, 0, mResources.getString(titleRes)); } public MenuItem add(int groupId, int itemId, int order, CharSequence title) { return addInternal(itemId, order, title); } public MenuItem add(int groupId, int itemId, int order, int titleRes) { return addInternal(itemId, order, mResources.getString(titleRes)); } /** * Adds an item to the menu. The other add methods funnel to this. */ private MenuItem addInternal(int itemId, int order, CharSequence title) { final SimpleMenuItem item = new SimpleMenuItem(this, itemId, order, title); mItems.add(findInsertIndex(mItems, order), item); return item; } private static int findInsertIndex(ArrayList<? extends MenuItem> items, int order) { for (int i = items.size() - 1; i >= 0; i--) { MenuItem item = items.get(i); if (item.getOrder() <= order) { return i + 1; } } return 0; } public int findItemIndex(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return i; } } return -1; } public void removeItem(int itemId) { removeItemAtInt(findItemIndex(itemId)); } private void removeItemAtInt(int index) { if ((index < 0) || (index >= mItems.size())) { return; } mItems.remove(index); } public void clear() { mItems.clear(); } public MenuItem findItem(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return item; } } return null; } public int size() { return mItems.size(); } public MenuItem getItem(int index) { return mItems.get(index); } // Unsupported operations. public SubMenu addSubMenu(CharSequence charSequence) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public int addIntentOptions(int i, int i1, int i2, ComponentName componentName, Intent[] intents, Intent intent, int i3, MenuItem[] menuItems) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void removeGroup(int i) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupCheckable(int i, boolean b, boolean b1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupVisible(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupEnabled(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean hasVisibleItems() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void close() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performShortcut(int i, KeyEvent keyEvent, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean isShortcutKey(int i, KeyEvent keyEvent) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performIdentifierAction(int i, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setQwertyMode(boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * 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 java.util.ArrayList; import java.util.Collections; /** * Provides static methods for creating {@code List} instances easily, and other * utility methods for working with lists. */ public class Lists { /** * Creates an empty {@code ArrayList} instance. * * <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use * {@link Collections#emptyList} instead. * * @return a newly-created, initially-empty {@code ArrayList} */ public static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); } /** * Creates a resizable {@code ArrayList} instance containing the given * elements. * * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the * following: * * <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);} * * <p>where {@code sub1} and {@code sub2} are references to subtypes of * {@code Base}, not of {@code Base} itself. To get around this, you must * use: * * <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);} * * @param elements the elements that the list should contain, in order * @return a newly-created {@code ArrayList} containing those elements */ public static <E> ArrayList<E> newArrayList(E... elements) { int capacity = (elements.length * 110) / 100 + 5; ArrayList<E> list = new ArrayList<E>(capacity); Collections.addAll(list, elements); return list; } }
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 com.google.android.apps.iosched.service.SyncService; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Helper class for fetching and disk-caching images from the web. */ public class BitmapUtils { private static final String TAG = "BitmapUtils"; // TODO: for concurrent connections, DefaultHttpClient isn't great, consider other options // that still allow for sharing resources across bitmap fetches. public static interface OnFetchCompleteListener { public void onFetchComplete(Object cookie, Bitmap result); } /** * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}. */ public static void fetchImage(final Context context, final String url, final OnFetchCompleteListener callback) { fetchImage(context, url, null, null, callback); } /** * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}. * * @param cookie An arbitrary object that will be passed to the callback. */ public static void fetchImage(final Context context, final String url, final BitmapFactory.Options decodeOptions, final Object cookie, final OnFetchCompleteListener callback) { new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { final String url = params[0]; if (TextUtils.isEmpty(url)) { return null; } // First compute the cache key and cache file path for this URL File cacheFile = null; try { MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); mDigest.update(url.getBytes()); final String cacheKey = bytesToHexString(mDigest.digest()); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { cacheFile = new File( Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + context.getPackageName() + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp"); } } catch (NoSuchAlgorithmException e) { // Oh well, SHA-1 not available (weird), don't cache bitmaps. } if (cacheFile != null && cacheFile.exists()) { Bitmap cachedBitmap = BitmapFactory.decodeFile( cacheFile.toString(), decodeOptions); if (cachedBitmap != null) { return cachedBitmap; } } try { // TODO: check for HTTP caching headers final HttpClient httpClient = SyncService.getHttpClient( context.getApplicationContext()); final HttpResponse resp = httpClient.execute(new HttpGet(url)); final HttpEntity entity = resp.getEntity(); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK || entity == null) { return null; } final byte[] respBytes = EntityUtils.toByteArray(entity); // Write response bytes to cache. if (cacheFile != null) { try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } } // Decode the bytes and return the bitmap. return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions); } catch (Exception e) { Log.w(TAG, "Problem while loading image: " + e.toString(), e); } return null; } @Override protected void onPostExecute(Bitmap result) { callback.onFetchComplete(cookie, result); } }.execute(url); } private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } }
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 com.google.android.apps.analytics.GoogleAnalyticsTracker; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; /** * Helper singleton class for the Google Analytics tracking library. */ public class AnalyticsUtils { private static final String TAG = "AnalyticsUtils"; GoogleAnalyticsTracker mTracker; private Context mApplicationContext; /** * The analytics tracking code for the app. */ // TODO: insert your Analytics UA code here. private static final String UACODE = "INSERT_YOUR_ANALYTICS_UA_CODE_HERE"; private static final int VISITOR_SCOPE = 1; private static final String FIRST_RUN_KEY = "firstRun"; private static final boolean ANALYTICS_ENABLED = true; private static AnalyticsUtils sInstance; /** * Returns the global {@link AnalyticsUtils} singleton object, creating one if necessary. */ public static AnalyticsUtils getInstance(Context context) { if (!ANALYTICS_ENABLED) { return sEmptyAnalyticsUtils; } if (sInstance == null) { if (context == null) { return sEmptyAnalyticsUtils; } sInstance = new AnalyticsUtils(context); } return sInstance; } private AnalyticsUtils(Context context) { if (context == null) { // This should only occur for the empty Analytics utils object. return; } mApplicationContext = context.getApplicationContext(); mTracker = GoogleAnalyticsTracker.getInstance(); // Unfortunately this needs to be synchronous. mTracker.start(UACODE, 300, mApplicationContext); Log.d(TAG, "Initializing Analytics"); // Since visitor CV's should only be declared the first time an app runs, check if // it's run before. Add as necessary. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( mApplicationContext); final boolean firstRun = prefs.getBoolean(FIRST_RUN_KEY, true); if (firstRun) { Log.d(TAG, "Analytics firstRun"); String apiLevel = Integer.toString(Build.VERSION.SDK_INT); String model = Build.MODEL; mTracker.setCustomVar(1, "apiLevel", apiLevel, VISITOR_SCOPE); mTracker.setCustomVar(2, "model", model, VISITOR_SCOPE); // Close out so we never run this block again, unless app is removed & = // reinstalled. prefs.edit().putBoolean(FIRST_RUN_KEY, false).commit(); } } public void trackEvent(final String category, final String action, final String label, final int value) { // We wrap the call in an AsyncTask since the Google Analytics library writes to disk // on its calling thread. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { mTracker.trackEvent(category, action, label, value); Log.d(TAG, "iosched Analytics trackEvent: " + category + " / " + action + " / " + label + " / " + value); } catch (Exception e) { // We don't want to crash if there's an Analytics library exception. Log.w(TAG, "iosched Analytics trackEvent error: " + category + " / " + action + " / " + label + " / " + value, e); } return null; } }.execute(); } public void trackPageView(final String path) { // We wrap the call in an AsyncTask since the Google Analytics library writes to disk // on its calling thread. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { mTracker.trackPageView(path); Log.d(TAG, "iosched Analytics trackPageView: " + path); } catch (Exception e) { // We don't want to crash if there's an Analytics library exception. Log.w(TAG, "iosched Analytics trackPageView error: " + path, e); } return null; } }.execute(); } /** * Empty instance for use when Analytics is disabled or there was no Context available. */ private static AnalyticsUtils sEmptyAnalyticsUtils = new AnalyticsUtils(null) { @Override public void trackEvent(String category, String action, String label, int value) {} @Override public void trackPageView(String path) {} }; }
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.text.format.DateUtils; import java.io.IOException; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.HREF; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.LINK; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.REL; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.TITLE; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.UPDATED; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class WorksheetEntry { private static final String REL_LISTFEED = "http://schemas.google.com/spreadsheets/2006#listfeed"; private long mUpdated; private String mTitle; private String mListFeed; public long getUpdated() { return mUpdated; } public String getTitle() { return mTitle; } public String getListFeed() { return mListFeed; } @Override public String toString() { return "title=" + mTitle + ", updated=" + mUpdated + " (" + DateUtils.getRelativeTimeSpanString(mUpdated) + ")"; } public static WorksheetEntry fromParser(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final WorksheetEntry entry = new WorksheetEntry(); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); if (LINK.equals(tag)) { final String rel = parser.getAttributeValue(null, REL); final String href = parser.getAttributeValue(null, HREF); if (REL_LISTFEED.equals(rel)) { entry.mListFeed = href; } } } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (TITLE.equals(tag)) { entry.mTitle = text; } else if (UPDATED.equals(tag)) { entry.mUpdated = ParserUtils.parseTime(text); } } } return entry; } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * 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. */ /* * Modifications: * -Imported from AOSP frameworks/base/core/java/com/android/internal/content * -Changed package name */ package com.google.android.apps.iosched.util; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Log; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; /** * Helper for building selection clauses for {@link SQLiteDatabase}. Each * appended clause is combined using {@code AND}. This class is <em>not</em> * thread safe. */ public class SelectionBuilder { private static final String TAG = "SelectionBuilder"; private static final boolean LOGV = false; private String mTable = null; private Map<String, String> mProjectionMap = Maps.newHashMap(); private StringBuilder mSelection = new StringBuilder(); private ArrayList<String> mSelectionArgs = Lists.newArrayList(); /** * Reset any internal state, allowing this builder to be recycled. */ public SelectionBuilder reset() { mTable = null; mSelection.setLength(0); mSelectionArgs.clear(); return this; } /** * Append the given selection clause to the internal state. Each clause is * surrounded with parenthesis and combined using {@code AND}. */ public SelectionBuilder where(String selection, String... selectionArgs) { if (TextUtils.isEmpty(selection)) { if (selectionArgs != null && selectionArgs.length > 0) { throw new IllegalArgumentException( "Valid selection required when including arguments="); } // Shortcut when clause is empty return this; } if (mSelection.length() > 0) { mSelection.append(" AND "); } mSelection.append("(").append(selection).append(")"); if (selectionArgs != null) { for (String arg : selectionArgs) { mSelectionArgs.add(arg); } } return this; } public SelectionBuilder table(String table) { mTable = table; return this; } private void assertTable() { if (mTable == null) { throw new IllegalStateException("Table not specified"); } } public SelectionBuilder mapToTable(String column, String table) { mProjectionMap.put(column, table + "." + column); return this; } public SelectionBuilder map(String fromColumn, String toClause) { mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn); return this; } /** * Return selection string for current internal state. * * @see #getSelectionArgs() */ public String getSelection() { return mSelection.toString(); } /** * Return selection arguments for current internal state. * * @see #getSelection() */ public String[] getSelectionArgs() { return mSelectionArgs.toArray(new String[mSelectionArgs.size()]); } private void mapColumns(String[] columns) { for (int i = 0; i < columns.length; i++) { final String target = mProjectionMap.get(columns[i]); if (target != null) { columns[i] = target; } } } @Override public String toString() { return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection() + ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]"; } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) { return query(db, columns, null, null, orderBy, null); } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String groupBy, String having, String orderBy, String limit) { assertTable(); if (columns != null) mapColumns(columns); if (LOGV) Log.v(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this); return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having, orderBy, limit); } /** * Execute update using the current internal state as {@code WHERE} clause. */ public int update(SQLiteDatabase db, ContentValues values) { assertTable(); if (LOGV) Log.v(TAG, "update() " + this); return db.update(mTable, values, getSelection(), getSelectionArgs()); } /** * Execute delete using the current internal state as {@code WHERE} clause. */ public int delete(SQLiteDatabase db) { assertTable(); if (LOGV) Log.v(TAG, "delete() " + this); return db.delete(mTable, getSelection(), getSelectionArgs()); } }
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 android.view.MotionEvent; /** * A utility class that emulates multitouch APIs available in Android 2.0+. */ public class MotionEventUtils { public static final int ACTION_MASK = 0xff; public static final int ACTION_POINTER_UP = 0x6; public static final int ACTION_POINTER_INDEX_MASK = 0x0000ff00; public static final int ACTION_POINTER_INDEX_SHIFT = 8; public static boolean sMultiTouchApiAvailable; static { try { MotionEvent.class.getMethod("getPointerId", new Class[]{int.class}); sMultiTouchApiAvailable = true; } catch (NoSuchMethodException nsme) { sMultiTouchApiAvailable = false; } } public static float getX(MotionEvent ev, int pointerIndex) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.getX(ev, pointerIndex); } else { return ev.getX(); } } public static float getY(MotionEvent ev, int pointerIndex) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.getY(ev, pointerIndex); } else { return ev.getY(); } } public static int getPointerId(MotionEvent ev, int pointerIndex) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.getPointerId(ev, pointerIndex); } else { return 0; } } public static int findPointerIndex(MotionEvent ev, int pointerId) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.findPointerIndex(ev, pointerId); } else { return (pointerId == 0) ? 0 : -1; } } /** * A wrapper around newer (SDK level 5) MotionEvent APIs. This class only gets loaded * if it is determined that these new APIs exist on the device. */ private static class WrappedStaticMotionEvent { public static float getX(MotionEvent ev, int pointerIndex) { return ev.getX(pointerIndex); } public static float getY(MotionEvent ev, int pointerIndex) { return ev.getY(pointerIndex); } public static int getPointerId(MotionEvent ev, int pointerIndex) { return ev.getPointerId(pointerIndex); } public static int findPointerIndex(MotionEvent ev, int pointerId) { return ev.findPointerIndex(pointerId); } } }
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 android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ContextMenu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; /** * A <em>really</em> dumb implementation of the {@link MenuItem} interface, that's only useful for * our old-actionbar purposes. See <code>com.android.internal.view.menu.MenuItemImpl</code> in * AOSP for a more complete implementation. */ public class SimpleMenuItem implements MenuItem { private SimpleMenu mMenu; private final int mId; private final int mOrder; private CharSequence mTitle; private CharSequence mTitleCondensed; private Drawable mIconDrawable; private int mIconResId = 0; private boolean mEnabled = true; public SimpleMenuItem(SimpleMenu menu, int id, int order, CharSequence title) { mMenu = menu; mId = id; mOrder = order; mTitle = title; } public int getItemId() { return mId; } public int getOrder() { return mOrder; } public MenuItem setTitle(CharSequence title) { mTitle = title; return this; } public MenuItem setTitle(int titleRes) { return setTitle(mMenu.getContext().getString(titleRes)); } public CharSequence getTitle() { return mTitle; } public MenuItem setTitleCondensed(CharSequence title) { mTitleCondensed = title; return this; } public CharSequence getTitleCondensed() { return mTitleCondensed != null ? mTitleCondensed : mTitle; } public MenuItem setIcon(Drawable icon) { mIconResId = 0; mIconDrawable = icon; return this; } public MenuItem setIcon(int iconResId) { mIconDrawable = null; mIconResId = iconResId; return this; } public Drawable getIcon() { if (mIconDrawable != null) { return mIconDrawable; } if (mIconResId != 0) { return mMenu.getResources().getDrawable(mIconResId); } return null; } public MenuItem setEnabled(boolean enabled) { mEnabled = enabled; return this; } public boolean isEnabled() { return mEnabled; } // No-op operations. We use no-ops to allow inflation from menu XML. public int getGroupId() { return 0; } public View getActionView() { return null; } public MenuItem setIntent(Intent intent) { // Noop return this; } public Intent getIntent() { return null; } public MenuItem setShortcut(char c, char c1) { // Noop return this; } public MenuItem setNumericShortcut(char c) { // Noop return this; } public char getNumericShortcut() { return 0; } public MenuItem setAlphabeticShortcut(char c) { // Noop return this; } public char getAlphabeticShortcut() { return 0; } public MenuItem setCheckable(boolean b) { // Noop return this; } public boolean isCheckable() { return false; } public MenuItem setChecked(boolean b) { // Noop return this; } public boolean isChecked() { return false; } public MenuItem setVisible(boolean b) { // Noop return this; } public boolean isVisible() { return true; } public boolean hasSubMenu() { return false; } public SubMenu getSubMenu() { return null; } public MenuItem setOnMenuItemClickListener( OnMenuItemClickListener onMenuItemClickListener) { // Noop return this; } public ContextMenu.ContextMenuInfo getMenuInfo() { return null; } public void setShowAsAction(int i) { // Noop } public MenuItem setActionView(View view) { // Noop return this; } public MenuItem setActionView(int i) { // Noop return this; } }
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 com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.HomeActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; /** * A class that handles some common activity-related functionality in the app, such as setting up * the action bar. This class provides functioanlity useful for both phones and tablets, and does * not require any Android 3.0-specific features. */ public class ActivityHelper { protected Activity mActivity; /** * Factory method for creating {@link ActivityHelper} objects for a given activity. Depending * on which device the app is running, either a basic helper or Honeycomb-specific helper will * be returned. */ public static ActivityHelper createInstance(Activity activity) { return UIUtils.isHoneycomb() ? new ActivityHelperHoneycomb(activity) : new ActivityHelper(activity); } protected ActivityHelper(Activity activity) { mActivity = activity; } public void onPostCreate(Bundle savedInstanceState) { // Create the action bar SimpleMenu menu = new SimpleMenu(mActivity); mActivity.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu); // TODO: call onPreparePanelMenu here as well for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); addActionButtonCompatFromMenuItem(item); } } public boolean onCreateOptionsMenu(Menu menu) { mActivity.getMenuInflater().inflate(R.menu.default_menu_items, menu); return false; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: goSearch(); return true; } return false; } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { return true; } return false; } public boolean onKeyLongPress(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { goHome(); return true; } return false; } /** * Method, to be called in <code>onPostCreate</code>, that sets up this activity as the * home activity for the app. */ public void setupHomeActivity() { } /** * Method, to be called in <code>onPostCreate</code>, that sets up this activity as a * sub-activity in the app. */ public void setupSubActivity() { } /** * Invoke "home" action, returning to {@link com.google.android.apps.iosched.ui.HomeActivity}. */ public void goHome() { if (mActivity instanceof HomeActivity) { return; } final Intent intent = new Intent(mActivity, HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); mActivity.startActivity(intent); if (!UIUtils.isHoneycomb()) { mActivity.overridePendingTransition(R.anim.home_enter, R.anim.home_exit); } } /** * Invoke "search" action, triggering a default search. */ public void goSearch() { mActivity.startSearch(null, false, Bundle.EMPTY, false); } /** * Sets up the action bar with the given title and accent color. If title is null, then * the app logo will be shown instead of a title. Otherwise, a home button and title are * visible. If color is null, then the default colorstrip is visible. */ public void setupActionBar(CharSequence title, int color) { final ViewGroup actionBarCompat = getActionBarCompat(); if (actionBarCompat == null) { return; } LinearLayout.LayoutParams springLayoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.FILL_PARENT); springLayoutParams.weight = 1; View.OnClickListener homeClickListener = new View.OnClickListener() { public void onClick(View view) { goHome(); } }; if (title != null) { // Add Home button addActionButtonCompat(R.drawable.ic_title_home, R.string.description_home, homeClickListener, true); // Add title text TextView titleText = new TextView(mActivity, null, R.attr.actionbarCompatTextStyle); titleText.setLayoutParams(springLayoutParams); titleText.setText(title); actionBarCompat.addView(titleText); } else { // Add logo ImageButton logo = new ImageButton(mActivity, null, R.attr.actionbarCompatLogoStyle); logo.setOnClickListener(homeClickListener); actionBarCompat.addView(logo); // Add spring (dummy view to align future children to the right) View spring = new View(mActivity); spring.setLayoutParams(springLayoutParams); actionBarCompat.addView(spring); } setActionBarColor(color); } /** * Sets the action bar color to the given color. */ public void setActionBarColor(int color) { if (color == 0) { return; } final View colorstrip = mActivity.findViewById(R.id.colorstrip); if (colorstrip == null) { return; } colorstrip.setBackgroundColor(color); } /** * Sets the action bar title to the given string. */ public void setActionBarTitle(CharSequence title) { ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return; } TextView titleText = (TextView) actionBar.findViewById(R.id.actionbar_compat_text); if (titleText != null) { titleText.setText(title); } } /** * Returns the {@link ViewGroup} for the action bar on phones (compatibility action bar). * Can return null, and will return null on Honeycomb. */ public ViewGroup getActionBarCompat() { return (ViewGroup) mActivity.findViewById(R.id.actionbar_compat); } /** * Adds an action bar button to the compatibility action bar (on phones). */ private View addActionButtonCompat(int iconResId, int textResId, View.OnClickListener clickListener, boolean separatorAfter) { final ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return null; } // Create the separator ImageView separator = new ImageView(mActivity, null, R.attr.actionbarCompatSeparatorStyle); separator.setLayoutParams( new ViewGroup.LayoutParams(2, ViewGroup.LayoutParams.FILL_PARENT)); // Create the button ImageButton actionButton = new ImageButton(mActivity, null, R.attr.actionbarCompatButtonStyle); actionButton.setLayoutParams(new ViewGroup.LayoutParams( (int) mActivity.getResources().getDimension(R.dimen.actionbar_compat_height), ViewGroup.LayoutParams.FILL_PARENT)); actionButton.setImageResource(iconResId); actionButton.setScaleType(ImageView.ScaleType.CENTER); actionButton.setContentDescription(mActivity.getResources().getString(textResId)); actionButton.setOnClickListener(clickListener); // Add separator and button to the action bar in the desired order if (!separatorAfter) { actionBar.addView(separator); } actionBar.addView(actionButton); if (separatorAfter) { actionBar.addView(separator); } return actionButton; } /** * Adds an action button to the compatibility action bar, using menu information from a * {@link MenuItem}. If the menu item ID is <code>menu_refresh</code>, the menu item's state * can be changed to show a loading spinner using * {@link ActivityHelper#setRefreshActionButtonCompatState(boolean)}. */ private View addActionButtonCompatFromMenuItem(final MenuItem item) { final ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return null; } // Create the separator ImageView separator = new ImageView(mActivity, null, R.attr.actionbarCompatSeparatorStyle); separator.setLayoutParams( new ViewGroup.LayoutParams(2, ViewGroup.LayoutParams.FILL_PARENT)); // Create the button ImageButton actionButton = new ImageButton(mActivity, null, R.attr.actionbarCompatButtonStyle); actionButton.setId(item.getItemId()); actionButton.setLayoutParams(new ViewGroup.LayoutParams( (int) mActivity.getResources().getDimension(R.dimen.actionbar_compat_height), ViewGroup.LayoutParams.FILL_PARENT)); actionButton.setImageDrawable(item.getIcon()); actionButton.setScaleType(ImageView.ScaleType.CENTER); actionButton.setContentDescription(item.getTitle()); actionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mActivity.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); } }); actionBar.addView(separator); actionBar.addView(actionButton); if (item.getItemId() == R.id.menu_refresh) { // Refresh buttons should be stateful, and allow for indeterminate progress indicators, // so add those. int buttonWidth = mActivity.getResources() .getDimensionPixelSize(R.dimen.actionbar_compat_height); int buttonWidthDiv3 = buttonWidth / 3; ProgressBar indicator = new ProgressBar(mActivity, null, R.attr.actionbarCompatProgressIndicatorStyle); LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( buttonWidthDiv3, buttonWidthDiv3); indicatorLayoutParams.setMargins(buttonWidthDiv3, buttonWidthDiv3, buttonWidth - 2 * buttonWidthDiv3, 0); indicator.setLayoutParams(indicatorLayoutParams); indicator.setVisibility(View.GONE); indicator.setId(R.id.menu_refresh_progress); actionBar.addView(indicator); } return actionButton; } /** * Sets the indeterminate loading state of a refresh button added with * {@link ActivityHelper#addActionButtonCompatFromMenuItem(android.view.MenuItem)} * (where the item ID was menu_refresh). */ public void setRefreshActionButtonCompatState(boolean refreshing) { View refreshButton = mActivity.findViewById(R.id.menu_refresh); View refreshIndicator = mActivity.findViewById(R.id.menu_refresh_progress); if (refreshButton != null) { refreshButton.setVisibility(refreshing ? View.GONE : View.VISIBLE); } if (refreshIndicator != null) { refreshIndicator.setVisibility(refreshing ? View.VISIBLE : View.GONE); } } }
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 java.lang.reflect.InvocationTargetException; public class ReflectionUtils { public static Object tryInvoke(Object target, String methodName, Object... args) { Class<?>[] argTypes = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { argTypes[i] = args[i].getClass(); } return tryInvoke(target, methodName, argTypes, args); } public static Object tryInvoke(Object target, String methodName, Class<?>[] argTypes, Object... args) { try { return target.getClass().getMethod(methodName, argTypes).invoke(target, args); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; } public static <E> E callWithDefault(Object target, String methodName, E defaultValue) { try { return (E) target.getClass().getMethod(methodName, (Class[]) null).invoke(target); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return defaultValue; } }
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 com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.ui.phone.MapActivity; import com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.preference.PreferenceManager; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.text.style.StyleSpan; import android.widget.TextView; import java.util.Formatter; import java.util.List; import java.util.Locale; import java.util.TimeZone; /** * An assortment of UI helpers. */ public class UIUtils { /** * Time zone to use when formatting all session times. To always use the * phone local time, use {@link TimeZone#getDefault()}. */ public static final TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone("America/Los_Angeles"); public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime( "2011-05-10T09:00:00.000-07:00"); public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime( "2011-05-11T17:30:00.000-07:00"); public static final Uri CONFERENCE_URL = Uri.parse("http://www.google.com/events/io/2011/"); /** Flags used with {@link DateUtils#formatDateRange}. */ private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY; /** {@link StringBuilder} used for formatting time block. */ private static StringBuilder sBuilder = new StringBuilder(50); /** {@link Formatter} used for formatting time block. */ private static Formatter sFormatter = new Formatter(sBuilder, Locale.getDefault()); private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD); /** * Format and return the given {@link Blocks} and {@link Rooms} values using * {@link #CONFERENCE_TIME_ZONE}. */ public static String formatSessionSubtitle(long blockStart, long blockEnd, String roomName, Context context) { TimeZone.setDefault(CONFERENCE_TIME_ZONE); // NOTE: There is an efficient version of formatDateRange in Eclair and // beyond that allows you to recycle a StringBuilder. final CharSequence timeString = DateUtils.formatDateRange(context, blockStart, blockEnd, TIME_FLAGS); return context.getString(R.string.session_subtitle, timeString, roomName); } /** * Populate the given {@link TextView} with the requested text, formatting * through {@link Html#fromHtml(String)} when applicable. Also sets * {@link TextView#setMovementMethod} so inline links are handled. */ public static void setTextMaybeHtml(TextView view, String text) { if (TextUtils.isEmpty(text)) { view.setText(""); return; } if (text.contains("<") && text.contains(">")) { view.setText(Html.fromHtml(text)); view.setMovementMethod(LinkMovementMethod.getInstance()); } else { view.setText(text); } } public static void setSessionTitleColor(long blockStart, long blockEnd, TextView title, TextView subtitle) { long currentTimeMillis = System.currentTimeMillis(); int colorId = R.color.body_text_1; int subColorId = R.color.body_text_2; if (currentTimeMillis > blockEnd && currentTimeMillis < CONFERENCE_END_MILLIS) { colorId = subColorId = R.color.body_text_disabled; } final Resources res = title.getResources(); title.setTextColor(res.getColor(colorId)); subtitle.setTextColor(res.getColor(subColorId)); } /** * Given a snippet string with matching segments surrounded by curly * braces, turn those areas into bold spans, removing the curly braces. */ public static Spannable buildStyledSnippet(String snippet) { final SpannableStringBuilder builder = new SpannableStringBuilder(snippet); // Walk through string, inserting bold snippet spans int startIndex = -1, endIndex = -1, delta = 0; while ((startIndex = snippet.indexOf('{', endIndex)) != -1) { endIndex = snippet.indexOf('}', startIndex); // Remove braces from both sides builder.delete(startIndex - delta, startIndex - delta + 1); builder.delete(endIndex - delta - 1, endIndex - delta); // Insert bold style builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); delta += 2; } return builder; } public static String getLastUsedTrackID(Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString("last_track_id", null); } public static void setLastUsedTrackID(Context context, String trackID) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString("last_track_id", trackID).commit(); } private static final int BRIGHTNESS_THRESHOLD = 130; /** * Calculate whether a color is light or dark, based on a commonly known * brightness formula. * * @see {@literal http://en.wikipedia.org/wiki/HSV_color_space%23Lightness} */ public static boolean isColorDark(int color) { return ((30 * Color.red(color) + 59 * Color.green(color) + 11 * Color.blue(color)) / 100) <= BRIGHTNESS_THRESHOLD; } public static boolean isHoneycomb() { // Can use static final constants like HONEYCOMB, declared in later versions // of the OS since they are inlined at compile time. This is guaranteed behavior. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } public static boolean isHoneycombTablet(Context context) { return isHoneycomb() && isTablet(context); } public static long getCurrentTime(final Context context) { //SharedPreferences prefs = context.getSharedPreferences("mock_data", 0); //prefs.edit().commit(); //return prefs.getLong("mock_current_time", System.currentTimeMillis()); return System.currentTimeMillis(); } public static Drawable getIconForIntent(final Context context, Intent i) { PackageManager pm = context.getPackageManager(); List<ResolveInfo> infos = pm.queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY); if (infos.size() > 0) { return infos.get(0).loadIcon(pm); } return null; } public static Class getMapActivityClass(Context context) { if (UIUtils.isHoneycombTablet(context)) { return MapMultiPaneActivity.class; } return MapActivity.class; } }
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 java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.SortedSet; import java.util.TreeSet; /** * Provides static methods for creating mutable {@code Set} instances easily and * other static methods for working with Sets. * */ public class Sets { /** * Creates an empty {@code HashSet} instance. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link * EnumSet#noneOf} instead. * * <p><b>Note:</b> if you only need an <i>immutable</i> empty Set, * use {@link Collections#emptySet} instead. * * @return a newly-created, initially-empty {@code HashSet} */ public static <K> HashSet<K> newHashSet() { return new HashSet<K>(); } /** * Creates a {@code HashSet} instance containing the given elements. * * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the * following: * * <p>{@code Set<Base> set = Sets.newHashSet(sub1, sub2);} * * <p>where {@code sub1} and {@code sub2} are references to subtypes of {@code * Base}, not of {@code Base} itself. To get around this, you must use: * * <p>{@code Set<Base> set = Sets.<Base>newHashSet(sub1, sub2);} * * @param elements the elements that the set should contain * @return a newly-created {@code HashSet} containing those elements (minus * duplicates) */ public static <E> HashSet<E> newHashSet(E... elements) { int capacity = elements.length * 4 / 3 + 1; HashSet<E> set = new HashSet<E>(capacity); Collections.addAll(set, elements); return set; } /** * Creates a {@code SortedSet} instance containing the given elements. * * @param elements the elements that the set should contain * @return a newly-created {@code SortedSet} containing those elements (minus * duplicates) */ public static <E> SortedSet<E> newSortedSet(E... elements) { SortedSet<E> set = new TreeSet<E>(); Collections.addAll(set, elements); return set; } }
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 java.io.IOException; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.CONTENT; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.UPDATED; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class SpreadsheetEntry extends HashMap<String, String> { private static final Pattern sContentPattern = Pattern.compile( "(?:^|, )([_a-zA-Z0-9]+): (.*?)(?=\\s*$|, [_a-zA-Z0-9]+: )", Pattern.DOTALL); private static Matcher sContentMatcher; private static Matcher getContentMatcher(CharSequence input) { if (sContentMatcher == null) { sContentMatcher = sContentPattern.matcher(input); } else { sContentMatcher.reset(input); } return sContentMatcher; } private long mUpdated; public long getUpdated() { return mUpdated; } public static SpreadsheetEntry fromParser(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final SpreadsheetEntry entry = new SpreadsheetEntry(); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { if (UPDATED.equals(tag)) { final String text = parser.getText(); entry.mUpdated = ParserUtils.parseTime(text); } else if (CONTENT.equals(tag)) { final String text = parser.getText(); final Matcher matcher = getContentMatcher(text); while (matcher.find()) { final String key = matcher.group(1); final String value = matcher.group(2).trim(); entry.put(key, value); } } } } return entry; } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * 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 android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import java.lang.ref.WeakReference; /** * Slightly more abstract {@link AsyncQueryHandler} that helps keep a * {@link WeakReference} back to a listener. Will properly close any * {@link Cursor} if the listener ceases to exist. * <p> * This pattern can be used to perform background queries without leaking * {@link Context} objects. * * @hide pending API council review */ public class NotifyingAsyncQueryHandler extends AsyncQueryHandler { private WeakReference<AsyncQueryListener> mListener; /** * Interface to listen for completed query operations. */ public interface AsyncQueryListener { void onQueryComplete(int token, Object cookie, Cursor cursor); } public NotifyingAsyncQueryHandler(ContentResolver resolver, AsyncQueryListener listener) { super(resolver); setQueryListener(listener); } /** * Assign the given {@link AsyncQueryListener} to receive query events from * asynchronous calls. Will replace any existing listener. */ public void setQueryListener(AsyncQueryListener listener) { mListener = new WeakReference<AsyncQueryListener>(listener); } /** * Clear any {@link AsyncQueryListener} set through * {@link #setQueryListener(AsyncQueryListener)} */ public void clearQueryListener() { mListener = null; } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is * called if a valid {@link AsyncQueryListener} is present. */ public void startQuery(Uri uri, String[] projection) { startQuery(-1, null, uri, projection, null, null, null); } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called * if a valid {@link AsyncQueryListener} is present. * * @param token Unique identifier passed through to * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} */ public void startQuery(int token, Uri uri, String[] projection) { startQuery(token, null, uri, projection, null, null, null); } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called * if a valid {@link AsyncQueryListener} is present. */ public void startQuery(Uri uri, String[] projection, String sortOrder) { startQuery(-1, null, uri, projection, null, null, sortOrder); } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called * if a valid {@link AsyncQueryListener} is present. */ public void startQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy) { startQuery(-1, null, uri, projection, selection, selectionArgs, orderBy); } /** * Begin an asynchronous update with the given arguments. */ public void startUpdate(Uri uri, ContentValues values) { startUpdate(-1, null, uri, values, null, null); } public void startInsert(Uri uri, ContentValues values) { startInsert(-1, null, uri, values); } public void startDelete(Uri uri) { startDelete(-1, null, uri, null, null); } /** {@inheritDoc} */ @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { final AsyncQueryListener listener = mListener == null ? null : mListener.get(); if (listener != null) { listener.onQueryComplete(token, cookie, cursor); } else if (cursor != null) { cursor.close(); } } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * 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 java.util.HashMap; import java.util.LinkedHashMap; /** * Provides static methods for creating mutable {@code Maps} instances easily. */ public class Maps { /** * Creates a {@code HashMap} instance. * * @return a newly-created, initially-empty {@code HashMap} */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } /** * Creates a {@code LinkedHashMap} instance. * * @return a newly-created, initially-empty {@code HashMap} */ public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() { return new LinkedHashMap<K, V>(); } }
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 com.google.android.apps.iosched.io.XmlHandler; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.text.format.Time; import java.io.InputStream; import java.util.ArrayList; import java.util.Set; import java.util.regex.Pattern; /** * Various utility methods used by {@link XmlHandler} implementations. */ public class ParserUtils { // TODO: consider refactor to HandlerUtils? // TODO: localize this string at some point public static final String BLOCK_TITLE_BREAKOUT_SESSIONS = "Breakout sessions"; public static final String BLOCK_TYPE_FOOD = "food"; public static final String BLOCK_TYPE_SESSION = "session"; public static final String BLOCK_TYPE_OFFICE_HOURS = "officehours"; // TODO: factor this out into a separate data file. public static final Set<String> LOCAL_TRACK_IDS = Sets.newHashSet( "accessibility", "android", "appengine", "chrome", "commerce", "developertools", "gamedevelopment", "geo", "googleapis", "googleapps", "googletv", "techtalk", "webgames", "youtube"); /** Used to sanitize a string to be {@link Uri} safe. */ private static final Pattern sSanitizePattern = Pattern.compile("[^a-z0-9-_]"); private static final Pattern sParenPattern = Pattern.compile("\\(.*?\\)"); /** Used to split a comma-separated string. */ private static final Pattern sCommaPattern = Pattern.compile("\\s*,\\s*"); private static Time sTime = new Time(); private static XmlPullParserFactory sFactory; /** * Sanitize the given string to be {@link Uri} safe for building * {@link ContentProvider} paths. */ public static String sanitizeId(String input) { return sanitizeId(input, false); } /** * Sanitize the given string to be {@link Uri} safe for building * {@link ContentProvider} paths. */ public static String sanitizeId(String input, boolean stripParen) { if (input == null) return null; if (stripParen) { // Strip out all parenthetical statements when requested. input = sParenPattern.matcher(input).replaceAll(""); } return sSanitizePattern.matcher(input.toLowerCase()).replaceAll(""); } /** * Split the given comma-separated string, returning all values. */ public static String[] splitComma(CharSequence input) { if (input == null) return new String[0]; return sCommaPattern.split(input); } /** * Build and return a new {@link XmlPullParser} with the given * {@link InputStream} assigned to it. */ public static XmlPullParser newPullParser(InputStream input) throws XmlPullParserException { if (sFactory == null) { sFactory = XmlPullParserFactory.newInstance(); } final XmlPullParser parser = sFactory.newPullParser(); parser.setInput(input, null); return parser; } /** * Parse the given string as a RFC 3339 timestamp, returning the value as * milliseconds since the epoch. */ public static long parseTime(String time) { sTime.parse3339(time); return sTime.toMillis(false); } /** * Return a {@link Blocks#BLOCK_ID} matching the requested arguments. */ public static String findBlock(String title, long startTime, long endTime) { // TODO: in future we might check provider if block exists return Blocks.generateBlockId(startTime, endTime); } /** * Return a {@link Blocks#BLOCK_ID} matching the requested arguments, * inserting a new {@link Blocks} entry as a * {@link ContentProviderOperation} when none already exists. */ public static String findOrCreateBlock(String title, String type, long startTime, long endTime, ArrayList<ContentProviderOperation> batch, ContentResolver resolver) { // TODO: check for existence instead of always blindly creating. it's // okay for now since the database replaces on conflict. final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Blocks.CONTENT_URI); final String blockId = Blocks.generateBlockId(startTime, endTime); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTime); builder.withValue(Blocks.BLOCK_END, endTime); builder.withValue(Blocks.BLOCK_TYPE, type); batch.add(builder.build()); return blockId; } /** * Query and return the {@link SyncColumns#UPDATED} time for the requested * {@link Uri}. Expects the {@link Uri} to reference a single item. */ public static long queryItemUpdated(Uri uri, ContentResolver resolver) { final String[] projection = { SyncColumns.UPDATED }; final Cursor cursor = resolver.query(uri, projection, null, null, null); try { if (cursor.moveToFirst()) { return cursor.getLong(0); } else { return ScheduleContract.UPDATED_NEVER; } } finally { cursor.close(); } } /** * Query and return the newest {@link SyncColumns#UPDATED} time for all * entries under the requested {@link Uri}. Expects the {@link Uri} to * reference a directory of several items. */ public static long queryDirUpdated(Uri uri, ContentResolver resolver) { final String[] projection = { "MAX(" + SyncColumns.UPDATED + ")" }; final Cursor cursor = resolver.query(uri, projection, null, null, null); try { cursor.moveToFirst(); return cursor.getLong(0); } finally { cursor.close(); } } /** * Translate an incoming {@link Tracks#TRACK_ID}, usually passing directly * through, but returning a different value when a local alias is defined. */ public static String translateTrackIdAlias(String trackId) { //if ("gwt".equals(trackId)) { // return "googlewebtoolkit"; //} else { return trackId; //} } /** * Translate a possibly locally aliased {@link Tracks#TRACK_ID} to its real value; * this usually is a pass-through. */ public static String translateTrackIdAliasInverse(String trackId) { //if ("googlewebtoolkit".equals(trackId)) { // return "gwt"; //} else { return trackId; //} } /** XML tag constants used by the Atom standard. */ public interface AtomTags { String ENTRY = "entry"; String UPDATED = "updated"; String TITLE = "title"; String LINK = "link"; String CONTENT = "content"; String REL = "rel"; String HREF = "href"; } }
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 android.graphics.Rect; import android.graphics.RectF; import android.view.MotionEvent; import android.view.TouchDelegate; import android.view.View; /** * {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing * then against fractional dimensions of the source view. * <p> * This is particularly useful when you want to define a rectangle in terms of * the source dimensions, but when those dimensions might change due to pending * or future layout passes. * <p> * One example is catching touches that occur in the top-right quadrant of * {@code sourceParent}, and relaying them to {@code targetChild}. This could be * done with: <code> * FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f)); * </code> */ public class FractionalTouchDelegate extends TouchDelegate { private View mSource; private View mTarget; private RectF mSourceFraction; private Rect mScrap = new Rect(); /** Cached full dimensions of {@link #mSource}. */ private Rect mSourceFull = new Rect(); /** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */ private Rect mSourcePartial = new Rect(); private boolean mDelegateTargeted; public FractionalTouchDelegate(View source, View target, RectF sourceFraction) { super(new Rect(0, 0, 0, 0), target); mSource = source; mTarget = target; mSourceFraction = sourceFraction; } /** * Helper to create and setup a {@link FractionalTouchDelegate} between the * given {@link View}. * * @param source Larger source {@link View}, usually a parent, that will be * assigned {@link View#setTouchDelegate(TouchDelegate)}. * @param target Smaller target {@link View} which will receive * {@link MotionEvent} that land in requested fractional area. * @param sourceFraction Fractional area projected onto source {@link View} * which determines when {@link MotionEvent} will be passed to * target {@link View}. */ public static void setupDelegate(View source, View target, RectF sourceFraction) { source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction)); } /** * Consider updating {@link #mSourcePartial} when {@link #mSource} * dimensions have changed. */ private void updateSourcePartial() { mSource.getHitRect(mScrap); if (!mScrap.equals(mSourceFull)) { // Copy over and calculate fractional rectangle mSourceFull.set(mScrap); final int width = mSourceFull.width(); final int height = mSourceFull.height(); mSourcePartial.left = (int) (mSourceFraction.left * width); mSourcePartial.top = (int) (mSourceFraction.top * height); mSourcePartial.right = (int) (mSourceFraction.right * width); mSourcePartial.bottom = (int) (mSourceFraction.bottom * height); } } @Override public boolean onTouchEvent(MotionEvent event) { updateSourcePartial(); // The logic below is mostly copied from the parent class, since we // can't update private mBounds variable. // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob; // f=core/java/android/view/TouchDelegate.java;hb=eclair#l98 final Rect sourcePartial = mSourcePartial; final View target = mTarget; int x = (int)event.getX(); int y = (int)event.getY(); boolean sendToDelegate = false; boolean hit = true; boolean handled = false; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (sourcePartial.contains(x, y)) { mDelegateTargeted = true; sendToDelegate = true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_MOVE: sendToDelegate = mDelegateTargeted; if (sendToDelegate) { if (!sourcePartial.contains(x, y)) { hit = false; } } break; case MotionEvent.ACTION_CANCEL: sendToDelegate = mDelegateTargeted; mDelegateTargeted = false; break; } if (sendToDelegate) { if (hit) { event.setLocation(target.getWidth() / 2, target.getHeight() / 2); } else { event.setLocation(-1, -1); } handled = target.dispatchTouchEvent(event); } return handled; } }
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 android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log; /** * Proxy {@link ResultReceiver} that offers a listener interface that can be * detached. Useful for when sending callbacks to a {@link Service} where a * listening {@link Activity} can be swapped out during configuration changes. */ public class DetachableResultReceiver extends ResultReceiver { private static final String TAG = "DetachableResultReceiver"; private Receiver mReceiver; public DetachableResultReceiver(Handler handler) { super(handler); } public void clearReceiver() { mReceiver = null; } public void setReceiver(Receiver receiver) { mReceiver = receiver; } public interface Receiver { public void onReceiveResult(int resultCode, Bundle resultData); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (mReceiver != null) { mReceiver.onReceiveResult(resultCode, resultData); } else { Log.w(TAG, "Dropping result on floor for code " + resultCode + ": " + resultData.toString()); } } }
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 com.google.android.apps.iosched.R; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; /** * A helper for showing EULAs and storing a {@link SharedPreferences} bit indicating whether the * user has accepted. */ public class EulaHelper { public static boolean hasAcceptedEula(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getBoolean("accepted_eula", false); } private static void setAcceptedEula(final Context context) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putBoolean("accepted_eula", true).commit(); return null; } }.execute(); } /** * Show End User License Agreement. * * @param accepted True IFF user has accepted license already, which means it can be dismissed. * If the user hasn't accepted, then the EULA must be accepted or the program * exits. * @param activity Activity started from. */ public static void showEula(final boolean accepted, final Activity activity) { AlertDialog.Builder eula = new AlertDialog.Builder(activity) .setTitle(R.string.eula_title) .setIcon(android.R.drawable.ic_dialog_info) .setMessage(R.string.eula_text) .setCancelable(accepted); if (accepted) { // If they've accepted the EULA allow, show an OK to dismiss. eula.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } else { // If they haven't accepted the EULA allow, show accept/decline buttons and exit on // decline. eula .setPositiveButton(R.string.accept, new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { setAcceptedEula(activity); dialog.dismiss(); } }) .setNegativeButton(R.string.decline, new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); activity.finish(); } }); } eula.show(); } }
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 com.google.android.apps.iosched.R; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; /** * Helper class for the Catch Notes integration, based on example code at * {@link https://github.com/catch/docs-api/}. */ public class CatchNotesHelper { private static final String TAG = "CatchNotesHelper"; // Intent actions public static final String ACTION_ADD = "com.catchnotes.intent.action.ADD"; public static final String ACTION_VIEW = "com.catchnotes.intent.action.VIEW"; // Intent extras for ACTION_ADD public static final String EXTRA_SOURCE = "com.catchnotes.intent.extra.SOURCE"; public static final String EXTRA_SOURCE_URL = "com.catchnotes.intent.extra.SOURCE_URL"; // Intent extras for ACTION_VIEW public static final String EXTRA_VIEW_FILTER = "com.catchnotes.intent.extra.VIEW_FILTER"; // Note: "3banana" was the original name of Catch Notes. Though it has been // rebranded, the package name must persist. private static final String NOTES_PACKAGE_NAME = "com.threebanana.notes"; private static final String NOTES_MARKET_URI = "http://market.android.com/details?id=" + NOTES_PACKAGE_NAME; private static final int NOTES_MIN_VERSION_CODE = 54; private final Context mContext; public CatchNotesHelper(Context context) { mContext = context; } public Intent createNoteIntent(String message) { if (!isNotesInstalledAndMinimumVersion()) { return notesMarketIntent(); } Intent intent = new Intent(); intent.setAction(ACTION_ADD); intent.putExtra(Intent.EXTRA_TEXT, message); intent.putExtra(EXTRA_SOURCE, mContext.getString(R.string.app_name)); intent.putExtra(EXTRA_SOURCE_URL, "http://www.google.com/io/"); intent.putExtra(Intent.EXTRA_TITLE, mContext.getString(R.string.app_name)); return intent; } public Intent viewNotesIntent(String tag) { if (!isNotesInstalledAndMinimumVersion()) { return notesMarketIntent(); } if (!tag.startsWith("#")) { tag = "#" + tag; } Intent intent = new Intent(); intent.setAction(ACTION_VIEW); intent.putExtra(EXTRA_VIEW_FILTER, tag); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } /** * Returns the installation status of Catch Notes. */ public boolean isNotesInstalledAndMinimumVersion() { try { PackageInfo packageInfo = mContext.getPackageManager() .getPackageInfo(NOTES_PACKAGE_NAME, PackageManager.GET_ACTIVITIES); if (packageInfo.versionCode < NOTES_MIN_VERSION_CODE) { return false; } } catch (NameNotFoundException e) { return false; } return true; } public Intent notesMarketIntent() { Uri uri = Uri.parse(NOTES_MARKET_URI); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 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.util; import com.google.android.apps.iosched.R; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; /** * An extension of {@link ActivityHelper} that provides Android 3.0-specific functionality for * Honeycomb tablets. It thus requires API level 11. */ public class ActivityHelperHoneycomb extends ActivityHelper { private Menu mOptionsMenu; protected ActivityHelperHoneycomb(Activity activity) { super(activity); } @Override public void onPostCreate(Bundle savedInstanceState) { // Do nothing in onPostCreate. ActivityHelper creates the old action bar, we don't // need to for Honeycomb. } @Override public boolean onCreateOptionsMenu(Menu menu) { mOptionsMenu = menu; return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Handle the HOME / UP affordance. Since the app is only two levels deep // hierarchically, UP always just goes home. goHome(); return true; } return super.onOptionsItemSelected(item); } /** {@inheritDoc} */ @Override public void setupHomeActivity() { super.setupHomeActivity(); // NOTE: there needs to be a content view set before this is called, so this method // should be called in onPostCreate. if (UIUtils.isTablet(mActivity)) { mActivity.getActionBar().setDisplayOptions( 0, ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE); } else { mActivity.getActionBar().setDisplayOptions( ActionBar.DISPLAY_USE_LOGO, ActionBar.DISPLAY_USE_LOGO | ActionBar.DISPLAY_SHOW_TITLE); } } /** {@inheritDoc} */ @Override public void setupSubActivity() { super.setupSubActivity(); // NOTE: there needs to be a content view set before this is called, so this method // should be called in onPostCreate. if (UIUtils.isTablet(mActivity)) { mActivity.getActionBar().setDisplayOptions( ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO, ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO); } else { mActivity.getActionBar().setDisplayOptions( 0, ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO); } } /** * No-op on Honeycomb. The action bar title always remains the same. */ @Override public void setActionBarTitle(CharSequence title) { } /** * No-op on Honeycomb. The action bar color always remains the same. */ @Override public void setActionBarColor(int color) { if (!UIUtils.isTablet(mActivity)) { super.setActionBarColor(color); } } /** {@inheritDoc} */ @Override public void setRefreshActionButtonCompatState(boolean refreshing) { // On Honeycomb, we can set the state of the refresh button by giving it a custom // action view. if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { refreshItem.setActionView(R.layout.actionbar_indeterminate_progress); } else { refreshItem.setActionView(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.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.util.Lists; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.graphics.Color; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalTracksHandler extends XmlHandler { public LocalTracksHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); batch.add(ContentProviderOperation.newDelete(Tracks.CONTENT_URI).build()); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.TRACK.equals(parser.getName())) { batch.add(parseTrack(parser)); } } return batch; } private static ContentProviderOperation parseTrack(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Tracks.CONTENT_URI); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.NAME.equals(tag)) { final String trackId = sanitizeId(text); builder.withValue(Tracks.TRACK_ID, trackId); builder.withValue(Tracks.TRACK_NAME, text); } else if (Tags.COLOR.equals(tag)) { final int color = Color.parseColor(text); builder.withValue(Tracks.TRACK_COLOR, color); } else if (Tags.ABSTRACT.equals(tag)) { builder.withValue(Tracks.TRACK_ABSTRACT, text); } } } return builder.build(); } interface Tags { String TRACK = "track"; String NAME = "name"; String COLOR = "color"; String ABSTRACT = "abstract"; } }
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.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.SpreadsheetEntry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static com.google.android.apps.iosched.util.ParserUtils.queryItemUpdated; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; /** * Handle a remote {@link XmlPullParser} that defines a set of {@link Speakers} * entries. Assumes that the remote source is a Google Spreadsheet. */ public class RemoteSpeakersHandler extends XmlHandler { private static final String TAG = "SpeakersHandler"; public RemoteSpeakersHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String speakerId = sanitizeId(entry.get(Columns.SPEAKER_TITLE), true); final Uri speakerUri = Speakers.buildSpeakerUri(speakerId); // Check for existing details, only update when changed final long localUpdated = queryItemUpdated(speakerUri, resolver); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found speaker " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; // Clear any existing values for this speaker, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(speakerUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Speakers.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Speakers.SPEAKER_ID, speakerId); builder.withValue(Speakers.SPEAKER_NAME, entry.get(Columns.SPEAKER_TITLE)); builder.withValue(Speakers.SPEAKER_IMAGE_URL, entry.get(Columns.SPEAKER_IMAGE_URL)); builder.withValue(Speakers.SPEAKER_COMPANY, entry.get(Columns.SPEAKER_COMPANY)); builder.withValue(Speakers.SPEAKER_ABSTRACT, entry.get(Columns.SPEAKER_ABSTRACT)); builder.withValue(Speakers.SPEAKER_URL, entry.get(Columns.SPEAKER_URL)); // Normal speaker details ready, write to provider batch.add(builder.build()); } } return batch; } /** Columns coming from remote spreadsheet. */ private interface Columns { String SPEAKER_TITLE = "speakertitle"; String SPEAKER_IMAGE_URL = "speakerimageurl"; String SPEAKER_COMPANY = "speakercompany"; String SPEAKER_ABSTRACT = "speakerabstract"; String SPEAKER_URL = "speakerurl"; // speaker_title: Aaron Koblin // speaker_image_url: http://path/to/image.png // speaker_company: Google // speaker_abstract: Aaron takes social and infrastructural data and uses... // speaker_url: http://profiles.google.com/... } }
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.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.SpreadsheetEntry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; /** * Handle a remote {@link XmlPullParser} that defines a set of {@link Vendors} * entries. Assumes that the remote source is a Google Spreadsheet. */ public class RemoteVendorsHandler extends XmlHandler { private static final String TAG = "VendorsHandler"; public RemoteVendorsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String vendorId = sanitizeId(entry.get(Columns.COMPANY_NAME)); final Uri vendorUri = Vendors.buildVendorUri(vendorId); // Check for existing details, only update when changed final ContentValues values = queryVendorDetails(vendorUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found vendor " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; // Clear any existing values for this vendor, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(vendorUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Vendors.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Vendors.VENDOR_ID, vendorId); builder.withValue(Vendors.VENDOR_NAME, entry.get(Columns.COMPANY_NAME)); builder.withValue(Vendors.VENDOR_LOCATION, entry.get(Columns.COMPANY_LOCATION)); builder.withValue(Vendors.VENDOR_DESC, entry.get(Columns.COMPANY_DESC)); builder.withValue(Vendors.VENDOR_URL, entry.get(Columns.COMPANY_URL)); builder.withValue(Vendors.VENDOR_LOGO_URL, entry.get(Columns.COMPANY_LOGO)); builder.withValue(Vendors.VENDOR_PRODUCT_DESC, entry.get(Columns.COMPANY_PRODUCT_DESC)); // Inherit starred value from previous row if (values.containsKey(Vendors.VENDOR_STARRED)) { builder.withValue(Vendors.VENDOR_STARRED, values.getAsInteger(Vendors.VENDOR_STARRED)); } // Assign track final String trackId = ParserUtils.translateTrackIdAlias(sanitizeId(entry .get(Columns.COMPANY_POD))); builder.withValue(Vendors.TRACK_ID, trackId); // Normal vendor details ready, write to provider batch.add(builder.build()); } } return batch; } private static ContentValues queryVendorDetails(Uri uri, ContentResolver resolver) { final ContentValues values = new ContentValues(); final Cursor cursor = resolver.query(uri, VendorsQuery.PROJECTION, null, null, null); try { if (cursor.moveToFirst()) { values.put(SyncColumns.UPDATED, cursor.getLong(VendorsQuery.UPDATED)); values.put(Vendors.VENDOR_STARRED, cursor.getInt(VendorsQuery.STARRED)); } else { values.put(SyncColumns.UPDATED, ScheduleContract.UPDATED_NEVER); } } finally { cursor.close(); } return values; } private interface VendorsQuery { String[] PROJECTION = { SyncColumns.UPDATED, Vendors.VENDOR_STARRED, }; int UPDATED = 0; int STARRED = 1; } /** Columns coming from remote spreadsheet. */ private interface Columns { String COMPANY_NAME = "companyname"; String COMPANY_LOCATION = "companylocation"; String COMPANY_DESC = "companydesc"; String COMPANY_URL = "companyurl"; String COMPANY_PRODUCT_DESC = "companyproductdesc"; String COMPANY_LOGO = "companylogo"; String COMPANY_POD = "companypod"; // company_name: 280 North, Inc. // company_location: San Francisco, California // company_desc: Creators of 280 Slides, a web based presentation // company_url: www.280north.com // company_product_desc: 280 Slides relies on the Google AJAX APIs to provide // company_logo: 280north.png // company_pod: Google APIs // company_tags: } }
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.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.util.Lists; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.SearchManager; import android.content.ContentProviderOperation; import android.content.ContentResolver; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalSearchSuggestHandler extends XmlHandler { public LocalSearchSuggestHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Clear any existing suggestion words batch.add(ContentProviderOperation.newDelete(SearchSuggest.CONTENT_URI).build()); String tag = null; int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.WORD.equals(tag)) { // Insert word as search suggestion batch.add(ContentProviderOperation.newInsert(SearchSuggest.CONTENT_URI) .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, text).build()); } } } return batch; } private interface Tags { String WORD = "word"; } }
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.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalSessionsHandler extends XmlHandler { public LocalSessionsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.SESSION.equals(parser.getName())) { parseSession(parser, batch, resolver); } } return batch; } private static void parseSession(XmlPullParser parser, ArrayList<ContentProviderOperation> batch, ContentResolver resolver) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Sessions.CONTENT_URI); builder.withValue(Sessions.UPDATED, 0); long startTime = -1; long endTime = -1; String title = null; String sessionId = null; String trackId = null; String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.START.equals(tag)) { startTime = ParserUtils.parseTime(text); } else if (Tags.END.equals(tag)) { endTime = ParserUtils.parseTime(text); } else if (Tags.ROOM.equals(tag)) { final String roomId = Rooms.generateRoomId(text); builder.withValue(Sessions.ROOM_ID, roomId); } else if (Tags.TRACK.equals(tag)) { trackId = Tracks.generateTrackId(text); } else if (Tags.ID.equals(tag)) { sessionId = text; } else if (Tags.TITLE.equals(tag)) { title = text; } else if (Tags.ABSTRACT.equals(tag)) { builder.withValue(Sessions.SESSION_ABSTRACT, text); } } } if (sessionId == null) { sessionId = Sessions.generateSessionId(title); } builder.withValue(Sessions.SESSION_ID, sessionId); builder.withValue(Sessions.SESSION_TITLE, title); // Use empty strings to make sure SQLite search trigger has valid data // for updating search index. builder.withValue(Sessions.SESSION_ABSTRACT, ""); builder.withValue(Sessions.SESSION_REQUIREMENTS, ""); builder.withValue(Sessions.SESSION_KEYWORDS, ""); final String blockId = ParserUtils.findBlock(title, startTime, endTime); builder.withValue(Sessions.BLOCK_ID, blockId); // Propagate any existing starred value final Uri sessionUri = Sessions.buildSessionUri(sessionId); final int starred = querySessionStarred(sessionUri, resolver); if (starred != -1) { builder.withValue(Sessions.SESSION_STARRED, starred); } batch.add(builder.build()); if (trackId != null) { // TODO: support parsing multiple tracks per session final Uri sessionTracks = Sessions.buildTracksDirUri(sessionId); batch.add(ContentProviderOperation.newInsert(sessionTracks) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } } public static int querySessionStarred(Uri uri, ContentResolver resolver) { final String[] projection = { Sessions.SESSION_STARRED }; final Cursor cursor = resolver.query(uri, projection, null, null, null); try { if (cursor.moveToFirst()) { return cursor.getInt(0); } else { return -1; } } finally { cursor.close(); } } interface Tags { String SESSION = "session"; String ID = "id"; String START = "start"; String END = "end"; String ROOM = "room"; String TRACK = "track"; String TITLE = "title"; String ABSTRACT = "abstract"; } }
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.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.OperationApplicationException; import android.os.RemoteException; import java.io.IOException; import java.util.ArrayList; /** * Abstract class that handles reading and parsing an {@link XmlPullParser} into * a set of {@link ContentProviderOperation}. It catches recoverable network * exceptions and rethrows them as {@link HandlerException}. Any local * {@link ContentProvider} exceptions are considered unrecoverable. * <p> * This class is only designed to handle simple one-way synchronization. */ public abstract class XmlHandler { private final String mAuthority; public XmlHandler(String authority) { mAuthority = authority; } /** * Parse the given {@link XmlPullParser}, turning into a series of * {@link ContentProviderOperation} that are immediately applied using the * given {@link ContentResolver}. */ public void parseAndApply(XmlPullParser parser, ContentResolver resolver) throws HandlerException { try { final ArrayList<ContentProviderOperation> batch = parse(parser, resolver); resolver.applyBatch(mAuthority, batch); } catch (HandlerException e) { throw e; } catch (XmlPullParserException e) { throw new HandlerException("Problem parsing XML response", e); } catch (IOException e) { throw new HandlerException("Problem reading response", e); } catch (RemoteException e) { // Failed binder transactions aren't recoverable throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { // Failures like constraint violation aren't recoverable // TODO: write unit tests to exercise full provider // TODO: consider catching version checking asserts here, and then // wrapping around to retry parsing again. throw new RuntimeException("Problem applying batch operation", e); } } /** * Parse the given {@link XmlPullParser}, returning a set of * {@link ContentProviderOperation} that will bring the * {@link ContentProvider} into sync with the parsed data. */ public abstract ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException; /** * General {@link IOException} that indicates a problem occured while * parsing or applying an {@link XmlPullParser}. */ public static class HandlerException extends IOException { public HandlerException(String message) { super(message); } public HandlerException(String message, Throwable cause) { super(message); initCause(cause); } @Override public String toString() { if (getCause() != null) { return getLocalizedMessage() + ": " + getCause(); } else { return getLocalizedMessage(); } } } }
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.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.util.Lists; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; /** * Handle a local {@link XmlPullParser} that defines a set of {@link Rooms} * entries. Usually loaded from {@link R.xml} resources. */ public class LocalRoomsHandler extends XmlHandler { public LocalRoomsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.ROOM.equals(parser.getName())) { parseRoom(parser, batch, resolver); } } return batch; } /** * Parse a given {@link Rooms} entry, building * {@link ContentProviderOperation} to define it locally. */ private static void parseRoom(XmlPullParser parser, ArrayList<ContentProviderOperation> batch, ContentResolver resolver) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Rooms.CONTENT_URI); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.ID.equals(tag)) { builder.withValue(Rooms.ROOM_ID, text); } else if (Tags.NAME.equals(tag)) { builder.withValue(Rooms.ROOM_NAME, text); } else if (Tags.FLOOR.equals(tag)) { builder.withValue(Rooms.ROOM_FLOOR, text); } } } batch.add(builder.build()); } /** XML tags expected from local source. */ private interface Tags { String ROOM = "room"; String ID = "id"; String NAME = "name"; String FLOOR = "floor"; } }
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.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.SpreadsheetEntry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.text.format.Time; import android.util.Log; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Locale; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static com.google.android.apps.iosched.util.ParserUtils.splitComma; import static com.google.android.apps.iosched.util.ParserUtils.translateTrackIdAlias; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; /** * Handle a remote {@link XmlPullParser} that defines a set of {@link Sessions} * entries. Assumes that the remote source is a Google Spreadsheet. */ public class RemoteSessionsHandler extends XmlHandler { private static final String TAG = "SessionsHandler"; /** * Custom format used internally that matches expected concatenation of * {@link Columns#SESSION_DATE} and {@link Columns#SESSION_TIME}. */ private static final SimpleDateFormat sTimeFormat = new SimpleDateFormat( "EEEE MMM d yyyy h:mma Z", Locale.US); public RemoteSessionsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String sessionId = sanitizeId(entry.get(Columns.SESSION_TITLE)); final Uri sessionUri = Sessions.buildSessionUri(sessionId); // Check for existing details, only update when changed final ContentValues values = querySessionDetails(sessionUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found session " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; final Uri sessionTracksUri = Sessions.buildTracksDirUri(sessionId); final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); // Clear any existing values for this session, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(sessionUri).build()); batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build()); batch.add(ContentProviderOperation.newDelete(sessionSpeakersUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Sessions.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Sessions.SESSION_ID, sessionId); builder.withValue(Sessions.SESSION_LEVEL, entry.get(Columns.SESSION_LEVEL)); builder.withValue(Sessions.SESSION_TITLE, entry.get(Columns.SESSION_TITLE)); builder.withValue(Sessions.SESSION_ABSTRACT, entry.get(Columns.SESSION_ABSTRACT)); builder.withValue(Sessions.SESSION_REQUIREMENTS, entry.get(Columns.SESSION_REQUIREMENTS)); builder.withValue(Sessions.SESSION_KEYWORDS, entry.get(Columns.SESSION_TAGS)); builder.withValue(Sessions.SESSION_HASHTAG, entry.get(Columns.SESSION_HASHTAG)); builder.withValue(Sessions.SESSION_SLUG, entry.get(Columns.SESSION_SLUG)); builder.withValue(Sessions.SESSION_URL, entry.get(Columns.SESSION_URL)); builder.withValue(Sessions.SESSION_MODERATOR_URL, entry.get(Columns.SESSION_MODERATOR_URL)); builder.withValue(Sessions.SESSION_YOUTUBE_URL, entry.get(Columns.SESSION_YOUTUBE_URL)); builder.withValue(Sessions.SESSION_PDF_URL, entry.get(Columns.SESSION_PDF_URL)); builder.withValue(Sessions.SESSION_FEEDBACK_URL, entry.get(Columns.SESSION_FEEDBACK_URL)); builder.withValue(Sessions.SESSION_NOTES_URL, entry.get(Columns.SESSION_NOTES_URL)); // Inherit starred value from previous row if (values.containsKey(Sessions.SESSION_STARRED)) { builder.withValue(Sessions.SESSION_STARRED, values.getAsInteger(Sessions.SESSION_STARRED)); } // Parse time string from two columns, which is pretty ugly code // since it assumes the column format is "Wednesday May 19" and // "10:45am-11:45am". Future spreadsheets should use RFC 3339. final String date = entry.get(Columns.SESSION_DATE); final String time = entry.get(Columns.SESSION_TIME); final int timeSplit = time.indexOf("-"); if (timeSplit == -1) { throw new HandlerException("Expecting " + Columns.SESSION_TIME + " to express span"); } final long startTime = parseTime(date, time.substring(0, timeSplit)); final long endTime = parseTime(date, time.substring(timeSplit + 1)); final String blockId = ParserUtils.findOrCreateBlock( ParserUtils.BLOCK_TITLE_BREAKOUT_SESSIONS, ParserUtils.BLOCK_TYPE_SESSION, startTime, endTime, batch, resolver); builder.withValue(Sessions.BLOCK_ID, blockId); // Assign room final String roomId = sanitizeId(entry.get(Columns.SESSION_ROOM)); builder.withValue(Sessions.ROOM_ID, roomId); // Normal session details ready, write to provider batch.add(builder.build()); // Assign tracks final String[] tracks = splitComma(entry.get(Columns.SESSION_TRACK)); for (String track : tracks) { final String trackId = translateTrackIdAlias(sanitizeId(track)); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } // Assign speakers final String[] speakers = splitComma(entry.get(Columns.SESSION_SPEAKERS)); for (String speaker : speakers) { final String speakerId = sanitizeId(speaker, true); batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, speakerId).build()); } } } return batch; } /** * Parse the given date and time coming from spreadsheet. This is tightly * tied to a specific format. Ideally, if the source used use RFC 3339 we * could parse quickly using {@link Time#parse3339}. * <p> * Internally assumes PST time zone and year 2011. * * @param date String of format "Wednesday May 19", usually read from * {@link Columns#SESSION_DATE}. * @param time String of format "10:45am", usually after splitting * {@link Columns#SESSION_TIME}. */ private static long parseTime(String date, String time) throws HandlerException { final String composed = String.format("%s 2011 %s -0700", date, time); try { return sTimeFormat.parse(composed).getTime(); } catch (java.text.ParseException e) { throw new HandlerException("Problem parsing timestamp", e); } } private static ContentValues querySessionDetails(Uri uri, ContentResolver resolver) { final ContentValues values = new ContentValues(); final Cursor cursor = resolver.query(uri, SessionsQuery.PROJECTION, null, null, null); try { if (cursor.moveToFirst()) { values.put(SyncColumns.UPDATED, cursor.getLong(SessionsQuery.UPDATED)); values.put(Sessions.SESSION_STARRED, cursor.getInt(SessionsQuery.STARRED)); } else { values.put(SyncColumns.UPDATED, ScheduleContract.UPDATED_NEVER); } } finally { cursor.close(); } return values; } private interface SessionsQuery { String[] PROJECTION = { SyncColumns.UPDATED, Sessions.SESSION_STARRED, }; int UPDATED = 0; int STARRED = 1; } /** Columns coming from remote spreadsheet. */ private interface Columns { String SESSION_DATE = "sessiondate"; String SESSION_TIME = "sessiontime"; String SESSION_ROOM = "sessionroom"; String SESSION_TRACK = "sessiontrack"; String SESSION_LEVEL = "sessionlevel"; String SESSION_TITLE = "sessiontitle"; String SESSION_TAGS = "sessiontags"; String SESSION_HASHTAG = "sessionhashtag"; String SESSION_SLUG = "sessionslug"; String SESSION_SPEAKERS = "sessionspeakers"; String SESSION_ABSTRACT = "sessionabstract"; String SESSION_REQUIREMENTS = "sessionrequirements"; String SESSION_URL = "sessionurl"; String SESSION_MODERATOR_URL = "sessionmoderatorurl"; String SESSION_YOUTUBE_URL = "sessionyoutubeurl"; String SESSION_PDF_URL = "sessionpdfurl"; String SESSION_FEEDBACK_URL = "sessionfeedbackurl"; String SESSION_NOTES_URL = "sessionnotesurl"; // session_date: Wednesday May 19 // session_time: 10:45am-11:45am // session_room: 6 // session_track: Enterprise, App Engine // session_level: 201 // session_title: Run corporate applications on Google App Engine? Yes we do. // session_slug: run-corporate-applications // session_tags: Enterprise, SaaS, PaaS, Hosting, App Engine, Java // session_speakers: Ben Fried, John Smith // session_abstract: And you can too! Come hear Google's CIO Ben Fried describe... // session_requirements: None // session_url: http://www.google.com/events/io/2011/foo // session_hashtag: #io11android1 // session_youtube_url // session_pdf_url // session_feedback_url // session_moderator_url // session_notes_url } }
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.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.Maps; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.WorksheetEntry; import org.apache.http.client.methods.HttpGet; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; public class RemoteWorksheetsHandler extends XmlHandler { private static final String TAG = "WorksheetsHandler"; private RemoteExecutor mExecutor; public RemoteWorksheetsHandler(RemoteExecutor executor) { super(ScheduleContract.CONTENT_AUTHORITY); mExecutor = executor; } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final HashMap<String, WorksheetEntry> sheets = Maps.newHashMap(); // walk response, collecting all known spreadsheets int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { final WorksheetEntry entry = WorksheetEntry.fromParser(parser); Log.d(TAG, "found worksheet " + entry.toString()); sheets.put(entry.getTitle(), entry); } } // consider updating each spreadsheet based on update timestamp considerUpdate(sheets, Worksheets.SESSIONS, Sessions.CONTENT_URI, resolver); considerUpdate(sheets, Worksheets.SPEAKERS, Speakers.CONTENT_URI, resolver); considerUpdate(sheets, Worksheets.VENDORS, Vendors.CONTENT_URI, resolver); return Lists.newArrayList(); } private void considerUpdate(HashMap<String, WorksheetEntry> sheets, String sheetName, Uri targetDir, ContentResolver resolver) throws HandlerException { final WorksheetEntry entry = sheets.get(sheetName); if (entry == null) { // Silently ignore missing spreadsheets to allow sync to continue. Log.w(TAG, "Missing '" + sheetName + "' worksheet data"); return; // throw new HandlerException("Missing '" + sheetName + "' worksheet data"); } final long localUpdated = ParserUtils.queryDirUpdated(targetDir, resolver); final long serverUpdated = entry.getUpdated(); Log.d(TAG, "considerUpdate() for " + entry.getTitle() + " found localUpdated=" + localUpdated + ", server=" + serverUpdated); if (localUpdated >= serverUpdated) return; final HttpGet request = new HttpGet(entry.getListFeed()); final XmlHandler handler = createRemoteHandler(entry); mExecutor.execute(request, handler); } private XmlHandler createRemoteHandler(WorksheetEntry entry) { final String title = entry.getTitle(); if (Worksheets.SESSIONS.equals(title)) { return new RemoteSessionsHandler(); } else if (Worksheets.SPEAKERS.equals(title)) { return new RemoteSpeakersHandler(); } else if (Worksheets.VENDORS.equals(title)) { return new RemoteVendorsHandler(); } else { throw new IllegalArgumentException("Unknown worksheet type"); } } interface Worksheets { String SESSIONS = "sessions"; String SPEAKERS = "speakers"; String VENDORS = "sandbox"; } }
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.io.XmlHandler.HandlerException; 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.Context; import android.content.res.Resources; import android.content.res.XmlResourceParser; import java.io.IOException; import java.io.InputStream; /** * Opens a local {@link Resources#getXml(int)} and passes the resulting * {@link XmlPullParser} to the given {@link XmlHandler}. */ public class LocalExecutor { private Resources mRes; private ContentResolver mResolver; public LocalExecutor(Resources res, ContentResolver resolver) { mRes = res; mResolver = resolver; } public void execute(Context context, String assetName, XmlHandler handler) throws HandlerException { try { final InputStream input = context.getAssets().open(assetName); final XmlPullParser parser = ParserUtils.newPullParser(input); handler.parseAndApply(parser, mResolver); } catch (HandlerException e) { throw e; } catch (XmlPullParserException e) { throw new HandlerException("Problem parsing local asset: " + assetName, e); } catch (IOException e) { throw new HandlerException("Problem parsing local asset: " + assetName, e); } } public void execute(int resId, XmlHandler handler) throws HandlerException { final XmlResourceParser parser = mRes.getXml(resId); try { handler.parseAndApply(parser, mResolver); } finally { parser.close(); } } }
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.io.XmlHandler.HandlerException; import com.google.android.apps.iosched.util.ParserUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentResolver; import java.io.IOException; import java.io.InputStream; /** * Executes an {@link HttpUriRequest} and passes the result as an * {@link XmlPullParser} to the given {@link XmlHandler}. */ public class RemoteExecutor { private final HttpClient mHttpClient; private final ContentResolver mResolver; public RemoteExecutor(HttpClient httpClient, ContentResolver resolver) { mHttpClient = httpClient; mResolver = resolver; } /** * Execute a {@link HttpGet} request, passing a valid response through * {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}. */ public void executeGet(String url, XmlHandler handler) throws HandlerException { final HttpUriRequest request = new HttpGet(url); execute(request, handler); } /** * Execute this {@link HttpUriRequest}, passing a valid response through * {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}. */ public void execute(HttpUriRequest request, XmlHandler handler) throws HandlerException { try { final HttpResponse resp = mHttpClient.execute(request); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } final InputStream input = resp.getEntity().getContent(); try { final XmlPullParser parser = ParserUtils.newPullParser(input); handler.parseAndApply(parser, mResolver); } catch (XmlPullParserException e) { throw new HandlerException("Malformed response for " + request.getRequestLine(), e); } finally { if (input != null) input.close(); } } catch (HandlerException e) { throw e; } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(), e); } } }
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.ScheduleContract.Blocks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalBlocksHandler extends XmlHandler { public LocalBlocksHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Clear any existing static blocks, as they may have been updated. final String selection = Blocks.BLOCK_TYPE + "=? OR " + Blocks.BLOCK_TYPE +"=?"; final String[] selectionArgs = { ParserUtils.BLOCK_TYPE_FOOD, ParserUtils.BLOCK_TYPE_OFFICE_HOURS }; batch.add(ContentProviderOperation.newDelete(Blocks.CONTENT_URI) .withSelection(selection, selectionArgs).build()); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.BLOCK.equals(parser.getName())) { batch.add(parseBlock(parser)); } } return batch; } private static ContentProviderOperation parseBlock(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Blocks.CONTENT_URI); String title = null; long startTime = -1; long endTime = -1; String blockType = null; String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.TITLE.equals(tag)) { title = text; } else if (Tags.START.equals(tag)) { startTime = ParserUtils.parseTime(text); } else if (Tags.END.equals(tag)) { endTime = ParserUtils.parseTime(text); } else if (Tags.TYPE.equals(tag)) { blockType = text; } } } final String blockId = Blocks.generateBlockId(startTime, endTime); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTime); builder.withValue(Blocks.BLOCK_END, endTime); builder.withValue(Blocks.BLOCK_TYPE, blockType); return builder.build(); } interface Tags { String BLOCK = "block"; String TITLE = "title"; String START = "start"; String END = "end"; String TYPE = "type"; } }
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
/* * 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.io; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.SpreadsheetEntry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; /** * Handle a remote {@link XmlPullParser} that defines a set of {@link Vendors} * entries. Assumes that the remote source is a Google Spreadsheet. */ public class RemoteVendorsHandler extends XmlHandler { private static final String TAG = "VendorsHandler"; public RemoteVendorsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String vendorId = sanitizeId(entry.get(Columns.COMPANY_NAME)); final Uri vendorUri = Vendors.buildVendorUri(vendorId); // Check for existing details, only update when changed final ContentValues values = queryVendorDetails(vendorUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found vendor " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; // Clear any existing values for this vendor, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(vendorUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Vendors.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Vendors.VENDOR_ID, vendorId); builder.withValue(Vendors.VENDOR_NAME, entry.get(Columns.COMPANY_NAME)); builder.withValue(Vendors.VENDOR_LOCATION, entry.get(Columns.COMPANY_LOCATION)); builder.withValue(Vendors.VENDOR_DESC, entry.get(Columns.COMPANY_DESC)); builder.withValue(Vendors.VENDOR_URL, entry.get(Columns.COMPANY_URL)); builder.withValue(Vendors.VENDOR_LOGO_URL, entry.get(Columns.COMPANY_LOGO)); builder.withValue(Vendors.VENDOR_PRODUCT_DESC, entry.get(Columns.COMPANY_PRODUCT_DESC)); // Inherit starred value from previous row if (values.containsKey(Vendors.VENDOR_STARRED)) { builder.withValue(Vendors.VENDOR_STARRED, values.getAsInteger(Vendors.VENDOR_STARRED)); } // Assign track final String trackId = ParserUtils.translateTrackIdAlias(sanitizeId(entry .get(Columns.COMPANY_POD))); builder.withValue(Vendors.TRACK_ID, trackId); // Normal vendor details ready, write to provider batch.add(builder.build()); } } return batch; } private static ContentValues queryVendorDetails(Uri uri, ContentResolver resolver) { final ContentValues values = new ContentValues(); final Cursor cursor = resolver.query(uri, VendorsQuery.PROJECTION, null, null, null); try { if (cursor.moveToFirst()) { values.put(SyncColumns.UPDATED, cursor.getLong(VendorsQuery.UPDATED)); values.put(Vendors.VENDOR_STARRED, cursor.getInt(VendorsQuery.STARRED)); } else { values.put(SyncColumns.UPDATED, ScheduleContract.UPDATED_NEVER); } } finally { cursor.close(); } return values; } private interface VendorsQuery { String[] PROJECTION = { SyncColumns.UPDATED, Vendors.VENDOR_STARRED, }; int UPDATED = 0; int STARRED = 1; } /** Columns coming from remote spreadsheet. */ private interface Columns { String COMPANY_NAME = "companyname"; String COMPANY_LOCATION = "companylocation"; String COMPANY_DESC = "companydesc"; String COMPANY_URL = "companyurl"; String COMPANY_PRODUCT_DESC = "companyproductdesc"; String COMPANY_LOGO = "companylogo"; String COMPANY_POD = "companypod"; // company_name: 280 North, Inc. // company_location: San Francisco, California // company_desc: Creators of 280 Slides, a web based presentation // company_url: www.280north.com // company_product_desc: 280 Slides relies on the Google AJAX APIs to provide // company_logo: 280north.png // company_pod: Google APIs // company_tags: } }
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.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.SpreadsheetEntry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static com.google.android.apps.iosched.util.ParserUtils.queryItemUpdated; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; /** * Handle a remote {@link XmlPullParser} that defines a set of {@link Speakers} * entries. Assumes that the remote source is a Google Spreadsheet. */ public class RemoteSpeakersHandler extends XmlHandler { private static final String TAG = "SpeakersHandler"; public RemoteSpeakersHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String speakerId = sanitizeId(entry.get(Columns.SPEAKER_TITLE), true); final Uri speakerUri = Speakers.buildSpeakerUri(speakerId); // Check for existing details, only update when changed final long localUpdated = queryItemUpdated(speakerUri, resolver); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found speaker " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; // Clear any existing values for this speaker, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(speakerUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Speakers.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Speakers.SPEAKER_ID, speakerId); builder.withValue(Speakers.SPEAKER_NAME, entry.get(Columns.SPEAKER_TITLE)); builder.withValue(Speakers.SPEAKER_IMAGE_URL, entry.get(Columns.SPEAKER_IMAGE_URL)); builder.withValue(Speakers.SPEAKER_COMPANY, entry.get(Columns.SPEAKER_COMPANY)); builder.withValue(Speakers.SPEAKER_ABSTRACT, entry.get(Columns.SPEAKER_ABSTRACT)); builder.withValue(Speakers.SPEAKER_URL, entry.get(Columns.SPEAKER_URL)); // Normal speaker details ready, write to provider batch.add(builder.build()); } } return batch; } /** Columns coming from remote spreadsheet. */ private interface Columns { String SPEAKER_TITLE = "speakertitle"; String SPEAKER_IMAGE_URL = "speakerimageurl"; String SPEAKER_COMPANY = "speakercompany"; String SPEAKER_ABSTRACT = "speakerabstract"; String SPEAKER_URL = "speakerurl"; // speaker_title: Aaron Koblin // speaker_image_url: http://path/to/image.png // speaker_company: Google // speaker_abstract: Aaron takes social and infrastructural data and uses... // speaker_url: http://profiles.google.com/... } }
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.ScheduleContract.Tracks; import com.google.android.apps.iosched.util.Lists; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.graphics.Color; import java.io.IOException; import java.util.ArrayList; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalTracksHandler extends XmlHandler { public LocalTracksHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); batch.add(ContentProviderOperation.newDelete(Tracks.CONTENT_URI).build()); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.TRACK.equals(parser.getName())) { batch.add(parseTrack(parser)); } } return batch; } private static ContentProviderOperation parseTrack(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Tracks.CONTENT_URI); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.NAME.equals(tag)) { final String trackId = sanitizeId(text); builder.withValue(Tracks.TRACK_ID, trackId); builder.withValue(Tracks.TRACK_NAME, text); } else if (Tags.COLOR.equals(tag)) { final int color = Color.parseColor(text); builder.withValue(Tracks.TRACK_COLOR, color); } else if (Tags.ABSTRACT.equals(tag)) { builder.withValue(Tracks.TRACK_ABSTRACT, text); } } } return builder.build(); } interface Tags { String TRACK = "track"; String NAME = "name"; String COLOR = "color"; String ABSTRACT = "abstract"; } }
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.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.util.Lists; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.SearchManager; import android.content.ContentProviderOperation; import android.content.ContentResolver; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalSearchSuggestHandler extends XmlHandler { public LocalSearchSuggestHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Clear any existing suggestion words batch.add(ContentProviderOperation.newDelete(SearchSuggest.CONTENT_URI).build()); String tag = null; int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.WORD.equals(tag)) { // Insert word as search suggestion batch.add(ContentProviderOperation.newInsert(SearchSuggest.CONTENT_URI) .withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, text).build()); } } } return batch; } private interface Tags { String WORD = "word"; } }
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.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.Maps; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.WorksheetEntry; import org.apache.http.client.methods.HttpGet; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.net.Uri; import android.util.Log; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; public class RemoteWorksheetsHandler extends XmlHandler { private static final String TAG = "WorksheetsHandler"; private RemoteExecutor mExecutor; public RemoteWorksheetsHandler(RemoteExecutor executor) { super(ScheduleContract.CONTENT_AUTHORITY); mExecutor = executor; } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final HashMap<String, WorksheetEntry> sheets = Maps.newHashMap(); // walk response, collecting all known spreadsheets int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { final WorksheetEntry entry = WorksheetEntry.fromParser(parser); Log.d(TAG, "found worksheet " + entry.toString()); sheets.put(entry.getTitle(), entry); } } // consider updating each spreadsheet based on update timestamp considerUpdate(sheets, Worksheets.SESSIONS, Sessions.CONTENT_URI, resolver); considerUpdate(sheets, Worksheets.SPEAKERS, Speakers.CONTENT_URI, resolver); considerUpdate(sheets, Worksheets.VENDORS, Vendors.CONTENT_URI, resolver); return Lists.newArrayList(); } private void considerUpdate(HashMap<String, WorksheetEntry> sheets, String sheetName, Uri targetDir, ContentResolver resolver) throws HandlerException { final WorksheetEntry entry = sheets.get(sheetName); if (entry == null) { // Silently ignore missing spreadsheets to allow sync to continue. Log.w(TAG, "Missing '" + sheetName + "' worksheet data"); return; // throw new HandlerException("Missing '" + sheetName + "' worksheet data"); } final long localUpdated = ParserUtils.queryDirUpdated(targetDir, resolver); final long serverUpdated = entry.getUpdated(); Log.d(TAG, "considerUpdate() for " + entry.getTitle() + " found localUpdated=" + localUpdated + ", server=" + serverUpdated); if (localUpdated >= serverUpdated) return; final HttpGet request = new HttpGet(entry.getListFeed()); final XmlHandler handler = createRemoteHandler(entry); mExecutor.execute(request, handler); } private XmlHandler createRemoteHandler(WorksheetEntry entry) { final String title = entry.getTitle(); if (Worksheets.SESSIONS.equals(title)) { return new RemoteSessionsHandler(); } else if (Worksheets.SPEAKERS.equals(title)) { return new RemoteSpeakersHandler(); } else if (Worksheets.VENDORS.equals(title)) { return new RemoteVendorsHandler(); } else { throw new IllegalArgumentException("Unknown worksheet type"); } } interface Worksheets { String SESSIONS = "sessions"; String SPEAKERS = "speakers"; String VENDORS = "sandbox"; } }
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.io.XmlHandler.HandlerException; 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.Context; import android.content.res.Resources; import android.content.res.XmlResourceParser; import java.io.IOException; import java.io.InputStream; /** * Opens a local {@link Resources#getXml(int)} and passes the resulting * {@link XmlPullParser} to the given {@link XmlHandler}. */ public class LocalExecutor { private Resources mRes; private ContentResolver mResolver; public LocalExecutor(Resources res, ContentResolver resolver) { mRes = res; mResolver = resolver; } public void execute(Context context, String assetName, XmlHandler handler) throws HandlerException { try { final InputStream input = context.getAssets().open(assetName); final XmlPullParser parser = ParserUtils.newPullParser(input); handler.parseAndApply(parser, mResolver); } catch (HandlerException e) { throw e; } catch (XmlPullParserException e) { throw new HandlerException("Problem parsing local asset: " + assetName, e); } catch (IOException e) { throw new HandlerException("Problem parsing local asset: " + assetName, e); } } public void execute(int resId, XmlHandler handler) throws HandlerException { final XmlResourceParser parser = mRes.getXml(resId); try { handler.parseAndApply(parser, mResolver); } finally { parser.close(); } } }
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.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.util.Lists; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; /** * Handle a local {@link XmlPullParser} that defines a set of {@link Rooms} * entries. Usually loaded from {@link R.xml} resources. */ public class LocalRoomsHandler extends XmlHandler { public LocalRoomsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.ROOM.equals(parser.getName())) { parseRoom(parser, batch, resolver); } } return batch; } /** * Parse a given {@link Rooms} entry, building * {@link ContentProviderOperation} to define it locally. */ private static void parseRoom(XmlPullParser parser, ArrayList<ContentProviderOperation> batch, ContentResolver resolver) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Rooms.CONTENT_URI); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.ID.equals(tag)) { builder.withValue(Rooms.ROOM_ID, text); } else if (Tags.NAME.equals(tag)) { builder.withValue(Rooms.ROOM_NAME, text); } else if (Tags.FLOOR.equals(tag)) { builder.withValue(Rooms.ROOM_FLOOR, text); } } } batch.add(builder.build()); } /** XML tags expected from local source. */ private interface Tags { String ROOM = "room"; String ID = "id"; String NAME = "name"; String FLOOR = "floor"; } }
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.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalSessionsHandler extends XmlHandler { public LocalSessionsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.SESSION.equals(parser.getName())) { parseSession(parser, batch, resolver); } } return batch; } private static void parseSession(XmlPullParser parser, ArrayList<ContentProviderOperation> batch, ContentResolver resolver) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Sessions.CONTENT_URI); builder.withValue(Sessions.UPDATED, 0); long startTime = -1; long endTime = -1; String title = null; String sessionId = null; String trackId = null; String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.START.equals(tag)) { startTime = ParserUtils.parseTime(text); } else if (Tags.END.equals(tag)) { endTime = ParserUtils.parseTime(text); } else if (Tags.ROOM.equals(tag)) { final String roomId = Rooms.generateRoomId(text); builder.withValue(Sessions.ROOM_ID, roomId); } else if (Tags.TRACK.equals(tag)) { trackId = Tracks.generateTrackId(text); } else if (Tags.ID.equals(tag)) { sessionId = text; } else if (Tags.TITLE.equals(tag)) { title = text; } else if (Tags.ABSTRACT.equals(tag)) { builder.withValue(Sessions.SESSION_ABSTRACT, text); } } } if (sessionId == null) { sessionId = Sessions.generateSessionId(title); } builder.withValue(Sessions.SESSION_ID, sessionId); builder.withValue(Sessions.SESSION_TITLE, title); // Use empty strings to make sure SQLite search trigger has valid data // for updating search index. builder.withValue(Sessions.SESSION_ABSTRACT, ""); builder.withValue(Sessions.SESSION_REQUIREMENTS, ""); builder.withValue(Sessions.SESSION_KEYWORDS, ""); final String blockId = ParserUtils.findBlock(title, startTime, endTime); builder.withValue(Sessions.BLOCK_ID, blockId); // Propagate any existing starred value final Uri sessionUri = Sessions.buildSessionUri(sessionId); final int starred = querySessionStarred(sessionUri, resolver); if (starred != -1) { builder.withValue(Sessions.SESSION_STARRED, starred); } batch.add(builder.build()); if (trackId != null) { // TODO: support parsing multiple tracks per session final Uri sessionTracks = Sessions.buildTracksDirUri(sessionId); batch.add(ContentProviderOperation.newInsert(sessionTracks) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } } public static int querySessionStarred(Uri uri, ContentResolver resolver) { final String[] projection = { Sessions.SESSION_STARRED }; final Cursor cursor = resolver.query(uri, projection, null, null, null); try { if (cursor.moveToFirst()) { return cursor.getInt(0); } else { return -1; } } finally { cursor.close(); } } interface Tags { String SESSION = "session"; String ID = "id"; String START = "start"; String END = "end"; String ROOM = "room"; String TRACK = "track"; String TITLE = "title"; String ABSTRACT = "abstract"; } }
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.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.SpreadsheetEntry; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.text.format.Time; import android.util.Log; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Locale; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.ENTRY; import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId; import static com.google.android.apps.iosched.util.ParserUtils.splitComma; import static com.google.android.apps.iosched.util.ParserUtils.translateTrackIdAlias; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.START_TAG; /** * Handle a remote {@link XmlPullParser} that defines a set of {@link Sessions} * entries. Assumes that the remote source is a Google Spreadsheet. */ public class RemoteSessionsHandler extends XmlHandler { private static final String TAG = "SessionsHandler"; /** * Custom format used internally that matches expected concatenation of * {@link Columns#SESSION_DATE} and {@link Columns#SESSION_TIME}. */ private static final SimpleDateFormat sTimeFormat = new SimpleDateFormat( "EEEE MMM d yyyy h:mma Z", Locale.US); public RemoteSessionsHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } /** {@inheritDoc} */ @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && ENTRY.equals(parser.getName())) { // Process single spreadsheet row at a time final SpreadsheetEntry entry = SpreadsheetEntry.fromParser(parser); final String sessionId = sanitizeId(entry.get(Columns.SESSION_TITLE)); final Uri sessionUri = Sessions.buildSessionUri(sessionId); // Check for existing details, only update when changed final ContentValues values = querySessionDetails(sessionUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found session " + entry.toString()); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated >= serverUpdated) continue; final Uri sessionTracksUri = Sessions.buildTracksDirUri(sessionId); final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId); // Clear any existing values for this session, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(sessionUri).build()); batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build()); batch.add(ContentProviderOperation.newDelete(sessionSpeakersUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Sessions.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Sessions.SESSION_ID, sessionId); builder.withValue(Sessions.SESSION_LEVEL, entry.get(Columns.SESSION_LEVEL)); builder.withValue(Sessions.SESSION_TITLE, entry.get(Columns.SESSION_TITLE)); builder.withValue(Sessions.SESSION_ABSTRACT, entry.get(Columns.SESSION_ABSTRACT)); builder.withValue(Sessions.SESSION_REQUIREMENTS, entry.get(Columns.SESSION_REQUIREMENTS)); builder.withValue(Sessions.SESSION_KEYWORDS, entry.get(Columns.SESSION_TAGS)); builder.withValue(Sessions.SESSION_HASHTAG, entry.get(Columns.SESSION_HASHTAG)); builder.withValue(Sessions.SESSION_SLUG, entry.get(Columns.SESSION_SLUG)); builder.withValue(Sessions.SESSION_URL, entry.get(Columns.SESSION_URL)); builder.withValue(Sessions.SESSION_MODERATOR_URL, entry.get(Columns.SESSION_MODERATOR_URL)); builder.withValue(Sessions.SESSION_YOUTUBE_URL, entry.get(Columns.SESSION_YOUTUBE_URL)); builder.withValue(Sessions.SESSION_PDF_URL, entry.get(Columns.SESSION_PDF_URL)); builder.withValue(Sessions.SESSION_FEEDBACK_URL, entry.get(Columns.SESSION_FEEDBACK_URL)); builder.withValue(Sessions.SESSION_NOTES_URL, entry.get(Columns.SESSION_NOTES_URL)); // Inherit starred value from previous row if (values.containsKey(Sessions.SESSION_STARRED)) { builder.withValue(Sessions.SESSION_STARRED, values.getAsInteger(Sessions.SESSION_STARRED)); } // Parse time string from two columns, which is pretty ugly code // since it assumes the column format is "Wednesday May 19" and // "10:45am-11:45am". Future spreadsheets should use RFC 3339. final String date = entry.get(Columns.SESSION_DATE); final String time = entry.get(Columns.SESSION_TIME); final int timeSplit = time.indexOf("-"); if (timeSplit == -1) { throw new HandlerException("Expecting " + Columns.SESSION_TIME + " to express span"); } final long startTime = parseTime(date, time.substring(0, timeSplit)); final long endTime = parseTime(date, time.substring(timeSplit + 1)); final String blockId = ParserUtils.findOrCreateBlock( ParserUtils.BLOCK_TITLE_BREAKOUT_SESSIONS, ParserUtils.BLOCK_TYPE_SESSION, startTime, endTime, batch, resolver); builder.withValue(Sessions.BLOCK_ID, blockId); // Assign room final String roomId = sanitizeId(entry.get(Columns.SESSION_ROOM)); builder.withValue(Sessions.ROOM_ID, roomId); // Normal session details ready, write to provider batch.add(builder.build()); // Assign tracks final String[] tracks = splitComma(entry.get(Columns.SESSION_TRACK)); for (String track : tracks) { final String trackId = translateTrackIdAlias(sanitizeId(track)); batch.add(ContentProviderOperation.newInsert(sessionTracksUri) .withValue(SessionsTracks.SESSION_ID, sessionId) .withValue(SessionsTracks.TRACK_ID, trackId).build()); } // Assign speakers final String[] speakers = splitComma(entry.get(Columns.SESSION_SPEAKERS)); for (String speaker : speakers) { final String speakerId = sanitizeId(speaker, true); batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri) .withValue(SessionsSpeakers.SESSION_ID, sessionId) .withValue(SessionsSpeakers.SPEAKER_ID, speakerId).build()); } } } return batch; } /** * Parse the given date and time coming from spreadsheet. This is tightly * tied to a specific format. Ideally, if the source used use RFC 3339 we * could parse quickly using {@link Time#parse3339}. * <p> * Internally assumes PST time zone and year 2011. * * @param date String of format "Wednesday May 19", usually read from * {@link Columns#SESSION_DATE}. * @param time String of format "10:45am", usually after splitting * {@link Columns#SESSION_TIME}. */ private static long parseTime(String date, String time) throws HandlerException { final String composed = String.format("%s 2011 %s -0700", date, time); try { return sTimeFormat.parse(composed).getTime(); } catch (java.text.ParseException e) { throw new HandlerException("Problem parsing timestamp", e); } } private static ContentValues querySessionDetails(Uri uri, ContentResolver resolver) { final ContentValues values = new ContentValues(); final Cursor cursor = resolver.query(uri, SessionsQuery.PROJECTION, null, null, null); try { if (cursor.moveToFirst()) { values.put(SyncColumns.UPDATED, cursor.getLong(SessionsQuery.UPDATED)); values.put(Sessions.SESSION_STARRED, cursor.getInt(SessionsQuery.STARRED)); } else { values.put(SyncColumns.UPDATED, ScheduleContract.UPDATED_NEVER); } } finally { cursor.close(); } return values; } private interface SessionsQuery { String[] PROJECTION = { SyncColumns.UPDATED, Sessions.SESSION_STARRED, }; int UPDATED = 0; int STARRED = 1; } /** Columns coming from remote spreadsheet. */ private interface Columns { String SESSION_DATE = "sessiondate"; String SESSION_TIME = "sessiontime"; String SESSION_ROOM = "sessionroom"; String SESSION_TRACK = "sessiontrack"; String SESSION_LEVEL = "sessionlevel"; String SESSION_TITLE = "sessiontitle"; String SESSION_TAGS = "sessiontags"; String SESSION_HASHTAG = "sessionhashtag"; String SESSION_SLUG = "sessionslug"; String SESSION_SPEAKERS = "sessionspeakers"; String SESSION_ABSTRACT = "sessionabstract"; String SESSION_REQUIREMENTS = "sessionrequirements"; String SESSION_URL = "sessionurl"; String SESSION_MODERATOR_URL = "sessionmoderatorurl"; String SESSION_YOUTUBE_URL = "sessionyoutubeurl"; String SESSION_PDF_URL = "sessionpdfurl"; String SESSION_FEEDBACK_URL = "sessionfeedbackurl"; String SESSION_NOTES_URL = "sessionnotesurl"; // session_date: Wednesday May 19 // session_time: 10:45am-11:45am // session_room: 6 // session_track: Enterprise, App Engine // session_level: 201 // session_title: Run corporate applications on Google App Engine? Yes we do. // session_slug: run-corporate-applications // session_tags: Enterprise, SaaS, PaaS, Hosting, App Engine, Java // session_speakers: Ben Fried, John Smith // session_abstract: And you can too! Come hear Google's CIO Ben Fried describe... // session_requirements: None // session_url: http://www.google.com/events/io/2011/foo // session_hashtag: #io11android1 // session_youtube_url // session_pdf_url // session_feedback_url // session_moderator_url // session_notes_url } }
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.io.XmlHandler.HandlerException; import com.google.android.apps.iosched.util.ParserUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentResolver; import java.io.IOException; import java.io.InputStream; /** * Executes an {@link HttpUriRequest} and passes the result as an * {@link XmlPullParser} to the given {@link XmlHandler}. */ public class RemoteExecutor { private final HttpClient mHttpClient; private final ContentResolver mResolver; public RemoteExecutor(HttpClient httpClient, ContentResolver resolver) { mHttpClient = httpClient; mResolver = resolver; } /** * Execute a {@link HttpGet} request, passing a valid response through * {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}. */ public void executeGet(String url, XmlHandler handler) throws HandlerException { final HttpUriRequest request = new HttpGet(url); execute(request, handler); } /** * Execute this {@link HttpUriRequest}, passing a valid response through * {@link XmlHandler#parseAndApply(XmlPullParser, ContentResolver)}. */ public void execute(HttpUriRequest request, XmlHandler handler) throws HandlerException { try { final HttpResponse resp = mHttpClient.execute(request); final int status = resp.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { throw new HandlerException("Unexpected server response " + resp.getStatusLine() + " for " + request.getRequestLine()); } final InputStream input = resp.getEntity().getContent(); try { final XmlPullParser parser = ParserUtils.newPullParser(input); handler.parseAndApply(parser, mResolver); } catch (XmlPullParserException e) { throw new HandlerException("Malformed response for " + request.getRequestLine(), e); } finally { if (input != null) input.close(); } } catch (HandlerException e) { throw e; } catch (IOException e) { throw new HandlerException("Problem reading remote response for " + request.getRequestLine(), e); } } }
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.ScheduleContract.Blocks; import com.google.android.apps.iosched.util.Lists; import com.google.android.apps.iosched.util.ParserUtils; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProviderOperation; import android.content.ContentResolver; import java.io.IOException; import java.util.ArrayList; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class LocalBlocksHandler extends XmlHandler { public LocalBlocksHandler() { super(ScheduleContract.CONTENT_AUTHORITY); } @Override public ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Clear any existing static blocks, as they may have been updated. final String selection = Blocks.BLOCK_TYPE + "=? OR " + Blocks.BLOCK_TYPE +"=?"; final String[] selectionArgs = { ParserUtils.BLOCK_TYPE_FOOD, ParserUtils.BLOCK_TYPE_OFFICE_HOURS }; batch.add(ContentProviderOperation.newDelete(Blocks.CONTENT_URI) .withSelection(selection, selectionArgs).build()); int type; while ((type = parser.next()) != END_DOCUMENT) { if (type == START_TAG && Tags.BLOCK.equals(parser.getName())) { batch.add(parseBlock(parser)); } } return batch; } private static ContentProviderOperation parseBlock(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Blocks.CONTENT_URI); String title = null; long startTime = -1; long endTime = -1; String blockType = null; String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (Tags.TITLE.equals(tag)) { title = text; } else if (Tags.START.equals(tag)) { startTime = ParserUtils.parseTime(text); } else if (Tags.END.equals(tag)) { endTime = ParserUtils.parseTime(text); } else if (Tags.TYPE.equals(tag)) { blockType = text; } } } final String blockId = Blocks.generateBlockId(startTime, endTime); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTime); builder.withValue(Blocks.BLOCK_END, endTime); builder.withValue(Blocks.BLOCK_TYPE, blockType); return builder.build(); } interface Tags { String BLOCK = "block"; String TITLE = "title"; String START = "start"; String END = "end"; String TYPE = "type"; } }
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.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.content.OperationApplicationException; import android.os.RemoteException; import java.io.IOException; import java.util.ArrayList; /** * Abstract class that handles reading and parsing an {@link XmlPullParser} into * a set of {@link ContentProviderOperation}. It catches recoverable network * exceptions and rethrows them as {@link HandlerException}. Any local * {@link ContentProvider} exceptions are considered unrecoverable. * <p> * This class is only designed to handle simple one-way synchronization. */ public abstract class XmlHandler { private final String mAuthority; public XmlHandler(String authority) { mAuthority = authority; } /** * Parse the given {@link XmlPullParser}, turning into a series of * {@link ContentProviderOperation} that are immediately applied using the * given {@link ContentResolver}. */ public void parseAndApply(XmlPullParser parser, ContentResolver resolver) throws HandlerException { try { final ArrayList<ContentProviderOperation> batch = parse(parser, resolver); resolver.applyBatch(mAuthority, batch); } catch (HandlerException e) { throw e; } catch (XmlPullParserException e) { throw new HandlerException("Problem parsing XML response", e); } catch (IOException e) { throw new HandlerException("Problem reading response", e); } catch (RemoteException e) { // Failed binder transactions aren't recoverable throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { // Failures like constraint violation aren't recoverable // TODO: write unit tests to exercise full provider // TODO: consider catching version checking asserts here, and then // wrapping around to retry parsing again. throw new RuntimeException("Problem applying batch operation", e); } } /** * Parse the given {@link XmlPullParser}, returning a set of * {@link ContentProviderOperation} that will bring the * {@link ContentProvider} into sync with the parsed data. */ public abstract ArrayList<ContentProviderOperation> parse(XmlPullParser parser, ContentResolver resolver) throws XmlPullParserException, IOException; /** * General {@link IOException} that indicates a problem occured while * parsing or applying an {@link XmlPullParser}. */ public static class HandlerException extends IOException { public HandlerException(String message) { super(message); } public HandlerException(String message, Throwable cause) { super(message); initCause(cause); } @Override public String toString() { if (getCause() != null) { return getLocalizedMessage() + ": " + getCause(); } else { return getLocalizedMessage(); } } } }
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.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleContract.VendorsColumns; import android.app.SearchManager; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log; /** * Helper for managing {@link SQLiteDatabase} that stores data for * {@link ScheduleProvider}. */ public class ScheduleDatabase extends SQLiteOpenHelper { private static final String TAG = "ScheduleDatabase"; private static final String DATABASE_NAME = "schedule.db"; // NOTE: carefully update onUpgrade() when bumping database versions to make // sure user data is saved. private static final int VER_LAUNCH = 21; private static final int VER_SESSION_FEEDBACK_URL = 22; private static final int VER_SESSION_NOTES_URL_SLUG = 23; private static final int DATABASE_VERSION = VER_SESSION_NOTES_URL_SLUG; interface Tables { String BLOCKS = "blocks"; String TRACKS = "tracks"; String ROOMS = "rooms"; String SESSIONS = "sessions"; String SPEAKERS = "speakers"; String SESSIONS_SPEAKERS = "sessions_speakers"; String SESSIONS_TRACKS = "sessions_tracks"; String VENDORS = "vendors"; String SESSIONS_SEARCH = "sessions_search"; String VENDORS_SEARCH = "vendors_search"; String SEARCH_SUGGEST = "search_suggest"; String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String VENDORS_JOIN_TRACKS = "vendors " + "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id"; String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers " + "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id"; String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers " + "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks " + "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id"; String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks " + "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search " + "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id " + "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id " + "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id"; String VENDORS_SEARCH_JOIN_VENDORS_TRACKS = "vendors_search " + "LEFT OUTER JOIN vendors ON vendors_search.vendor_id=vendors.vendor_id " + "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id"; } private interface Triggers { String SESSIONS_SEARCH_INSERT = "sessions_search_insert"; String SESSIONS_SEARCH_DELETE = "sessions_search_delete"; String SESSIONS_SEARCH_UPDATE = "sessions_search_update"; String VENDORS_SEARCH_INSERT = "vendors_search_insert"; String VENDORS_SEARCH_DELETE = "vendors_search_delete"; } public interface SessionsSpeakers { String SESSION_ID = "session_id"; String SPEAKER_ID = "speaker_id"; } public interface SessionsTracks { String SESSION_ID = "session_id"; String TRACK_ID = "track_id"; } interface SessionsSearchColumns { String SESSION_ID = "session_id"; String BODY = "body"; } interface VendorsSearchColumns { String VENDOR_ID = "vendor_id"; String BODY = "body"; } /** Fully-qualified field names. */ private interface Qualified { String SESSIONS_SEARCH_SESSION_ID = Tables.SESSIONS_SEARCH + "." + SessionsSearchColumns.SESSION_ID; String VENDORS_SEARCH_VENDOR_ID = Tables.VENDORS_SEARCH + "." + VendorsSearchColumns.VENDOR_ID; String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID + "," + SessionsSearchColumns.BODY + ")"; String VENDORS_SEARCH = Tables.VENDORS_SEARCH + "(" + VendorsSearchColumns.VENDOR_ID + "," + VendorsSearchColumns.BODY + ")"; } /** {@code REFERENCES} clauses. */ private interface References { String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")"; String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")"; String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")"; String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")"; String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")"; String VENDOR_ID = "REFERENCES " + Tables.VENDORS + "(" + Vendors.VENDOR_ID + ")"; } private interface Subquery { /** * Subquery used to build the {@link SessionsSearchColumns#BODY} string * used for indexing {@link Sessions} content. */ String SESSIONS_BODY = "(new." + Sessions.SESSION_TITLE + "||'; '||new." + Sessions.SESSION_ABSTRACT + "||'; '||" + "coalesce(new." + Sessions.SESSION_KEYWORDS + ", '')" + ")"; /** * Subquery used to build the {@link VendorsSearchColumns#BODY} string * used for indexing {@link Vendors} content. */ String VENDORS_BODY = "(new." + Vendors.VENDOR_NAME + "||'; '||new." + Vendors.VENDOR_DESC + "||'; '||new." + Vendors.VENDOR_PRODUCT_DESC + ")"; } public ScheduleDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + Tables.BLOCKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + BlocksColumns.BLOCK_ID + " TEXT NOT NULL," + BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL," + BlocksColumns.BLOCK_START + " INTEGER NOT NULL," + BlocksColumns.BLOCK_END + " INTEGER NOT NULL," + BlocksColumns.BLOCK_TYPE + " TEXT," + "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TracksColumns.TRACK_ID + " TEXT NOT NULL," + TracksColumns.TRACK_NAME + " TEXT," + TracksColumns.TRACK_COLOR + " INTEGER," + TracksColumns.TRACK_ABSTRACT + " TEXT," + "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.ROOMS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + RoomsColumns.ROOM_ID + " TEXT NOT NULL," + RoomsColumns.ROOM_NAME + " TEXT," + RoomsColumns.ROOM_FLOOR + " TEXT," + "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SessionsColumns.SESSION_ID + " TEXT NOT NULL," + Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + "," + Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + "," + SessionsColumns.SESSION_LEVEL + " TEXT," + SessionsColumns.SESSION_TITLE + " TEXT," + SessionsColumns.SESSION_ABSTRACT + " TEXT," + SessionsColumns.SESSION_REQUIREMENTS + " TEXT," + SessionsColumns.SESSION_KEYWORDS + " TEXT," + SessionsColumns.SESSION_HASHTAG + " TEXT," + SessionsColumns.SESSION_SLUG + " TEXT," + SessionsColumns.SESSION_URL + " TEXT," + SessionsColumns.SESSION_MODERATOR_URL + " TEXT," + SessionsColumns.SESSION_YOUTUBE_URL + " TEXT," + SessionsColumns.SESSION_PDF_URL + " TEXT," + SessionsColumns.SESSION_FEEDBACK_URL + " TEXT," + SessionsColumns.SESSION_NOTES_URL + " TEXT," + SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0," + "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL," + SpeakersColumns.SPEAKER_NAME + " TEXT," + SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT," + SpeakersColumns.SPEAKER_COMPANY + " TEXT," + SpeakersColumns.SPEAKER_ABSTRACT + " TEXT," + SpeakersColumns.SPEAKER_URL+ " TEXT," + "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + "," + "UNIQUE (" + SessionsSpeakers.SESSION_ID + "," + SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID + "," + "UNIQUE (" + SessionsTracks.SESSION_ID + "," + SessionsTracks.TRACK_ID + ") ON CONFLICT REPLACE)"); db.execSQL("CREATE TABLE " + Tables.VENDORS + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SyncColumns.UPDATED + " INTEGER NOT NULL," + VendorsColumns.VENDOR_ID + " TEXT NOT NULL," + Vendors.TRACK_ID + " TEXT " + References.TRACK_ID + "," + VendorsColumns.VENDOR_NAME + " TEXT," + VendorsColumns.VENDOR_LOCATION + " TEXT," + VendorsColumns.VENDOR_DESC + " TEXT," + VendorsColumns.VENDOR_URL + " TEXT," + VendorsColumns.VENDOR_PRODUCT_DESC + " TEXT," + VendorsColumns.VENDOR_LOGO_URL + " TEXT," + VendorsColumns.VENDOR_STARRED + " INTEGER," + "UNIQUE (" + VendorsColumns.VENDOR_ID + ") ON CONFLICT REPLACE)"); createSessionsSearch(db); createVendorsSearch(db); db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)"); } /** * Create triggers that automatically build {@link Tables#SESSIONS_SEARCH} * as values are changed in {@link Tables#SESSIONS}. */ private static void createSessionsSearch(SQLiteDatabase db) { // Using the "porter" tokenizer for simple stemming, so that // "frustration" matches "frustrated." db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SessionsSearchColumns.BODY + " TEXT NOT NULL," + SessionsSearchColumns.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + "," + "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE," + "tokenize=porter)"); // TODO: handle null fields in body, which cause trigger to fail // TODO: implement update trigger, not currently exercised db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_INSERT + " AFTER INSERT ON " + Tables.SESSIONS + " BEGIN INSERT INTO " + Qualified.SESSIONS_SEARCH + " " + " VALUES(new." + Sessions.SESSION_ID + ", " + Subquery.SESSIONS_BODY + ");" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_DELETE + " AFTER DELETE ON " + Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SEARCH + " " + " WHERE " + Qualified.SESSIONS_SEARCH_SESSION_ID + "=old." + Sessions.SESSION_ID + ";" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_UPDATE + " AFTER UPDATE ON " + Tables.SESSIONS + " BEGIN UPDATE sessions_search SET " + SessionsSearchColumns.BODY + " = " + Subquery.SESSIONS_BODY + " WHERE session_id = old.session_id" + "; END;"); } /** * Create triggers that automatically build {@link Tables#VENDORS_SEARCH} as * values are changed in {@link Tables#VENDORS}. */ private static void createVendorsSearch(SQLiteDatabase db) { // Using the "porter" tokenizer for simple stemming, so that // "frustration" matches "frustrated." db.execSQL("CREATE VIRTUAL TABLE " + Tables.VENDORS_SEARCH + " USING fts3(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + VendorsSearchColumns.BODY + " TEXT NOT NULL," + VendorsSearchColumns.VENDOR_ID + " TEXT NOT NULL " + References.VENDOR_ID + "," + "UNIQUE (" + VendorsSearchColumns.VENDOR_ID + ") ON CONFLICT REPLACE," + "tokenize=porter)"); // TODO: handle null fields in body, which cause trigger to fail // TODO: implement update trigger, not currently exercised db.execSQL("CREATE TRIGGER " + Triggers.VENDORS_SEARCH_INSERT + " AFTER INSERT ON " + Tables.VENDORS + " BEGIN INSERT INTO " + Qualified.VENDORS_SEARCH + " " + " VALUES(new." + Vendors.VENDOR_ID + ", " + Subquery.VENDORS_BODY + ");" + " END;"); db.execSQL("CREATE TRIGGER " + Triggers.VENDORS_SEARCH_DELETE + " AFTER DELETE ON " + Tables.VENDORS + " BEGIN DELETE FROM " + Tables.VENDORS_SEARCH + " " + " WHERE " + Qualified.VENDORS_SEARCH_VENDOR_ID + "=old." + Vendors.VENDOR_ID + ";" + " END;"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion); // NOTE: This switch statement is designed to handle cascading database // updates, starting at the current version and falling through to all // future upgrade cases. Only use "break;" when you want to drop and // recreate the entire database. int version = oldVersion; switch (version) { case VER_LAUNCH: // Version 22 added column for session feedback URL. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_FEEDBACK_URL + " TEXT"); version = VER_SESSION_FEEDBACK_URL; case VER_SESSION_FEEDBACK_URL: // Version 23 added columns for session official notes URL and slug. db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_NOTES_URL + " TEXT"); db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN " + SessionsColumns.SESSION_SLUG + " TEXT"); version = VER_SESSION_NOTES_URL_SLUG; } Log.d(TAG, "after upgrade logic, at version " + version); if (version != DATABASE_VERSION) { Log.w(TAG, "Destroying old data during upgrade"); db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS); db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_INSERT); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_DELETE); db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.VENDORS_SEARCH_INSERT); db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.VENDORS_SEARCH_DELETE); db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS_SEARCH); db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST); onCreate(db); } } }
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.provider; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Speakers; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers; import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks; import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables; import com.google.android.apps.iosched.provider.ScheduleDatabase.VendorsSearchColumns; import com.google.android.apps.iosched.service.SyncService; import com.google.android.apps.iosched.util.SelectionBuilder; import android.app.Activity; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.ParcelFileDescriptor; import android.provider.BaseColumns; import android.util.Log; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Provider that stores {@link ScheduleContract} data. Data is usually inserted * by {@link SyncService}, and queried by various {@link Activity} instances. */ public class ScheduleProvider extends ContentProvider { private static final String TAG = "ScheduleProvider"; private static final boolean LOGV = Log.isLoggable(TAG, Log.VERBOSE); private ScheduleDatabase mOpenHelper; private static final UriMatcher sUriMatcher = buildUriMatcher(); private static final int BLOCKS = 100; private static final int BLOCKS_BETWEEN = 101; private static final int BLOCKS_ID = 102; private static final int BLOCKS_ID_SESSIONS = 103; private static final int TRACKS = 200; private static final int TRACKS_ID = 201; private static final int TRACKS_ID_SESSIONS = 202; private static final int TRACKS_ID_VENDORS = 203; private static final int ROOMS = 300; private static final int ROOMS_ID = 301; private static final int ROOMS_ID_SESSIONS = 302; private static final int SESSIONS = 400; private static final int SESSIONS_STARRED = 401; private static final int SESSIONS_SEARCH = 402; private static final int SESSIONS_AT = 403; private static final int SESSIONS_ID = 404; private static final int SESSIONS_ID_SPEAKERS = 405; private static final int SESSIONS_ID_TRACKS = 406; private static final int SPEAKERS = 500; private static final int SPEAKERS_ID = 501; private static final int SPEAKERS_ID_SESSIONS = 502; private static final int VENDORS = 600; private static final int VENDORS_STARRED = 601; private static final int VENDORS_SEARCH = 603; private static final int VENDORS_ID = 604; private static final int SEARCH_SUGGEST = 800; private static final String MIME_XML = "text/xml"; /** * Build and return a {@link UriMatcher} that catches all {@link Uri} * variations supported by this {@link ContentProvider}. */ private static UriMatcher buildUriMatcher() { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = ScheduleContract.CONTENT_AUTHORITY; matcher.addURI(authority, "blocks", BLOCKS); matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN); matcher.addURI(authority, "blocks/*", BLOCKS_ID); matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS); matcher.addURI(authority, "tracks", TRACKS); matcher.addURI(authority, "tracks/*", TRACKS_ID); matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS); matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS); matcher.addURI(authority, "rooms", ROOMS); matcher.addURI(authority, "rooms/*", ROOMS_ID); matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS); matcher.addURI(authority, "sessions", SESSIONS); matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED); matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH); matcher.addURI(authority, "sessions/at/*", SESSIONS_AT); matcher.addURI(authority, "sessions/*", SESSIONS_ID); matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS); matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS); matcher.addURI(authority, "speakers", SPEAKERS); matcher.addURI(authority, "speakers/*", SPEAKERS_ID); matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS); matcher.addURI(authority, "vendors", VENDORS); matcher.addURI(authority, "vendors/starred", VENDORS_STARRED); matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH); matcher.addURI(authority, "vendors/*", VENDORS_ID); matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST); return matcher; } @Override public boolean onCreate() { final Context context = getContext(); mOpenHelper = new ScheduleDatabase(context); return true; } /** {@inheritDoc} */ @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: return Blocks.CONTENT_TYPE; case BLOCKS_BETWEEN: return Blocks.CONTENT_TYPE; case BLOCKS_ID: return Blocks.CONTENT_ITEM_TYPE; case BLOCKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS: return Tracks.CONTENT_TYPE; case TRACKS_ID: return Tracks.CONTENT_ITEM_TYPE; case TRACKS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case TRACKS_ID_VENDORS: return Vendors.CONTENT_TYPE; case ROOMS: return Rooms.CONTENT_TYPE; case ROOMS_ID: return Rooms.CONTENT_ITEM_TYPE; case ROOMS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS: return Sessions.CONTENT_TYPE; case SESSIONS_STARRED: return Sessions.CONTENT_TYPE; case SESSIONS_SEARCH: return Sessions.CONTENT_TYPE; case SESSIONS_AT: return Sessions.CONTENT_TYPE; case SESSIONS_ID: return Sessions.CONTENT_ITEM_TYPE; case SESSIONS_ID_SPEAKERS: return Speakers.CONTENT_TYPE; case SESSIONS_ID_TRACKS: return Tracks.CONTENT_TYPE; case SPEAKERS: return Speakers.CONTENT_TYPE; case SPEAKERS_ID: return Speakers.CONTENT_ITEM_TYPE; case SPEAKERS_ID_SESSIONS: return Sessions.CONTENT_TYPE; case VENDORS: return Vendors.CONTENT_TYPE; case VENDORS_STARRED: return Vendors.CONTENT_TYPE; case VENDORS_SEARCH: return Vendors.CONTENT_TYPE; case VENDORS_ID: return Vendors.CONTENT_ITEM_TYPE; default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } /** {@inheritDoc} */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (LOGV) Log.v(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); final SQLiteDatabase db = mOpenHelper.getReadableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { default: { // Most cases are handled with simple SelectionBuilder final SelectionBuilder builder = buildExpandedSelection(uri, match); return builder.where(selection, selectionArgs).query(db, projection, sortOrder); } case SEARCH_SUGGEST: { final SelectionBuilder builder = new SelectionBuilder(); // Adjust incoming query to become SQL text match selectionArgs[0] = selectionArgs[0] + "%"; builder.table(Tables.SEARCH_SUGGEST); builder.where(selection, selectionArgs); builder.map(SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_TEXT_1); projection = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_QUERY }; final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT); return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit); } } } /** {@inheritDoc} */ @Override public Uri insert(Uri uri, ContentValues values) { if (LOGV) Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { db.insertOrThrow(Tables.BLOCKS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID)); } case TRACKS: { db.insertOrThrow(Tables.TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID)); } case ROOMS: { db.insertOrThrow(Tables.ROOMS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID)); } case SESSIONS: { db.insertOrThrow(Tables.SESSIONS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID)); } case SESSIONS_ID_SPEAKERS: { db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID)); } case SESSIONS_ID_TRACKS: { db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID)); } case SPEAKERS: { db.insertOrThrow(Tables.SPEAKERS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID)); } case VENDORS: { db.insertOrThrow(Tables.VENDORS, null, values); getContext().getContentResolver().notifyChange(uri, null); return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID)); } case SEARCH_SUGGEST: { db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values); getContext().getContentResolver().notifyChange(uri, null); return SearchSuggest.CONTENT_URI; } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** {@inheritDoc} */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).update(db, values); getContext().getContentResolver().notifyChange(uri, null); return retVal; } /** {@inheritDoc} */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { if (LOGV) Log.v(TAG, "delete(uri=" + uri + ")"); final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final SelectionBuilder builder = buildSimpleSelection(uri); int retVal = builder.where(selection, selectionArgs).delete(db); getContext().getContentResolver().notifyChange(uri, null); return retVal; } /** * Apply the given set of {@link ContentProviderOperation}, executing inside * a {@link SQLiteDatabase} transaction. All changes will be rolled back if * any single one fails. */ @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); db.beginTransaction(); try { final int numOperations = operations.size(); final ContentProviderResult[] results = new ContentProviderResult[numOperations]; for (int i = 0; i < numOperations; i++) { results[i] = operations.get(i).apply(this, results, i); } db.setTransactionSuccessful(); return results; } finally { db.endTransaction(); } } /** * Build a simple {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually enough to support {@link #insert}, * {@link #update}, and {@link #delete} operations. */ private SelectionBuilder buildSimpleSelection(Uri uri) { final SelectionBuilder builder = new SelectionBuilder(); final int match = sUriMatcher.match(uri); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .where(Blocks.BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS) .where(Sessions.SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } case SEARCH_SUGGEST: { return builder.table(Tables.SEARCH_SUGGEST); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } /** * Build an advanced {@link SelectionBuilder} to match the requested * {@link Uri}. This is usually only used by {@link #query}, since it * performs table joins useful for {@link Cursor} data. */ private SelectionBuilder buildExpandedSelection(Uri uri, int match) { final SelectionBuilder builder = new SelectionBuilder(); switch (match) { case BLOCKS: { return builder.table(Tables.BLOCKS); } case BLOCKS_BETWEEN: { final List<String> segments = uri.getPathSegments(); final String startTime = segments.get(2); final String endTime = segments.get(3); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_START + ">=?", startTime) .where(Blocks.BLOCK_START + "<=?", endTime); } case BLOCKS_ID: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.BLOCKS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .where(Blocks.BLOCK_ID + "=?", blockId); } case BLOCKS_ID_SESSIONS: { final String blockId = Blocks.getBlockId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT) .map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId); } case TRACKS: { return builder.table(Tables.TRACKS) .map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT) .map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT); } case TRACKS_ID: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.TRACKS) .where(Tracks.TRACK_ID + "=?", trackId); } case TRACKS_ID_SESSIONS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId); } case TRACKS_ID_VENDORS: { final String trackId = Tracks.getTrackId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Qualified.VENDORS_TRACK_ID + "=?", trackId); } case ROOMS: { return builder.table(Tables.ROOMS); } case ROOMS_ID: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.ROOMS) .where(Rooms.ROOM_ID + "=?", roomId); } case ROOMS_ID_SESSIONS: { final String roomId = Rooms.getRoomId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_ROOM_ID + "=?", roomId); } case SESSIONS: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS); } case SESSIONS_STARRED: { return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.SESSION_STARRED + "=1"); } case SESSIONS_SEARCH: { final String query = Sessions.getSearchQuery(uri); return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS) .map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(SessionsSearchColumns.BODY + " MATCH ?", query); } case SESSIONS_AT: { final List<String> segments = uri.getPathSegments(); final String time = segments.get(2); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Sessions.BLOCK_START + "<=?", time) .where(Sessions.BLOCK_END + ">=?", time); } case SESSIONS_ID: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_SPEAKERS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS) .mapToTable(Speakers._ID, Tables.SPEAKERS) .mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS) .where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId); } case SESSIONS_ID_TRACKS: { final String sessionId = Sessions.getSessionId(uri); return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS) .mapToTable(Tracks._ID, Tables.TRACKS) .mapToTable(Tracks.TRACK_ID, Tables.TRACKS) .where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId); } case SPEAKERS: { return builder.table(Tables.SPEAKERS); } case SPEAKERS_ID: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SPEAKERS) .where(Speakers.SPEAKER_ID + "=?", speakerId); } case SPEAKERS_ID_SESSIONS: { final String speakerId = Speakers.getSpeakerId(uri); return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS) .mapToTable(Sessions._ID, Tables.SESSIONS) .mapToTable(Sessions.SESSION_ID, Tables.SESSIONS) .mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS) .mapToTable(Sessions.ROOM_ID, Tables.SESSIONS) .where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId); } case VENDORS: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS); } case VENDORS_STARRED: { return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_STARRED + "=1"); } case VENDORS_SEARCH: { final String query = Vendors.getSearchQuery(uri); return builder.table(Tables.VENDORS_SEARCH_JOIN_VENDORS_TRACKS) .map(Vendors.SEARCH_SNIPPET, Subquery.VENDORS_SNIPPET) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.VENDOR_ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(VendorsSearchColumns.BODY + " MATCH ?", query); } case VENDORS_ID: { final String vendorId = Vendors.getVendorId(uri); return builder.table(Tables.VENDORS_JOIN_TRACKS) .mapToTable(Vendors._ID, Tables.VENDORS) .mapToTable(Vendors.TRACK_ID, Tables.VENDORS) .where(Vendors.VENDOR_ID + "=?", vendorId); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { final int match = sUriMatcher.match(uri); switch (match) { default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } private interface Subquery { String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String BLOCK_CONTAINS_STARRED = "(SELECT MAX(" + Qualified.SESSIONS_STARRED + ") FROM " + Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "=" + Qualified.BLOCKS_BLOCK_ID + ")"; String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID + ") FROM " + Tables.SESSIONS_TRACKS + " WHERE " + Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM " + Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")"; String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')"; String VENDORS_SNIPPET = "snippet(" + Tables.VENDORS_SEARCH + ",'{','}','\u2026')"; } /** * {@link ScheduleContract} fields that are fully qualified with a specific * parent {@link Tables}. Used when needed to work around SQL ambiguity. */ private interface Qualified { String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID; String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID; String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID; String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.SESSION_ID; String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "." + SessionsTracks.TRACK_ID; String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SESSION_ID; String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "." + SessionsSpeakers.SPEAKER_ID; String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID; String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID; @SuppressWarnings("hiding") String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED; String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID; String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID; } }
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.provider; import com.google.android.apps.iosched.util.ParserUtils; import android.app.SearchManager; import android.graphics.Color; import android.net.Uri; import android.provider.BaseColumns; import android.text.format.DateUtils; import java.util.List; /** * Contract class for interacting with {@link ScheduleProvider}. Unless * otherwise noted, all time-based fields are milliseconds since epoch and can * be compared against {@link System#currentTimeMillis()}. * <p> * The backing {@link android.content.ContentProvider} assumes that {@link Uri} are generated * using stronger {@link String} identifiers, instead of {@code int} * {@link BaseColumns#_ID} values, which are prone to shuffle during sync. */ public class ScheduleContract { /** * Special value for {@link SyncColumns#UPDATED} indicating that an entry * has never been updated, or doesn't exist yet. */ public static final long UPDATED_NEVER = -2; /** * Special value for {@link SyncColumns#UPDATED} indicating that the last * update time is unknown, usually when inserted from a local file source. */ public static final long UPDATED_UNKNOWN = -1; public interface SyncColumns { /** Last time this entry was updated or synchronized. */ String UPDATED = "updated"; } interface BlocksColumns { /** Unique string identifying this block of time. */ String BLOCK_ID = "block_id"; /** Title describing this block of time. */ String BLOCK_TITLE = "block_title"; /** Time when this block starts. */ String BLOCK_START = "block_start"; /** Time when this block ends. */ String BLOCK_END = "block_end"; /** Type describing this block. */ String BLOCK_TYPE = "block_type"; } interface TracksColumns { /** Unique string identifying this track. */ String TRACK_ID = "track_id"; /** Name describing this track. */ String TRACK_NAME = "track_name"; /** Color used to identify this track, in {@link Color#argb} format. */ String TRACK_COLOR = "track_color"; /** Body of text explaining this track in detail. */ String TRACK_ABSTRACT = "track_abstract"; } interface RoomsColumns { /** Unique string identifying this room. */ String ROOM_ID = "room_id"; /** Name describing this room. */ String ROOM_NAME = "room_name"; /** Building floor this room exists on. */ String ROOM_FLOOR = "room_floor"; } interface SessionsColumns { /** Unique string identifying this session. */ String SESSION_ID = "session_id"; /** Difficulty level of the session. */ String SESSION_LEVEL = "session_level"; /** Title describing this track. */ String SESSION_TITLE = "session_title"; /** Body of text explaining this session in detail. */ String SESSION_ABSTRACT = "session_abstract"; /** Requirements that attendees should meet. */ String SESSION_REQUIREMENTS = "session_requirements"; /** Kewords/tags for this session. */ String SESSION_KEYWORDS = "session_keywords"; /** Hashtag for this session. */ String SESSION_HASHTAG = "session_hashtag"; /** Slug (short name) for this session. */ String SESSION_SLUG = "session_slug"; /** Full URL to session online. */ String SESSION_URL = "session_url"; /** Link to Moderator for this session. */ String SESSION_MODERATOR_URL = "session_moderator_url"; /** Full URL to YouTube. */ String SESSION_YOUTUBE_URL = "session_youtube_url"; /** Full URL to PDF. */ String SESSION_PDF_URL = "session_pdf_url"; /** Full URL to speakermeter/external feedback URL. */ String SESSION_FEEDBACK_URL = "session_feedback_url"; /** Full URL to official session notes. */ String SESSION_NOTES_URL = "session_notes_url"; /** User-specific flag indicating starred status. */ String SESSION_STARRED = "session_starred"; } interface SpeakersColumns { /** Unique string identifying this speaker. */ String SPEAKER_ID = "speaker_id"; /** Name of this speaker. */ String SPEAKER_NAME = "speaker_name"; /** Profile photo of this speaker. */ String SPEAKER_IMAGE_URL = "speaker_image_url"; /** Company this speaker works for. */ String SPEAKER_COMPANY = "speaker_company"; /** Body of text describing this speaker in detail. */ String SPEAKER_ABSTRACT = "speaker_abstract"; /** Full URL to the speaker's profile. */ String SPEAKER_URL = "speaker_url"; } interface VendorsColumns { /** Unique string identifying this vendor. */ String VENDOR_ID = "vendor_id"; /** Name of this vendor. */ String VENDOR_NAME = "vendor_name"; /** Location or city this vendor is based in. */ String VENDOR_LOCATION = "vendor_location"; /** Body of text describing this vendor. */ String VENDOR_DESC = "vendor_desc"; /** Link to vendor online. */ String VENDOR_URL = "vendor_url"; /** Body of text describing the product of this vendor. */ String VENDOR_PRODUCT_DESC = "vendor_product_desc"; /** Link to vendor logo. */ String VENDOR_LOGO_URL = "vendor_logo_url"; /** User-specific flag indicating starred status. */ String VENDOR_STARRED = "vendor_starred"; } public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched"; private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); private static final String PATH_BLOCKS = "blocks"; private static final String PATH_AT = "at"; private static final String PATH_BETWEEN = "between"; private static final String PATH_TRACKS = "tracks"; private static final String PATH_ROOMS = "rooms"; private static final String PATH_SESSIONS = "sessions"; private static final String PATH_STARRED = "starred"; private static final String PATH_SPEAKERS = "speakers"; private static final String PATH_VENDORS = "vendors"; private static final String PATH_EXPORT = "export"; private static final String PATH_SEARCH = "search"; private static final String PATH_SEARCH_SUGGEST = "search_suggest_query"; /** * Blocks are generic timeslots that {@link Sessions} and other related * events fall into. */ public static class Blocks implements BlocksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.block"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.block"; /** Count of {@link Sessions} inside given block. */ public static final String SESSIONS_COUNT = "sessions_count"; /** * Flag indicating that at least one {@link Sessions#SESSION_ID} inside * this block has {@link Sessions#SESSION_STARRED} set. */ public static final String CONTAINS_STARRED = "contains_starred"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, " + BlocksColumns.BLOCK_END + " ASC"; /** Build {@link Uri} for requested {@link #BLOCK_ID}. */ public static Uri buildBlockUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #BLOCK_ID}. */ public static Uri buildSessionsUri(String blockId) { return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references any {@link Blocks} that occur * between the requested time boundaries. */ public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) { return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath( String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build(); } /** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */ public static String getBlockId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #BLOCK_ID} that will always match the requested * {@link Blocks} details. */ public static String generateBlockId(long startTime, long endTime) { startTime /= DateUtils.SECOND_IN_MILLIS; endTime /= DateUtils.SECOND_IN_MILLIS; return ParserUtils.sanitizeId(startTime + "-" + endTime); } } /** * Tracks are overall categories for {@link Sessions} and {@link Vendors}, * such as "Android" or "Enterprise." */ public static class Tracks implements TracksColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.track"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.track"; /** Count of {@link Sessions} inside given track. */ public static final String SESSIONS_COUNT = "sessions_count"; /** Count of {@link Vendors} inside given track. */ public static final String VENDORS_COUNT = "vendors_count"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + " ASC"; /** "All tracks" ID. */ public static final String ALL_TRACK_ID = "all"; /** Build {@link Uri} for requested {@link #TRACK_ID}. */ public static Uri buildTrackUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #TRACK_ID}. */ public static Uri buildSessionsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build(); } /** * Build {@link Uri} that references any {@link Vendors} associated with * the requested {@link #TRACK_ID}. */ public static Uri buildVendorsUri(String trackId) { return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build(); } /** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */ public static String getTrackId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #TRACK_ID} that will always match the requested * {@link Tracks} details. */ public static String generateTrackId(String title) { return ParserUtils.sanitizeId(title); } } /** * Rooms are physical locations at the conference venue. */ public static class Rooms implements RoomsColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.room"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.room"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, " + RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #ROOM_ID}. */ public static Uri buildRoomUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #ROOM_ID}. */ public static Uri buildSessionsDirUri(String roomId) { return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */ public static String getRoomId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #ROOM_ID} that will always match the requested * {@link Rooms} details. */ public static String generateRoomId(String room) { return ParserUtils.sanitizeId(room); } } /** * Each session is a block of time that has a {@link Tracks}, a * {@link Rooms}, and zero or more {@link Speakers}. */ public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build(); public static final Uri CONTENT_STARRED_URI = CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.session"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.session"; public static final String BLOCK_ID = "block_id"; public static final String ROOM_ID = "room_id"; public static final String SEARCH_SNIPPET = "search_snippet"; // TODO: shortcut primary track to offer sub-sorting here /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC," + SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #SESSION_ID}. */ public static Uri buildSessionUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).build(); } /** * Build {@link Uri} that references any {@link Speakers} associated * with the requested {@link #SESSION_ID}. */ public static Uri buildSpeakersDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build(); } /** * Build {@link Uri} that references any {@link Tracks} associated with * the requested {@link #SESSION_ID}. */ public static Uri buildTracksDirUri(String sessionId) { return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build(); } public static Uri buildSessionsAtDirUri(long time) { return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time)) .build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */ public static String getSessionId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } /** * Generate a {@link #SESSION_ID} that will always match the requested * {@link Sessions} details. */ public static String generateSessionId(String title) { return ParserUtils.sanitizeId(title); } } /** * Speakers are individual people that lead {@link Sessions}. */ public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.speaker"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.speaker"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #SPEAKER_ID}. */ public static Uri buildSpeakerUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).build(); } /** * Build {@link Uri} that references any {@link Sessions} associated * with the requested {@link #SPEAKER_ID}. */ public static Uri buildSessionsDirUri(String speakerId) { return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build(); } /** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */ public static String getSpeakerId(Uri uri) { return uri.getPathSegments().get(1); } /** * Generate a {@link #SPEAKER_ID} that will always match the requested * {@link Speakers} details. */ public static String generateSpeakerId(String speakerLdap) { return ParserUtils.sanitizeId(speakerLdap); } } /** * Each vendor is a company appearing at the conference that may be * associated with a specific {@link Tracks}. */ public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build(); public static final Uri CONTENT_STARRED_URI = CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build(); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.vendor"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.vendor"; /** {@link Tracks#TRACK_ID} that this vendor belongs to. */ public static final String TRACK_ID = "track_id"; public static final String SEARCH_SNIPPET = "search_snippet"; /** Default "ORDER BY" clause. */ public static final String DEFAULT_SORT = VendorsColumns.VENDOR_NAME + " COLLATE NOCASE ASC"; /** Build {@link Uri} for requested {@link #VENDOR_ID}. */ public static Uri buildVendorUri(String vendorId) { return CONTENT_URI.buildUpon().appendPath(vendorId).build(); } public static Uri buildSearchUri(String query) { return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build(); } public static boolean isSearchUri(Uri uri) { List<String> pathSegments = uri.getPathSegments(); return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1)); } /** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */ public static String getVendorId(Uri uri) { return uri.getPathSegments().get(1); } public static String getSearchQuery(Uri uri) { return uri.getPathSegments().get(2); } /** * Generate a {@link #VENDOR_ID} that will always match the requested * {@link Vendors} details. */ public static String generateVendorId(String companyLogo) { return ParserUtils.sanitizeId(companyLogo); } } public static class SearchSuggest { public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build(); public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1 + " COLLATE NOCASE ASC"; } private ScheduleContract() { } }
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.service; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.io.LocalBlocksHandler; import com.google.android.apps.iosched.io.LocalExecutor; import com.google.android.apps.iosched.io.LocalRoomsHandler; import com.google.android.apps.iosched.io.LocalSearchSuggestHandler; import com.google.android.apps.iosched.io.LocalSessionsHandler; import com.google.android.apps.iosched.io.LocalTracksHandler; import com.google.android.apps.iosched.io.RemoteExecutor; import com.google.android.apps.iosched.io.RemoteSessionsHandler; import com.google.android.apps.iosched.io.RemoteSpeakersHandler; import com.google.android.apps.iosched.io.RemoteVendorsHandler; import com.google.android.apps.iosched.io.RemoteWorksheetsHandler; import com.google.android.apps.iosched.provider.ScheduleProvider; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.client.HttpClient; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HttpContext; import android.app.IntentService; import android.app.Service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.os.Bundle; import android.os.ResultReceiver; import android.text.format.DateUtils; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; /** * Background {@link Service} that synchronizes data living in * {@link ScheduleProvider}. Reads data from both local {@link Resources} and * from remote sources, such as a spreadsheet. */ public class SyncService extends IntentService { private static final String TAG = "SyncService"; public static final String EXTRA_STATUS_RECEIVER = "com.google.android.iosched.extra.STATUS_RECEIVER"; public static final int STATUS_RUNNING = 0x1; public static final int STATUS_ERROR = 0x2; public static final int STATUS_FINISHED = 0x3; private static final int SECOND_IN_MILLIS = (int) DateUtils.SECOND_IN_MILLIS; /** Root worksheet feed for online data source */ // TODO: insert your sessions/speakers/vendors spreadsheet doc URL here. private static final String WORKSHEETS_URL = "INSERT_SPREADSHEET_URL_HERE"; private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; private static final String ENCODING_GZIP = "gzip"; private static final int VERSION_NONE = 0; private static final int VERSION_CURRENT = 11; private LocalExecutor mLocalExecutor; private RemoteExecutor mRemoteExecutor; public SyncService() { super(TAG); } @Override public void onCreate() { super.onCreate(); final HttpClient httpClient = getHttpClient(this); final ContentResolver resolver = getContentResolver(); mLocalExecutor = new LocalExecutor(getResources(), resolver); mRemoteExecutor = new RemoteExecutor(httpClient, resolver); } @Override protected void onHandleIntent(Intent intent) { Log.d(TAG, "onHandleIntent(intent=" + intent.toString() + ")"); final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER); if (receiver != null) receiver.send(STATUS_RUNNING, Bundle.EMPTY); final Context context = this; final SharedPreferences prefs = getSharedPreferences(Prefs.IOSCHED_SYNC, Context.MODE_PRIVATE); final int localVersion = prefs.getInt(Prefs.LOCAL_VERSION, VERSION_NONE); try { // Bulk of sync work, performed by executing several fetches from // local and online sources. final long startLocal = System.currentTimeMillis(); final boolean localParse = localVersion < VERSION_CURRENT; Log.d(TAG, "found localVersion=" + localVersion + " and VERSION_CURRENT=" + VERSION_CURRENT); if (localParse) { // Load static local data mLocalExecutor.execute(R.xml.blocks, new LocalBlocksHandler()); mLocalExecutor.execute(R.xml.rooms, new LocalRoomsHandler()); mLocalExecutor.execute(R.xml.tracks, new LocalTracksHandler()); mLocalExecutor.execute(R.xml.search_suggest, new LocalSearchSuggestHandler()); mLocalExecutor.execute(R.xml.sessions, new LocalSessionsHandler()); // Parse values from local cache first, since spreadsheet copy // or network might be down. mLocalExecutor.execute(context, "cache-sessions.xml", new RemoteSessionsHandler()); mLocalExecutor.execute(context, "cache-speakers.xml", new RemoteSpeakersHandler()); mLocalExecutor.execute(context, "cache-vendors.xml", new RemoteVendorsHandler()); // Save local parsed version prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit(); } Log.d(TAG, "local sync took " + (System.currentTimeMillis() - startLocal) + "ms"); // Always hit remote spreadsheet for any updates final long startRemote = System.currentTimeMillis(); mRemoteExecutor .executeGet(WORKSHEETS_URL, new RemoteWorksheetsHandler(mRemoteExecutor)); Log.d(TAG, "remote sync took " + (System.currentTimeMillis() - startRemote) + "ms"); } catch (Exception e) { Log.e(TAG, "Problem while syncing", e); if (receiver != null) { // Pass back error to surface listener final Bundle bundle = new Bundle(); bundle.putString(Intent.EXTRA_TEXT, e.toString()); receiver.send(STATUS_ERROR, bundle); } } // Announce success to any surface listener Log.d(TAG, "sync finished"); if (receiver != null) receiver.send(STATUS_FINISHED, Bundle.EMPTY); } /** * Generate and return a {@link HttpClient} configured for general use, * including setting an application-specific user-agent string. */ public static HttpClient getHttpClient(Context context) { final HttpParams params = new BasicHttpParams(); // Use generous timeouts for slow mobile networks HttpConnectionParams.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS); HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpProtocolParams.setUserAgent(params, buildUserAgent(context)); final DefaultHttpClient client = new DefaultHttpClient(params); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { // Add header to accept gzip content if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, HttpContext context) { // Inflate any responses compressed with gzip final HttpEntity entity = response.getEntity(); final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); return client; } /** * Build and return a user-agent string that can identify this application * to remote servers. Contains the package name and version code. */ private static String buildUserAgent(Context context) { try { final PackageManager manager = context.getPackageManager(); final PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); // Some APIs require "(gzip)" in the user-agent string. return info.packageName + "/" + info.versionName + " (" + info.versionCode + ") (gzip)"; } catch (NameNotFoundException e) { return null; } } /** * Simple {@link HttpEntityWrapper} that inflates the wrapped * {@link HttpEntity} by passing it through {@link GZIPInputStream}. */ private static class InflatingEntity extends HttpEntityWrapper { public InflatingEntity(HttpEntity wrapped) { super(wrapped); } @Override public InputStream getContent() throws IOException { return new GZIPInputStream(wrappedEntity.getContent()); } @Override public long getContentLength() { return -1; } } private interface Prefs { String IOSCHED_SYNC = "iosched_sync"; String LOCAL_VERSION = "local_version"; } }
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 com.google.android.apps.iosched.service.SyncService; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.util.EntityUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Environment; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Helper class for fetching and disk-caching images from the web. */ public class BitmapUtils { private static final String TAG = "BitmapUtils"; // TODO: for concurrent connections, DefaultHttpClient isn't great, consider other options // that still allow for sharing resources across bitmap fetches. public static interface OnFetchCompleteListener { public void onFetchComplete(Object cookie, Bitmap result); } /** * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}. */ public static void fetchImage(final Context context, final String url, final OnFetchCompleteListener callback) { fetchImage(context, url, null, null, callback); } /** * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}. * * @param cookie An arbitrary object that will be passed to the callback. */ public static void fetchImage(final Context context, final String url, final BitmapFactory.Options decodeOptions, final Object cookie, final OnFetchCompleteListener callback) { new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { final String url = params[0]; if (TextUtils.isEmpty(url)) { return null; } // First compute the cache key and cache file path for this URL File cacheFile = null; try { MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); mDigest.update(url.getBytes()); final String cacheKey = bytesToHexString(mDigest.digest()); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { cacheFile = new File( Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + context.getPackageName() + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp"); } } catch (NoSuchAlgorithmException e) { // Oh well, SHA-1 not available (weird), don't cache bitmaps. } if (cacheFile != null && cacheFile.exists()) { Bitmap cachedBitmap = BitmapFactory.decodeFile( cacheFile.toString(), decodeOptions); if (cachedBitmap != null) { return cachedBitmap; } } try { // TODO: check for HTTP caching headers final HttpClient httpClient = SyncService.getHttpClient( context.getApplicationContext()); final HttpResponse resp = httpClient.execute(new HttpGet(url)); final HttpEntity entity = resp.getEntity(); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK || entity == null) { return null; } final byte[] respBytes = EntityUtils.toByteArray(entity); // Write response bytes to cache. if (cacheFile != null) { try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } } // Decode the bytes and return the bitmap. return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions); } catch (Exception e) { Log.w(TAG, "Problem while loading image: " + e.toString(), e); } return null; } @Override protected void onPostExecute(Bitmap result) { callback.onFetchComplete(cookie, result); } }.execute(url); } private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } }
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 android.graphics.Rect; import android.graphics.RectF; import android.view.MotionEvent; import android.view.TouchDelegate; import android.view.View; /** * {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing * then against fractional dimensions of the source view. * <p> * This is particularly useful when you want to define a rectangle in terms of * the source dimensions, but when those dimensions might change due to pending * or future layout passes. * <p> * One example is catching touches that occur in the top-right quadrant of * {@code sourceParent}, and relaying them to {@code targetChild}. This could be * done with: <code> * FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f)); * </code> */ public class FractionalTouchDelegate extends TouchDelegate { private View mSource; private View mTarget; private RectF mSourceFraction; private Rect mScrap = new Rect(); /** Cached full dimensions of {@link #mSource}. */ private Rect mSourceFull = new Rect(); /** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */ private Rect mSourcePartial = new Rect(); private boolean mDelegateTargeted; public FractionalTouchDelegate(View source, View target, RectF sourceFraction) { super(new Rect(0, 0, 0, 0), target); mSource = source; mTarget = target; mSourceFraction = sourceFraction; } /** * Helper to create and setup a {@link FractionalTouchDelegate} between the * given {@link View}. * * @param source Larger source {@link View}, usually a parent, that will be * assigned {@link View#setTouchDelegate(TouchDelegate)}. * @param target Smaller target {@link View} which will receive * {@link MotionEvent} that land in requested fractional area. * @param sourceFraction Fractional area projected onto source {@link View} * which determines when {@link MotionEvent} will be passed to * target {@link View}. */ public static void setupDelegate(View source, View target, RectF sourceFraction) { source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction)); } /** * Consider updating {@link #mSourcePartial} when {@link #mSource} * dimensions have changed. */ private void updateSourcePartial() { mSource.getHitRect(mScrap); if (!mScrap.equals(mSourceFull)) { // Copy over and calculate fractional rectangle mSourceFull.set(mScrap); final int width = mSourceFull.width(); final int height = mSourceFull.height(); mSourcePartial.left = (int) (mSourceFraction.left * width); mSourcePartial.top = (int) (mSourceFraction.top * height); mSourcePartial.right = (int) (mSourceFraction.right * width); mSourcePartial.bottom = (int) (mSourceFraction.bottom * height); } } @Override public boolean onTouchEvent(MotionEvent event) { updateSourcePartial(); // The logic below is mostly copied from the parent class, since we // can't update private mBounds variable. // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob; // f=core/java/android/view/TouchDelegate.java;hb=eclair#l98 final Rect sourcePartial = mSourcePartial; final View target = mTarget; int x = (int)event.getX(); int y = (int)event.getY(); boolean sendToDelegate = false; boolean hit = true; boolean handled = false; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (sourcePartial.contains(x, y)) { mDelegateTargeted = true; sendToDelegate = true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_MOVE: sendToDelegate = mDelegateTargeted; if (sendToDelegate) { if (!sourcePartial.contains(x, y)) { hit = false; } } break; case MotionEvent.ACTION_CANCEL: sendToDelegate = mDelegateTargeted; mDelegateTargeted = false; break; } if (sendToDelegate) { if (hit) { event.setLocation(target.getWidth() / 2, target.getHeight() / 2); } else { event.setLocation(-1, -1); } handled = target.dispatchTouchEvent(event); } return handled; } }
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 java.io.IOException; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.CONTENT; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.UPDATED; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class SpreadsheetEntry extends HashMap<String, String> { private static final Pattern sContentPattern = Pattern.compile( "(?:^|, )([_a-zA-Z0-9]+): (.*?)(?=\\s*$|, [_a-zA-Z0-9]+: )", Pattern.DOTALL); private static Matcher sContentMatcher; private static Matcher getContentMatcher(CharSequence input) { if (sContentMatcher == null) { sContentMatcher = sContentPattern.matcher(input); } else { sContentMatcher.reset(input); } return sContentMatcher; } private long mUpdated; public long getUpdated() { return mUpdated; } public static SpreadsheetEntry fromParser(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final SpreadsheetEntry entry = new SpreadsheetEntry(); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { if (UPDATED.equals(tag)) { final String text = parser.getText(); entry.mUpdated = ParserUtils.parseTime(text); } else if (CONTENT.equals(tag)) { final String text = parser.getText(); final Matcher matcher = getContentMatcher(text); while (matcher.find()) { final String key = matcher.group(1); final String value = matcher.group(2).trim(); entry.put(key, value); } } } } return entry; } }
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.text.format.DateUtils; import java.io.IOException; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.HREF; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.LINK; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.REL; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.TITLE; import static com.google.android.apps.iosched.util.ParserUtils.AtomTags.UPDATED; import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; import static org.xmlpull.v1.XmlPullParser.END_TAG; import static org.xmlpull.v1.XmlPullParser.START_TAG; import static org.xmlpull.v1.XmlPullParser.TEXT; public class WorksheetEntry { private static final String REL_LISTFEED = "http://schemas.google.com/spreadsheets/2006#listfeed"; private long mUpdated; private String mTitle; private String mListFeed; public long getUpdated() { return mUpdated; } public String getTitle() { return mTitle; } public String getListFeed() { return mListFeed; } @Override public String toString() { return "title=" + mTitle + ", updated=" + mUpdated + " (" + DateUtils.getRelativeTimeSpanString(mUpdated) + ")"; } public static WorksheetEntry fromParser(XmlPullParser parser) throws XmlPullParserException, IOException { final int depth = parser.getDepth(); final WorksheetEntry entry = new WorksheetEntry(); String tag = null; int type; while (((type = parser.next()) != END_TAG || parser.getDepth() > depth) && type != END_DOCUMENT) { if (type == START_TAG) { tag = parser.getName(); if (LINK.equals(tag)) { final String rel = parser.getAttributeValue(null, REL); final String href = parser.getAttributeValue(null, HREF); if (REL_LISTFEED.equals(rel)) { entry.mListFeed = href; } } } else if (type == END_TAG) { tag = null; } else if (type == TEXT) { final String text = parser.getText(); if (TITLE.equals(tag)) { entry.mTitle = text; } else if (UPDATED.equals(tag)) { entry.mUpdated = ParserUtils.parseTime(text); } } } return entry; } }
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 java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.SortedSet; import java.util.TreeSet; /** * Provides static methods for creating mutable {@code Set} instances easily and * other static methods for working with Sets. * */ public class Sets { /** * Creates an empty {@code HashSet} instance. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link * EnumSet#noneOf} instead. * * <p><b>Note:</b> if you only need an <i>immutable</i> empty Set, * use {@link Collections#emptySet} instead. * * @return a newly-created, initially-empty {@code HashSet} */ public static <K> HashSet<K> newHashSet() { return new HashSet<K>(); } /** * Creates a {@code HashSet} instance containing the given elements. * * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the * following: * * <p>{@code Set<Base> set = Sets.newHashSet(sub1, sub2);} * * <p>where {@code sub1} and {@code sub2} are references to subtypes of {@code * Base}, not of {@code Base} itself. To get around this, you must use: * * <p>{@code Set<Base> set = Sets.<Base>newHashSet(sub1, sub2);} * * @param elements the elements that the set should contain * @return a newly-created {@code HashSet} containing those elements (minus * duplicates) */ public static <E> HashSet<E> newHashSet(E... elements) { int capacity = elements.length * 4 / 3 + 1; HashSet<E> set = new HashSet<E>(capacity); Collections.addAll(set, elements); return set; } /** * Creates a {@code SortedSet} instance containing the given elements. * * @param elements the elements that the set should contain * @return a newly-created {@code SortedSet} containing those elements (minus * duplicates) */ public static <E> SortedSet<E> newSortedSet(E... elements) { SortedSet<E> set = new TreeSet<E>(); Collections.addAll(set, elements); return set; } }
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 android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import java.util.ArrayList; /** * A <em>really</em> dumb implementation of the {@link Menu} interface, that's only useful for our * old-actionbar purposes. See <code>com.android.internal.view.menu.MenuBuilder</code> in AOSP for * a more complete implementation. */ public class SimpleMenu implements Menu { private Context mContext; private Resources mResources; private ArrayList<SimpleMenuItem> mItems; public SimpleMenu(Context context) { mContext = context; mResources = context.getResources(); mItems = new ArrayList<SimpleMenuItem>(); } public Context getContext() { return mContext; } public Resources getResources() { return mResources; } public MenuItem add(CharSequence title) { return addInternal(0, 0, title); } public MenuItem add(int titleRes) { return addInternal(0, 0, mResources.getString(titleRes)); } public MenuItem add(int groupId, int itemId, int order, CharSequence title) { return addInternal(itemId, order, title); } public MenuItem add(int groupId, int itemId, int order, int titleRes) { return addInternal(itemId, order, mResources.getString(titleRes)); } /** * Adds an item to the menu. The other add methods funnel to this. */ private MenuItem addInternal(int itemId, int order, CharSequence title) { final SimpleMenuItem item = new SimpleMenuItem(this, itemId, order, title); mItems.add(findInsertIndex(mItems, order), item); return item; } private static int findInsertIndex(ArrayList<? extends MenuItem> items, int order) { for (int i = items.size() - 1; i >= 0; i--) { MenuItem item = items.get(i); if (item.getOrder() <= order) { return i + 1; } } return 0; } public int findItemIndex(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return i; } } return -1; } public void removeItem(int itemId) { removeItemAtInt(findItemIndex(itemId)); } private void removeItemAtInt(int index) { if ((index < 0) || (index >= mItems.size())) { return; } mItems.remove(index); } public void clear() { mItems.clear(); } public MenuItem findItem(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return item; } } return null; } public int size() { return mItems.size(); } public MenuItem getItem(int index) { return mItems.get(index); } // Unsupported operations. public SubMenu addSubMenu(CharSequence charSequence) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public int addIntentOptions(int i, int i1, int i2, ComponentName componentName, Intent[] intents, Intent intent, int i3, MenuItem[] menuItems) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void removeGroup(int i) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupCheckable(int i, boolean b, boolean b1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupVisible(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupEnabled(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean hasVisibleItems() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void close() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performShortcut(int i, KeyEvent keyEvent, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean isShortcutKey(int i, KeyEvent keyEvent) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performIdentifierAction(int i, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setQwertyMode(boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * 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 java.util.ArrayList; import java.util.Collections; /** * Provides static methods for creating {@code List} instances easily, and other * utility methods for working with lists. */ public class Lists { /** * Creates an empty {@code ArrayList} instance. * * <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use * {@link Collections#emptyList} instead. * * @return a newly-created, initially-empty {@code ArrayList} */ public static <E> ArrayList<E> newArrayList() { return new ArrayList<E>(); } /** * Creates a resizable {@code ArrayList} instance containing the given * elements. * * <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the * following: * * <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);} * * <p>where {@code sub1} and {@code sub2} are references to subtypes of * {@code Base}, not of {@code Base} itself. To get around this, you must * use: * * <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);} * * @param elements the elements that the list should contain, in order * @return a newly-created {@code ArrayList} containing those elements */ public static <E> ArrayList<E> newArrayList(E... elements) { int capacity = (elements.length * 110) / 100 + 5; ArrayList<E> list = new ArrayList<E>(capacity); Collections.addAll(list, elements); return list; } }
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 com.google.android.apps.iosched.R; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; /** * Helper class for the Catch Notes integration, based on example code at * {@link https://github.com/catch/docs-api/}. */ public class CatchNotesHelper { private static final String TAG = "CatchNotesHelper"; // Intent actions public static final String ACTION_ADD = "com.catchnotes.intent.action.ADD"; public static final String ACTION_VIEW = "com.catchnotes.intent.action.VIEW"; // Intent extras for ACTION_ADD public static final String EXTRA_SOURCE = "com.catchnotes.intent.extra.SOURCE"; public static final String EXTRA_SOURCE_URL = "com.catchnotes.intent.extra.SOURCE_URL"; // Intent extras for ACTION_VIEW public static final String EXTRA_VIEW_FILTER = "com.catchnotes.intent.extra.VIEW_FILTER"; // Note: "3banana" was the original name of Catch Notes. Though it has been // rebranded, the package name must persist. private static final String NOTES_PACKAGE_NAME = "com.threebanana.notes"; private static final String NOTES_MARKET_URI = "http://market.android.com/details?id=" + NOTES_PACKAGE_NAME; private static final int NOTES_MIN_VERSION_CODE = 54; private final Context mContext; public CatchNotesHelper(Context context) { mContext = context; } public Intent createNoteIntent(String message) { if (!isNotesInstalledAndMinimumVersion()) { return notesMarketIntent(); } Intent intent = new Intent(); intent.setAction(ACTION_ADD); intent.putExtra(Intent.EXTRA_TEXT, message); intent.putExtra(EXTRA_SOURCE, mContext.getString(R.string.app_name)); intent.putExtra(EXTRA_SOURCE_URL, "http://www.google.com/io/"); intent.putExtra(Intent.EXTRA_TITLE, mContext.getString(R.string.app_name)); return intent; } public Intent viewNotesIntent(String tag) { if (!isNotesInstalledAndMinimumVersion()) { return notesMarketIntent(); } if (!tag.startsWith("#")) { tag = "#" + tag; } Intent intent = new Intent(); intent.setAction(ACTION_VIEW); intent.putExtra(EXTRA_VIEW_FILTER, tag); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } /** * Returns the installation status of Catch Notes. */ public boolean isNotesInstalledAndMinimumVersion() { try { PackageInfo packageInfo = mContext.getPackageManager() .getPackageInfo(NOTES_PACKAGE_NAME, PackageManager.GET_ACTIVITIES); if (packageInfo.versionCode < NOTES_MIN_VERSION_CODE) { return false; } } catch (NameNotFoundException e) { return false; } return true; } public Intent notesMarketIntent() { Uri uri = Uri.parse(NOTES_MARKET_URI); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); return intent; } }
Java
/* * Copyright (C) 2011 The Android Open Source Project * * 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. */ /* * Modifications: * -Imported from AOSP frameworks/base/core/java/com/android/internal/content * -Changed package name */ package com.google.android.apps.iosched.util; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Log; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; /** * Helper for building selection clauses for {@link SQLiteDatabase}. Each * appended clause is combined using {@code AND}. This class is <em>not</em> * thread safe. */ public class SelectionBuilder { private static final String TAG = "SelectionBuilder"; private static final boolean LOGV = false; private String mTable = null; private Map<String, String> mProjectionMap = Maps.newHashMap(); private StringBuilder mSelection = new StringBuilder(); private ArrayList<String> mSelectionArgs = Lists.newArrayList(); /** * Reset any internal state, allowing this builder to be recycled. */ public SelectionBuilder reset() { mTable = null; mSelection.setLength(0); mSelectionArgs.clear(); return this; } /** * Append the given selection clause to the internal state. Each clause is * surrounded with parenthesis and combined using {@code AND}. */ public SelectionBuilder where(String selection, String... selectionArgs) { if (TextUtils.isEmpty(selection)) { if (selectionArgs != null && selectionArgs.length > 0) { throw new IllegalArgumentException( "Valid selection required when including arguments="); } // Shortcut when clause is empty return this; } if (mSelection.length() > 0) { mSelection.append(" AND "); } mSelection.append("(").append(selection).append(")"); if (selectionArgs != null) { for (String arg : selectionArgs) { mSelectionArgs.add(arg); } } return this; } public SelectionBuilder table(String table) { mTable = table; return this; } private void assertTable() { if (mTable == null) { throw new IllegalStateException("Table not specified"); } } public SelectionBuilder mapToTable(String column, String table) { mProjectionMap.put(column, table + "." + column); return this; } public SelectionBuilder map(String fromColumn, String toClause) { mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn); return this; } /** * Return selection string for current internal state. * * @see #getSelectionArgs() */ public String getSelection() { return mSelection.toString(); } /** * Return selection arguments for current internal state. * * @see #getSelection() */ public String[] getSelectionArgs() { return mSelectionArgs.toArray(new String[mSelectionArgs.size()]); } private void mapColumns(String[] columns) { for (int i = 0; i < columns.length; i++) { final String target = mProjectionMap.get(columns[i]); if (target != null) { columns[i] = target; } } } @Override public String toString() { return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection() + ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]"; } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) { return query(db, columns, null, null, orderBy, null); } /** * Execute query using the current internal state as {@code WHERE} clause. */ public Cursor query(SQLiteDatabase db, String[] columns, String groupBy, String having, String orderBy, String limit) { assertTable(); if (columns != null) mapColumns(columns); if (LOGV) Log.v(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this); return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having, orderBy, limit); } /** * Execute update using the current internal state as {@code WHERE} clause. */ public int update(SQLiteDatabase db, ContentValues values) { assertTable(); if (LOGV) Log.v(TAG, "update() " + this); return db.update(mTable, values, getSelection(), getSelectionArgs()); } /** * Execute delete using the current internal state as {@code WHERE} clause. */ public int delete(SQLiteDatabase db) { assertTable(); if (LOGV) Log.v(TAG, "delete() " + this); return db.delete(mTable, getSelection(), getSelectionArgs()); } }
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 com.google.android.apps.iosched.R; import android.app.ActionBar; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; /** * An extension of {@link ActivityHelper} that provides Android 3.0-specific functionality for * Honeycomb tablets. It thus requires API level 11. */ public class ActivityHelperHoneycomb extends ActivityHelper { private Menu mOptionsMenu; protected ActivityHelperHoneycomb(Activity activity) { super(activity); } @Override public void onPostCreate(Bundle savedInstanceState) { // Do nothing in onPostCreate. ActivityHelper creates the old action bar, we don't // need to for Honeycomb. } @Override public boolean onCreateOptionsMenu(Menu menu) { mOptionsMenu = menu; return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Handle the HOME / UP affordance. Since the app is only two levels deep // hierarchically, UP always just goes home. goHome(); return true; } return super.onOptionsItemSelected(item); } /** {@inheritDoc} */ @Override public void setupHomeActivity() { super.setupHomeActivity(); // NOTE: there needs to be a content view set before this is called, so this method // should be called in onPostCreate. if (UIUtils.isTablet(mActivity)) { mActivity.getActionBar().setDisplayOptions( 0, ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE); } else { mActivity.getActionBar().setDisplayOptions( ActionBar.DISPLAY_USE_LOGO, ActionBar.DISPLAY_USE_LOGO | ActionBar.DISPLAY_SHOW_TITLE); } } /** {@inheritDoc} */ @Override public void setupSubActivity() { super.setupSubActivity(); // NOTE: there needs to be a content view set before this is called, so this method // should be called in onPostCreate. if (UIUtils.isTablet(mActivity)) { mActivity.getActionBar().setDisplayOptions( ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO, ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO); } else { mActivity.getActionBar().setDisplayOptions( 0, ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_USE_LOGO); } } /** * No-op on Honeycomb. The action bar title always remains the same. */ @Override public void setActionBarTitle(CharSequence title) { } /** * No-op on Honeycomb. The action bar color always remains the same. */ @Override public void setActionBarColor(int color) { if (!UIUtils.isTablet(mActivity)) { super.setActionBarColor(color); } } /** {@inheritDoc} */ @Override public void setRefreshActionButtonCompatState(boolean refreshing) { // On Honeycomb, we can set the state of the refresh button by giving it a custom // action view. if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { refreshItem.setActionView(R.layout.actionbar_indeterminate_progress); } else { refreshItem.setActionView(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.util; import com.google.android.apps.iosched.R; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; /** * A helper for showing EULAs and storing a {@link SharedPreferences} bit indicating whether the * user has accepted. */ public class EulaHelper { public static boolean hasAcceptedEula(final Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getBoolean("accepted_eula", false); } private static void setAcceptedEula(final Context context) { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putBoolean("accepted_eula", true).commit(); return null; } }.execute(); } /** * Show End User License Agreement. * * @param accepted True IFF user has accepted license already, which means it can be dismissed. * If the user hasn't accepted, then the EULA must be accepted or the program * exits. * @param activity Activity started from. */ public static void showEula(final boolean accepted, final Activity activity) { AlertDialog.Builder eula = new AlertDialog.Builder(activity) .setTitle(R.string.eula_title) .setIcon(android.R.drawable.ic_dialog_info) .setMessage(R.string.eula_text) .setCancelable(accepted); if (accepted) { // If they've accepted the EULA allow, show an OK to dismiss. eula.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } else { // If they haven't accepted the EULA allow, show accept/decline buttons and exit on // decline. eula .setPositiveButton(R.string.accept, new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { setAcceptedEula(activity); dialog.dismiss(); } }) .setNegativeButton(R.string.decline, new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); activity.finish(); } }); } eula.show(); } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * 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 java.util.HashMap; import java.util.LinkedHashMap; /** * Provides static methods for creating mutable {@code Maps} instances easily. */ public class Maps { /** * Creates a {@code HashMap} instance. * * @return a newly-created, initially-empty {@code HashMap} */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<K, V>(); } /** * Creates a {@code LinkedHashMap} instance. * * @return a newly-created, initially-empty {@code HashMap} */ public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() { return new LinkedHashMap<K, V>(); } }
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 android.os.Bundle; import android.os.Handler; import android.os.ResultReceiver; import android.util.Log; /** * Proxy {@link ResultReceiver} that offers a listener interface that can be * detached. Useful for when sending callbacks to a {@link Service} where a * listening {@link Activity} can be swapped out during configuration changes. */ public class DetachableResultReceiver extends ResultReceiver { private static final String TAG = "DetachableResultReceiver"; private Receiver mReceiver; public DetachableResultReceiver(Handler handler) { super(handler); } public void clearReceiver() { mReceiver = null; } public void setReceiver(Receiver receiver) { mReceiver = receiver; } public interface Receiver { public void onReceiveResult(int resultCode, Bundle resultData); } @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (mReceiver != null) { mReceiver.onReceiveResult(resultCode, resultData); } else { Log.w(TAG, "Dropping result on floor for code " + resultCode + ": " + resultData.toString()); } } }
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 com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.ui.phone.MapActivity; import com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.preference.PreferenceManager; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.method.LinkMovementMethod; import android.text.style.StyleSpan; import android.widget.TextView; import java.util.Formatter; import java.util.List; import java.util.Locale; import java.util.TimeZone; /** * An assortment of UI helpers. */ public class UIUtils { /** * Time zone to use when formatting all session times. To always use the * phone local time, use {@link TimeZone#getDefault()}. */ public static final TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone("America/Los_Angeles"); public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime( "2011-05-10T09:00:00.000-07:00"); public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime( "2011-05-11T17:30:00.000-07:00"); public static final Uri CONFERENCE_URL = Uri.parse("http://www.google.com/events/io/2011/"); /** Flags used with {@link DateUtils#formatDateRange}. */ private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY; /** {@link StringBuilder} used for formatting time block. */ private static StringBuilder sBuilder = new StringBuilder(50); /** {@link Formatter} used for formatting time block. */ private static Formatter sFormatter = new Formatter(sBuilder, Locale.getDefault()); private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD); /** * Format and return the given {@link Blocks} and {@link Rooms} values using * {@link #CONFERENCE_TIME_ZONE}. */ public static String formatSessionSubtitle(long blockStart, long blockEnd, String roomName, Context context) { TimeZone.setDefault(CONFERENCE_TIME_ZONE); // NOTE: There is an efficient version of formatDateRange in Eclair and // beyond that allows you to recycle a StringBuilder. final CharSequence timeString = DateUtils.formatDateRange(context, blockStart, blockEnd, TIME_FLAGS); return context.getString(R.string.session_subtitle, timeString, roomName); } /** * Populate the given {@link TextView} with the requested text, formatting * through {@link Html#fromHtml(String)} when applicable. Also sets * {@link TextView#setMovementMethod} so inline links are handled. */ public static void setTextMaybeHtml(TextView view, String text) { if (TextUtils.isEmpty(text)) { view.setText(""); return; } if (text.contains("<") && text.contains(">")) { view.setText(Html.fromHtml(text)); view.setMovementMethod(LinkMovementMethod.getInstance()); } else { view.setText(text); } } public static void setSessionTitleColor(long blockStart, long blockEnd, TextView title, TextView subtitle) { long currentTimeMillis = System.currentTimeMillis(); int colorId = R.color.body_text_1; int subColorId = R.color.body_text_2; if (currentTimeMillis > blockEnd && currentTimeMillis < CONFERENCE_END_MILLIS) { colorId = subColorId = R.color.body_text_disabled; } final Resources res = title.getResources(); title.setTextColor(res.getColor(colorId)); subtitle.setTextColor(res.getColor(subColorId)); } /** * Given a snippet string with matching segments surrounded by curly * braces, turn those areas into bold spans, removing the curly braces. */ public static Spannable buildStyledSnippet(String snippet) { final SpannableStringBuilder builder = new SpannableStringBuilder(snippet); // Walk through string, inserting bold snippet spans int startIndex = -1, endIndex = -1, delta = 0; while ((startIndex = snippet.indexOf('{', endIndex)) != -1) { endIndex = snippet.indexOf('}', startIndex); // Remove braces from both sides builder.delete(startIndex - delta, startIndex - delta + 1); builder.delete(endIndex - delta - 1, endIndex - delta); // Insert bold style builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); delta += 2; } return builder; } public static String getLastUsedTrackID(Context context) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); return sp.getString("last_track_id", null); } public static void setLastUsedTrackID(Context context, String trackID) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); sp.edit().putString("last_track_id", trackID).commit(); } private static final int BRIGHTNESS_THRESHOLD = 130; /** * Calculate whether a color is light or dark, based on a commonly known * brightness formula. * * @see {@literal http://en.wikipedia.org/wiki/HSV_color_space%23Lightness} */ public static boolean isColorDark(int color) { return ((30 * Color.red(color) + 59 * Color.green(color) + 11 * Color.blue(color)) / 100) <= BRIGHTNESS_THRESHOLD; } public static boolean isHoneycomb() { // Can use static final constants like HONEYCOMB, declared in later versions // of the OS since they are inlined at compile time. This is guaranteed behavior. return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB; } public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE; } public static boolean isHoneycombTablet(Context context) { return isHoneycomb() && isTablet(context); } public static long getCurrentTime(final Context context) { //SharedPreferences prefs = context.getSharedPreferences("mock_data", 0); //prefs.edit().commit(); //return prefs.getLong("mock_current_time", System.currentTimeMillis()); return System.currentTimeMillis(); } public static Drawable getIconForIntent(final Context context, Intent i) { PackageManager pm = context.getPackageManager(); List<ResolveInfo> infos = pm.queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY); if (infos.size() > 0) { return infos.get(0).loadIcon(pm); } return null; } public static Class getMapActivityClass(Context context) { if (UIUtils.isHoneycombTablet(context)) { return MapMultiPaneActivity.class; } return MapActivity.class; } }
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 android.view.MotionEvent; /** * A utility class that emulates multitouch APIs available in Android 2.0+. */ public class MotionEventUtils { public static final int ACTION_MASK = 0xff; public static final int ACTION_POINTER_UP = 0x6; public static final int ACTION_POINTER_INDEX_MASK = 0x0000ff00; public static final int ACTION_POINTER_INDEX_SHIFT = 8; public static boolean sMultiTouchApiAvailable; static { try { MotionEvent.class.getMethod("getPointerId", new Class[]{int.class}); sMultiTouchApiAvailable = true; } catch (NoSuchMethodException nsme) { sMultiTouchApiAvailable = false; } } public static float getX(MotionEvent ev, int pointerIndex) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.getX(ev, pointerIndex); } else { return ev.getX(); } } public static float getY(MotionEvent ev, int pointerIndex) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.getY(ev, pointerIndex); } else { return ev.getY(); } } public static int getPointerId(MotionEvent ev, int pointerIndex) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.getPointerId(ev, pointerIndex); } else { return 0; } } public static int findPointerIndex(MotionEvent ev, int pointerId) { if (sMultiTouchApiAvailable) { return WrappedStaticMotionEvent.findPointerIndex(ev, pointerId); } else { return (pointerId == 0) ? 0 : -1; } } /** * A wrapper around newer (SDK level 5) MotionEvent APIs. This class only gets loaded * if it is determined that these new APIs exist on the device. */ private static class WrappedStaticMotionEvent { public static float getX(MotionEvent ev, int pointerIndex) { return ev.getX(pointerIndex); } public static float getY(MotionEvent ev, int pointerIndex) { return ev.getY(pointerIndex); } public static int getPointerId(MotionEvent ev, int pointerIndex) { return ev.getPointerId(pointerIndex); } public static int findPointerIndex(MotionEvent ev, int pointerId) { return ev.findPointerIndex(pointerId); } } }
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 android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ContextMenu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; /** * A <em>really</em> dumb implementation of the {@link MenuItem} interface, that's only useful for * our old-actionbar purposes. See <code>com.android.internal.view.menu.MenuItemImpl</code> in * AOSP for a more complete implementation. */ public class SimpleMenuItem implements MenuItem { private SimpleMenu mMenu; private final int mId; private final int mOrder; private CharSequence mTitle; private CharSequence mTitleCondensed; private Drawable mIconDrawable; private int mIconResId = 0; private boolean mEnabled = true; public SimpleMenuItem(SimpleMenu menu, int id, int order, CharSequence title) { mMenu = menu; mId = id; mOrder = order; mTitle = title; } public int getItemId() { return mId; } public int getOrder() { return mOrder; } public MenuItem setTitle(CharSequence title) { mTitle = title; return this; } public MenuItem setTitle(int titleRes) { return setTitle(mMenu.getContext().getString(titleRes)); } public CharSequence getTitle() { return mTitle; } public MenuItem setTitleCondensed(CharSequence title) { mTitleCondensed = title; return this; } public CharSequence getTitleCondensed() { return mTitleCondensed != null ? mTitleCondensed : mTitle; } public MenuItem setIcon(Drawable icon) { mIconResId = 0; mIconDrawable = icon; return this; } public MenuItem setIcon(int iconResId) { mIconDrawable = null; mIconResId = iconResId; return this; } public Drawable getIcon() { if (mIconDrawable != null) { return mIconDrawable; } if (mIconResId != 0) { return mMenu.getResources().getDrawable(mIconResId); } return null; } public MenuItem setEnabled(boolean enabled) { mEnabled = enabled; return this; } public boolean isEnabled() { return mEnabled; } // No-op operations. We use no-ops to allow inflation from menu XML. public int getGroupId() { return 0; } public View getActionView() { return null; } public MenuItem setIntent(Intent intent) { // Noop return this; } public Intent getIntent() { return null; } public MenuItem setShortcut(char c, char c1) { // Noop return this; } public MenuItem setNumericShortcut(char c) { // Noop return this; } public char getNumericShortcut() { return 0; } public MenuItem setAlphabeticShortcut(char c) { // Noop return this; } public char getAlphabeticShortcut() { return 0; } public MenuItem setCheckable(boolean b) { // Noop return this; } public boolean isCheckable() { return false; } public MenuItem setChecked(boolean b) { // Noop return this; } public boolean isChecked() { return false; } public MenuItem setVisible(boolean b) { // Noop return this; } public boolean isVisible() { return true; } public boolean hasSubMenu() { return false; } public SubMenu getSubMenu() { return null; } public MenuItem setOnMenuItemClickListener( OnMenuItemClickListener onMenuItemClickListener) { // Noop return this; } public ContextMenu.ContextMenuInfo getMenuInfo() { return null; } public void setShowAsAction(int i) { // Noop } public MenuItem setActionView(View view) { // Noop return this; } public MenuItem setActionView(int i) { // Noop return this; } }
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 com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.HomeActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; /** * A class that handles some common activity-related functionality in the app, such as setting up * the action bar. This class provides functionality useful for both phones and tablets, and does * not require any Android 3.0-specific features. */ public class ActivityHelper { protected Activity mActivity; /** * Factory method for creating {@link ActivityHelper} objects for a given activity. Depending * on which device the app is running, either a basic helper or Honeycomb-specific helper will * be returned. */ public static ActivityHelper createInstance(Activity activity) { return UIUtils.isHoneycomb() ? new ActivityHelperHoneycomb(activity) : new ActivityHelper(activity); } protected ActivityHelper(Activity activity) { mActivity = activity; } public void onPostCreate(Bundle savedInstanceState) { // Create the action bar SimpleMenu menu = new SimpleMenu(mActivity); mActivity.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu); // TODO: call onPreparePanelMenu here as well for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); addActionButtonCompatFromMenuItem(item); } } public boolean onCreateOptionsMenu(Menu menu) { mActivity.getMenuInflater().inflate(R.menu.default_menu_items, menu); return false; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: goSearch(); return true; } return false; } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { return true; } return false; } public boolean onKeyLongPress(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { goHome(); return true; } return false; } /** * Method, to be called in <code>onPostCreate</code>, that sets up this activity as the * home activity for the app. */ public void setupHomeActivity() { } /** * Method, to be called in <code>onPostCreate</code>, that sets up this activity as a * sub-activity in the app. */ public void setupSubActivity() { } /** * Invoke "home" action, returning to {@link com.google.android.apps.iosched.ui.HomeActivity}. */ public void goHome() { if (mActivity instanceof HomeActivity) { return; } final Intent intent = new Intent(mActivity, HomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); mActivity.startActivity(intent); if (!UIUtils.isHoneycomb()) { mActivity.overridePendingTransition(R.anim.home_enter, R.anim.home_exit); } } /** * Invoke "search" action, triggering a default search. */ public void goSearch() { mActivity.startSearch(null, false, Bundle.EMPTY, false); } /** * Sets up the action bar with the given title and accent color. If title is null, then * the app logo will be shown instead of a title. Otherwise, a home button and title are * visible. If color is null, then the default colorstrip is visible. */ public void setupActionBar(CharSequence title, int color) { final ViewGroup actionBarCompat = getActionBarCompat(); if (actionBarCompat == null) { return; } LinearLayout.LayoutParams springLayoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.FILL_PARENT); springLayoutParams.weight = 1; View.OnClickListener homeClickListener = new View.OnClickListener() { public void onClick(View view) { goHome(); } }; if (title != null) { // Add Home button addActionButtonCompat(R.drawable.ic_title_home, R.string.description_home, homeClickListener, true); // Add title text TextView titleText = new TextView(mActivity, null, R.attr.actionbarCompatTextStyle); titleText.setLayoutParams(springLayoutParams); titleText.setText(title); actionBarCompat.addView(titleText); } else { // Add logo ImageButton logo = new ImageButton(mActivity, null, R.attr.actionbarCompatLogoStyle); logo.setOnClickListener(homeClickListener); actionBarCompat.addView(logo); // Add spring (dummy view to align future children to the right) View spring = new View(mActivity); spring.setLayoutParams(springLayoutParams); actionBarCompat.addView(spring); } setActionBarColor(color); } /** * Sets the action bar color to the given color. */ public void setActionBarColor(int color) { if (color == 0) { return; } final View colorstrip = mActivity.findViewById(R.id.colorstrip); if (colorstrip == null) { return; } colorstrip.setBackgroundColor(color); } /** * Sets the action bar title to the given string. */ public void setActionBarTitle(CharSequence title) { ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return; } TextView titleText = (TextView) actionBar.findViewById(R.id.actionbar_compat_text); if (titleText != null) { titleText.setText(title); } } /** * Returns the {@link ViewGroup} for the action bar on phones (compatibility action bar). * Can return null, and will return null on Honeycomb. */ public ViewGroup getActionBarCompat() { return (ViewGroup) mActivity.findViewById(R.id.actionbar_compat); } /** * Adds an action bar button to the compatibility action bar (on phones). */ private View addActionButtonCompat(int iconResId, int textResId, View.OnClickListener clickListener, boolean separatorAfter) { final ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return null; } // Create the separator ImageView separator = new ImageView(mActivity, null, R.attr.actionbarCompatSeparatorStyle); separator.setLayoutParams( new ViewGroup.LayoutParams(2, ViewGroup.LayoutParams.FILL_PARENT)); // Create the button ImageButton actionButton = new ImageButton(mActivity, null, R.attr.actionbarCompatButtonStyle); actionButton.setLayoutParams(new ViewGroup.LayoutParams( (int) mActivity.getResources().getDimension(R.dimen.actionbar_compat_height), ViewGroup.LayoutParams.FILL_PARENT)); actionButton.setImageResource(iconResId); actionButton.setScaleType(ImageView.ScaleType.CENTER); actionButton.setContentDescription(mActivity.getResources().getString(textResId)); actionButton.setOnClickListener(clickListener); // Add separator and button to the action bar in the desired order if (!separatorAfter) { actionBar.addView(separator); } actionBar.addView(actionButton); if (separatorAfter) { actionBar.addView(separator); } return actionButton; } /** * Adds an action button to the compatibility action bar, using menu information from a * {@link MenuItem}. If the menu item ID is <code>menu_refresh</code>, the menu item's state * can be changed to show a loading spinner using * {@link ActivityHelper#setRefreshActionButtonCompatState(boolean)}. */ private View addActionButtonCompatFromMenuItem(final MenuItem item) { final ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return null; } // Create the separator ImageView separator = new ImageView(mActivity, null, R.attr.actionbarCompatSeparatorStyle); separator.setLayoutParams( new ViewGroup.LayoutParams(2, ViewGroup.LayoutParams.FILL_PARENT)); // Create the button ImageButton actionButton = new ImageButton(mActivity, null, R.attr.actionbarCompatButtonStyle); actionButton.setId(item.getItemId()); actionButton.setLayoutParams(new ViewGroup.LayoutParams( (int) mActivity.getResources().getDimension(R.dimen.actionbar_compat_height), ViewGroup.LayoutParams.FILL_PARENT)); actionButton.setImageDrawable(item.getIcon()); actionButton.setScaleType(ImageView.ScaleType.CENTER); actionButton.setContentDescription(item.getTitle()); actionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mActivity.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); } }); actionBar.addView(separator); actionBar.addView(actionButton); if (item.getItemId() == R.id.menu_refresh) { // Refresh buttons should be stateful, and allow for indeterminate progress indicators, // so add those. int buttonWidth = mActivity.getResources() .getDimensionPixelSize(R.dimen.actionbar_compat_height); int buttonWidthDiv3 = buttonWidth / 3; ProgressBar indicator = new ProgressBar(mActivity, null, R.attr.actionbarCompatProgressIndicatorStyle); LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( buttonWidthDiv3, buttonWidthDiv3); indicatorLayoutParams.setMargins(buttonWidthDiv3, buttonWidthDiv3, buttonWidth - 2 * buttonWidthDiv3, 0); indicator.setLayoutParams(indicatorLayoutParams); indicator.setVisibility(View.GONE); indicator.setId(R.id.menu_refresh_progress); actionBar.addView(indicator); } return actionButton; } /** * Sets the indeterminate loading state of a refresh button added with * {@link ActivityHelper#addActionButtonCompatFromMenuItem(android.view.MenuItem)} * (where the item ID was menu_refresh). */ public void setRefreshActionButtonCompatState(boolean refreshing) { View refreshButton = mActivity.findViewById(R.id.menu_refresh); View refreshIndicator = mActivity.findViewById(R.id.menu_refresh_progress); if (refreshButton != null) { refreshButton.setVisibility(refreshing ? View.GONE : View.VISIBLE); } if (refreshIndicator != null) { refreshIndicator.setVisibility(refreshing ? View.VISIBLE : View.GONE); } } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * 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 android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import java.lang.ref.WeakReference; /** * Slightly more abstract {@link AsyncQueryHandler} that helps keep a * {@link WeakReference} back to a listener. Will properly close any * {@link Cursor} if the listener ceases to exist. * <p> * This pattern can be used to perform background queries without leaking * {@link Context} objects. * * @hide pending API council review */ public class NotifyingAsyncQueryHandler extends AsyncQueryHandler { private WeakReference<AsyncQueryListener> mListener; /** * Interface to listen for completed query operations. */ public interface AsyncQueryListener { void onQueryComplete(int token, Object cookie, Cursor cursor); } public NotifyingAsyncQueryHandler(ContentResolver resolver, AsyncQueryListener listener) { super(resolver); setQueryListener(listener); } /** * Assign the given {@link AsyncQueryListener} to receive query events from * asynchronous calls. Will replace any existing listener. */ public void setQueryListener(AsyncQueryListener listener) { mListener = new WeakReference<AsyncQueryListener>(listener); } /** * Clear any {@link AsyncQueryListener} set through * {@link #setQueryListener(AsyncQueryListener)} */ public void clearQueryListener() { mListener = null; } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is * called if a valid {@link AsyncQueryListener} is present. */ public void startQuery(Uri uri, String[] projection) { startQuery(-1, null, uri, projection, null, null, null); } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called * if a valid {@link AsyncQueryListener} is present. * * @param token Unique identifier passed through to * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} */ public void startQuery(int token, Uri uri, String[] projection) { startQuery(token, null, uri, projection, null, null, null); } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called * if a valid {@link AsyncQueryListener} is present. */ public void startQuery(Uri uri, String[] projection, String sortOrder) { startQuery(-1, null, uri, projection, null, null, sortOrder); } /** * Begin an asynchronous query with the given arguments. When finished, * {@link AsyncQueryListener#onQueryComplete(int, Object, Cursor)} is called * if a valid {@link AsyncQueryListener} is present. */ public void startQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy) { startQuery(-1, null, uri, projection, selection, selectionArgs, orderBy); } /** * Begin an asynchronous update with the given arguments. */ public void startUpdate(Uri uri, ContentValues values) { startUpdate(-1, null, uri, values, null, null); } public void startInsert(Uri uri, ContentValues values) { startInsert(-1, null, uri, values); } public void startDelete(Uri uri) { startDelete(-1, null, uri, null, null); } /** {@inheritDoc} */ @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { final AsyncQueryListener listener = mListener == null ? null : mListener.get(); if (listener != null) { listener.onQueryComplete(token, cookie, cursor); } else if (cursor != null) { cursor.close(); } } }
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 com.google.android.apps.analytics.GoogleAnalyticsTracker; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; /** * Helper singleton class for the Google Analytics tracking library. */ public class AnalyticsUtils { private static final String TAG = "AnalyticsUtils"; GoogleAnalyticsTracker mTracker; private Context mApplicationContext; /** * The analytics tracking code for the app. */ // TODO: insert your Analytics UA code here. private static final String UACODE = "INSERT_YOUR_ANALYTICS_UA_CODE_HERE"; private static final int VISITOR_SCOPE = 1; private static final String FIRST_RUN_KEY = "firstRun"; private static final boolean ANALYTICS_ENABLED = true; private static AnalyticsUtils sInstance; /** * Returns the global {@link AnalyticsUtils} singleton object, creating one if necessary. */ public static AnalyticsUtils getInstance(Context context) { if (!ANALYTICS_ENABLED) { return sEmptyAnalyticsUtils; } if (sInstance == null) { if (context == null) { return sEmptyAnalyticsUtils; } sInstance = new AnalyticsUtils(context); } return sInstance; } private AnalyticsUtils(Context context) { if (context == null) { // This should only occur for the empty Analytics utils object. return; } mApplicationContext = context.getApplicationContext(); mTracker = GoogleAnalyticsTracker.getInstance(); // Unfortunately this needs to be synchronous. mTracker.start(UACODE, 300, mApplicationContext); Log.d(TAG, "Initializing Analytics"); // Since visitor CV's should only be declared the first time an app runs, check if // it's run before. Add as necessary. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( mApplicationContext); final boolean firstRun = prefs.getBoolean(FIRST_RUN_KEY, true); if (firstRun) { Log.d(TAG, "Analytics firstRun"); String apiLevel = Integer.toString(Build.VERSION.SDK_INT); String model = Build.MODEL; mTracker.setCustomVar(1, "apiLevel", apiLevel, VISITOR_SCOPE); mTracker.setCustomVar(2, "model", model, VISITOR_SCOPE); // Close out so we never run this block again, unless app is removed & = // reinstalled. prefs.edit().putBoolean(FIRST_RUN_KEY, false).commit(); } } public void trackEvent(final String category, final String action, final String label, final int value) { // We wrap the call in an AsyncTask since the Google Analytics library writes to disk // on its calling thread. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { mTracker.trackEvent(category, action, label, value); Log.d(TAG, "iosched Analytics trackEvent: " + category + " / " + action + " / " + label + " / " + value); } catch (Exception e) { // We don't want to crash if there's an Analytics library exception. Log.w(TAG, "iosched Analytics trackEvent error: " + category + " / " + action + " / " + label + " / " + value, e); } return null; } }.execute(); } public void trackPageView(final String path) { // We wrap the call in an AsyncTask since the Google Analytics library writes to disk // on its calling thread. new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { mTracker.trackPageView(path); Log.d(TAG, "iosched Analytics trackPageView: " + path); } catch (Exception e) { // We don't want to crash if there's an Analytics library exception. Log.w(TAG, "iosched Analytics trackPageView error: " + path, e); } return null; } }.execute(); } /** * Empty instance for use when Analytics is disabled or there was no Context available. */ private static AnalyticsUtils sEmptyAnalyticsUtils = new AnalyticsUtils(null) { @Override public void trackEvent(String category, String action, String label, int value) {} @Override public void trackPageView(String path) {} }; }
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 java.lang.reflect.InvocationTargetException; public class ReflectionUtils { public static Object tryInvoke(Object target, String methodName, Object... args) { Class<?>[] argTypes = new Class<?>[args.length]; for (int i = 0; i < args.length; i++) { argTypes[i] = args[i].getClass(); } return tryInvoke(target, methodName, argTypes, args); } public static Object tryInvoke(Object target, String methodName, Class<?>[] argTypes, Object... args) { try { return target.getClass().getMethod(methodName, argTypes).invoke(target, args); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return null; } public static <E> E callWithDefault(Object target, String methodName, E defaultValue) { try { return (E) target.getClass().getMethod(methodName, (Class[]) null).invoke(target); } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } return defaultValue; } }
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 com.google.android.apps.iosched.io.XmlHandler; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Blocks; import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns; import com.google.android.apps.iosched.provider.ScheduleContract.Tracks; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentResolver; import android.database.Cursor; import android.net.Uri; import android.text.format.Time; import java.io.InputStream; import java.util.ArrayList; import java.util.Set; import java.util.regex.Pattern; /** * Various utility methods used by {@link XmlHandler} implementations. */ public class ParserUtils { // TODO: consider refactor to HandlerUtils? // TODO: localize this string at some point public static final String BLOCK_TITLE_BREAKOUT_SESSIONS = "Breakout sessions"; public static final String BLOCK_TYPE_FOOD = "food"; public static final String BLOCK_TYPE_SESSION = "session"; public static final String BLOCK_TYPE_OFFICE_HOURS = "officehours"; // TODO: factor this out into a separate data file. public static final Set<String> LOCAL_TRACK_IDS = Sets.newHashSet( "accessibility", "android", "appengine", "chrome", "commerce", "developertools", "gamedevelopment", "geo", "googleapis", "googleapps", "googletv", "techtalk", "webgames", "youtube"); /** Used to sanitize a string to be {@link Uri} safe. */ private static final Pattern sSanitizePattern = Pattern.compile("[^a-z0-9-_]"); private static final Pattern sParenPattern = Pattern.compile("\\(.*?\\)"); /** Used to split a comma-separated string. */ private static final Pattern sCommaPattern = Pattern.compile("\\s*,\\s*"); private static Time sTime = new Time(); private static XmlPullParserFactory sFactory; /** * Sanitize the given string to be {@link Uri} safe for building * {@link ContentProvider} paths. */ public static String sanitizeId(String input) { return sanitizeId(input, false); } /** * Sanitize the given string to be {@link Uri} safe for building * {@link ContentProvider} paths. */ public static String sanitizeId(String input, boolean stripParen) { if (input == null) return null; if (stripParen) { // Strip out all parenthetical statements when requested. input = sParenPattern.matcher(input).replaceAll(""); } return sSanitizePattern.matcher(input.toLowerCase()).replaceAll(""); } /** * Split the given comma-separated string, returning all values. */ public static String[] splitComma(CharSequence input) { if (input == null) return new String[0]; return sCommaPattern.split(input); } /** * Build and return a new {@link XmlPullParser} with the given * {@link InputStream} assigned to it. */ public static XmlPullParser newPullParser(InputStream input) throws XmlPullParserException { if (sFactory == null) { sFactory = XmlPullParserFactory.newInstance(); } final XmlPullParser parser = sFactory.newPullParser(); parser.setInput(input, null); return parser; } /** * Parse the given string as a RFC 3339 timestamp, returning the value as * milliseconds since the epoch. */ public static long parseTime(String time) { sTime.parse3339(time); return sTime.toMillis(false); } /** * Return a {@link Blocks#BLOCK_ID} matching the requested arguments. */ public static String findBlock(String title, long startTime, long endTime) { // TODO: in future we might check provider if block exists return Blocks.generateBlockId(startTime, endTime); } /** * Return a {@link Blocks#BLOCK_ID} matching the requested arguments, * inserting a new {@link Blocks} entry as a * {@link ContentProviderOperation} when none already exists. */ public static String findOrCreateBlock(String title, String type, long startTime, long endTime, ArrayList<ContentProviderOperation> batch, ContentResolver resolver) { // TODO: check for existence instead of always blindly creating. it's // okay for now since the database replaces on conflict. final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Blocks.CONTENT_URI); final String blockId = Blocks.generateBlockId(startTime, endTime); builder.withValue(Blocks.BLOCK_ID, blockId); builder.withValue(Blocks.BLOCK_TITLE, title); builder.withValue(Blocks.BLOCK_START, startTime); builder.withValue(Blocks.BLOCK_END, endTime); builder.withValue(Blocks.BLOCK_TYPE, type); batch.add(builder.build()); return blockId; } /** * Query and return the {@link SyncColumns#UPDATED} time for the requested * {@link Uri}. Expects the {@link Uri} to reference a single item. */ public static long queryItemUpdated(Uri uri, ContentResolver resolver) { final String[] projection = { SyncColumns.UPDATED }; final Cursor cursor = resolver.query(uri, projection, null, null, null); try { if (cursor.moveToFirst()) { return cursor.getLong(0); } else { return ScheduleContract.UPDATED_NEVER; } } finally { cursor.close(); } } /** * Query and return the newest {@link SyncColumns#UPDATED} time for all * entries under the requested {@link Uri}. Expects the {@link Uri} to * reference a directory of several items. */ public static long queryDirUpdated(Uri uri, ContentResolver resolver) { final String[] projection = { "MAX(" + SyncColumns.UPDATED + ")" }; final Cursor cursor = resolver.query(uri, projection, null, null, null); try { cursor.moveToFirst(); return cursor.getLong(0); } finally { cursor.close(); } } /** * Translate an incoming {@link Tracks#TRACK_ID}, usually passing directly * through, but returning a different value when a local alias is defined. */ public static String translateTrackIdAlias(String trackId) { //if ("gwt".equals(trackId)) { // return "googlewebtoolkit"; //} else { return trackId; //} } /** * Translate a possibly locally aliased {@link Tracks#TRACK_ID} to its real value; * this usually is a pass-through. */ public static String translateTrackIdAliasInverse(String trackId) { //if ("googlewebtoolkit".equals(trackId)) { // return "gwt"; //} else { return trackId; //} } /** XML tag constants used by the Atom standard. */ public interface AtomTags { String ENTRY = "entry"; String UPDATED = "updated"; String TITLE = "title"; String LINK = "link"; String CONTENT = "content"; String REL = "rel"; String HREF = "href"; } }
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.ui.widget.BlockView; import com.google.android.apps.iosched.ui.widget.BlocksLayout; import com.google.android.apps.iosched.ui.widget.ObservableScrollView; import com.google.android.apps.iosched.ui.widget.Workspace; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.Maps; import com.google.android.apps.iosched.util.MotionEventUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Rect; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.Fragment; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TimeZone; /** * Shows a horizontally-pageable calendar of conference days. Horizontaly paging is achieved using * {@link Workspace}, and the primary UI classes for rendering the calendar are * {@link com.google.android.apps.iosched.ui.widget.TimeRulerView}, * {@link BlocksLayout}, and {@link BlockView}. */ public class ScheduleFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, ObservableScrollView.OnScrollListener, View.OnClickListener { private static final String TAG = "ScheduleFragment"; /** * Flags used with {@link android.text.format.DateUtils#formatDateRange}. */ private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY; private static final long TUE_START = ParserUtils.parseTime("2011-05-10T00:00:00.000-07:00"); private static final long WED_START = ParserUtils.parseTime("2011-05-11T00:00:00.000-07:00"); private static final int DISABLED_BLOCK_ALPHA = 100; private static final HashMap<String, Integer> sTypeColumnMap = buildTypeColumnMap(); // TODO: show blocks that don't fall into columns at the bottom public static final String EXTRA_TIME_START = "com.google.android.iosched.extra.TIME_START"; public static final String EXTRA_TIME_END = "com.google.android.iosched.extra.TIME_END"; private NotifyingAsyncQueryHandler mHandler; private Workspace mWorkspace; private TextView mTitle; private int mTitleCurrentDayIndex = -1; private View mLeftIndicator; private View mRightIndicator; /** * A helper class containing object references related to a particular day in the schedule. */ private class Day { private ViewGroup rootView; private ObservableScrollView scrollView; private View nowView; private BlocksLayout blocksView; private int index = -1; private String label = null; private Uri blocksUri = null; private long timeStart = -1; private long timeEnd = -1; } private List<Day> mDays = new ArrayList<Day>(); private static HashMap<String, Integer> buildTypeColumnMap() { final HashMap<String, Integer> map = Maps.newHashMap(); map.put(ParserUtils.BLOCK_TYPE_FOOD, 0); map.put(ParserUtils.BLOCK_TYPE_SESSION, 1); map.put(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, 2); return map; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); setHasOptionsMenu(true); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Schedule"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_schedule, null); mWorkspace = (Workspace) root.findViewById(R.id.workspace); mTitle = (TextView) root.findViewById(R.id.block_title); mLeftIndicator = root.findViewById(R.id.indicator_left); mLeftIndicator.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent motionEvent) { if ((motionEvent.getAction() & MotionEventUtils.ACTION_MASK) == MotionEvent.ACTION_DOWN) { mWorkspace.scrollLeft(); return true; } return false; } }); mLeftIndicator.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mWorkspace.scrollLeft(); } }); mRightIndicator = root.findViewById(R.id.indicator_right); mRightIndicator.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent motionEvent) { if ((motionEvent.getAction() & MotionEventUtils.ACTION_MASK) == MotionEvent.ACTION_DOWN) { mWorkspace.scrollRight(); return true; } return false; } }); mRightIndicator.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mWorkspace.scrollRight(); } }); setupDay(inflater, TUE_START); setupDay(inflater, WED_START); updateWorkspaceHeader(0); mWorkspace.setOnScrollListener(new Workspace.OnScrollListener() { public void onScroll(float screenFraction) { updateWorkspaceHeader(Math.round(screenFraction)); } }, true); return root; } public void updateWorkspaceHeader(int dayIndex) { if (mTitleCurrentDayIndex == dayIndex) { return; } mTitleCurrentDayIndex = dayIndex; Day day = mDays.get(dayIndex); mTitle.setText(day.label); mLeftIndicator .setVisibility((dayIndex != 0) ? View.VISIBLE : View.INVISIBLE); mRightIndicator .setVisibility((dayIndex < mDays.size() - 1) ? View.VISIBLE : View.INVISIBLE); } private void setupDay(LayoutInflater inflater, long startMillis) { Day day = new Day(); // Setup data day.index = mDays.size(); day.timeStart = startMillis; day.timeEnd = startMillis + DateUtils.DAY_IN_MILLIS; day.blocksUri = ScheduleContract.Blocks.buildBlocksBetweenDirUri( day.timeStart, day.timeEnd); // Setup views day.rootView = (ViewGroup) inflater.inflate(R.layout.blocks_content, null); day.scrollView = (ObservableScrollView) day.rootView.findViewById(R.id.blocks_scroll); day.scrollView.setOnScrollListener(this); day.blocksView = (BlocksLayout) day.rootView.findViewById(R.id.blocks); day.nowView = day.rootView.findViewById(R.id.blocks_now); day.blocksView.setDrawingCacheEnabled(true); day.blocksView.setAlwaysDrawnWithCacheEnabled(true); TimeZone.setDefault(UIUtils.CONFERENCE_TIME_ZONE); day.label = DateUtils.formatDateTime(getActivity(), startMillis, TIME_FLAGS); mWorkspace.addView(day.rootView); mDays.add(day); } @Override public void onResume() { super.onResume(); // Since we build our views manually instead of using an adapter, we // need to manually requery every time launched. requery(); getActivity().getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mSessionChangesObserver); // Start listening for time updates to adjust "now" bar. TIME_TICK is // triggered once per minute, which is how we move the bar over time. final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_TIME_TICK); filter.addAction(Intent.ACTION_TIME_CHANGED); filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); getActivity().registerReceiver(mReceiver, filter, null, new Handler()); } private void requery() { for (Day day : mDays) { mHandler.startQuery(0, day, day.blocksUri, BlocksQuery.PROJECTION, null, null, ScheduleContract.Blocks.DEFAULT_SORT); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getActivity().runOnUiThread(new Runnable() { public void run() { updateNowView(true); } }); } @Override public void onPause() { super.onPause(); getActivity().unregisterReceiver(mReceiver); getActivity().getContentResolver().unregisterContentObserver(mSessionChangesObserver); } /** * {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } Day day = (Day) cookie; // Clear out any existing sessions before inserting again day.blocksView.removeAllBlocks(); try { while (cursor.moveToNext()) { final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final Integer column = sTypeColumnMap.get(type); // TODO: place random blocks at bottom of entire layout if (column == null) { continue; } final String blockId = cursor.getString(BlocksQuery.BLOCK_ID); final String title = cursor.getString(BlocksQuery.BLOCK_TITLE); final long start = cursor.getLong(BlocksQuery.BLOCK_START); final long end = cursor.getLong(BlocksQuery.BLOCK_END); final boolean containsStarred = cursor.getInt(BlocksQuery.CONTAINS_STARRED) != 0; final BlockView blockView = new BlockView(getActivity(), blockId, title, start, end, containsStarred, column); final int sessionsCount = cursor.getInt(BlocksQuery.SESSIONS_COUNT); if (sessionsCount > 0) { blockView.setOnClickListener(this); } else { blockView.setFocusable(false); blockView.setEnabled(false); LayerDrawable buttonDrawable = (LayerDrawable) blockView.getBackground(); buttonDrawable.getDrawable(0).setAlpha(DISABLED_BLOCK_ALPHA); buttonDrawable.getDrawable(2).setAlpha(DISABLED_BLOCK_ALPHA); } day.blocksView.addBlock(blockView); } } finally { cursor.close(); } } /** {@inheritDoc} */ public void onClick(View view) { if (view instanceof BlockView) { String title = ((BlockView)view).getText().toString(); AnalyticsUtils.getInstance(getActivity()).trackEvent( "Schedule", "Session Click", title, 0); final String blockId = ((BlockView) view).getBlockId(); final Uri sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(SessionsFragment.EXTRA_SCHEDULE_TIME_STRING, ((BlockView) view).getBlockTimeString()); ((BaseActivity) getActivity()).openActivityOrFragment(intent); } } /** * Update position and visibility of "now" view. */ private boolean updateNowView(boolean forceScroll) { final long now = UIUtils.getCurrentTime(getActivity()); Day nowDay = null; // effectively Day corresponding to today for (Day day : mDays) { if (now >= day.timeStart && now <= day.timeEnd) { nowDay = day; day.nowView.setVisibility(View.VISIBLE); } else { day.nowView.setVisibility(View.GONE); } } if (nowDay != null && forceScroll) { // Scroll to show "now" in center mWorkspace.setCurrentScreen(nowDay.index); final int offset = nowDay.scrollView.getHeight() / 2; nowDay.nowView.requestRectangleOnScreen(new Rect(0, offset, 0, offset), true); nowDay.blocksView.requestLayout(); return true; } return false; } public void onScrollChanged(ObservableScrollView view) { // Keep each day view at the same vertical scroll offset. final int scrollY = view.getScrollY(); for (Day day : mDays) { if (day.scrollView != view) { day.scrollView.scrollTo(0, scrollY); } } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.schedule_menu_items, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_now) { if (!updateNowView(true)) { Toast.makeText(getActivity(), R.string.toast_now_not_visible, Toast.LENGTH_SHORT).show(); } return true; } return super.onOptionsItemSelected(item); } private ContentObserver mSessionChangesObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { requery(); } }; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive time update"); updateNowView(false); } }; private interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.SESSIONS_COUNT, ScheduleContract.Blocks.CONTAINS_STARRED, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int SESSIONS_COUNT = 6; int CONTAINS_STARRED = 7; } }
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.ui.phone.ScheduleActivity; import com.google.android.apps.iosched.ui.tablet.ScheduleMultiPaneActivity; import com.google.android.apps.iosched.ui.tablet.SessionsMultiPaneActivity; import com.google.android.apps.iosched.ui.tablet.VendorsMultiPaneActivity; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class DashboardFragment extends Fragment { public void fireTrackerEvent(String label) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Home Screen Dashboard", "Click", label, 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_dashboard, container); // Attach event handlers root.findViewById(R.id.home_btn_schedule).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Schedule"); if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), ScheduleMultiPaneActivity.class)); } else { startActivity(new Intent(getActivity(), ScheduleActivity.class)); } } }); root.findViewById(R.id.home_btn_sessions).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Sessions"); // Launch sessions list if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), SessionsMultiPaneActivity.class)); } else { final Intent intent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.title_session_tracks)); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_SESSIONS); startActivity(intent); } } }); root.findViewById(R.id.home_btn_starred).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Starred"); // Launch list of sessions and vendors the user has starred startActivity(new Intent(getActivity(), StarredActivity.class)); } }); root.findViewById(R.id.home_btn_vendors).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Sandbox"); // Launch vendors list if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), VendorsMultiPaneActivity.class)); } else { final Intent intent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.title_vendor_tracks)); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_VENDORS); startActivity(intent); } } }); root.findViewById(R.id.home_btn_map).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Launch map of conference venue fireTrackerEvent("Map"); startActivity(new Intent(getActivity(), UIUtils.getMapActivityClass(getActivity()))); } }); root.findViewById(R.id.home_btn_announcements).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { // splicing in tag streamer fireTrackerEvent("Bulletin"); Intent intent = new Intent(getActivity(), BulletinActivity.class); startActivity(intent); } }); return root; } }
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.provider.ScheduleContract.Rooms; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.ParserUtils; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; 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.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; /** * Shows a {@link WebView} with a map of the conference venue. */ public class MapFragment extends Fragment { private static final String TAG = "MapFragment"; /** * When specified, will automatically point the map to the requested room. */ public static final String EXTRA_ROOM = "com.google.android.iosched.extra.ROOM"; private static final String MAP_JSI_NAME = "MAP_CONTAINER"; private static final String MAP_URL = "http://www.google.com/events/io/2011/embed.html"; private static boolean CLEAR_CACHE_ON_LOAD = false; private WebView mWebView; private View mLoadingSpinner; private boolean mMapInitialized = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Map"); } @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.setWebChromeClient(mWebChromeClient); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable() { public void run() { // Initialize web view if (CLEAR_CACHE_ON_LOAD) { mWebView.clearCache(true); } mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); mWebView.loadUrl(MAP_URL); mWebView.addJavascriptInterface(mMapJsiImpl, MAP_JSI_NAME); } }); 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 void runJs(String js) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Loading javascript:" + js); } mWebView.loadUrl("javascript:" + js); } /** * Helper method to escape JavaScript strings. Useful when passing strings to a WebView via * "javascript:" calls. */ private static String escapeJsString(String s) { if (s == null) { return ""; } return s.replace("'", "\\'").replace("\"", "\\\""); } public void panLeft(float screenFraction) { runJs("IoMap.panLeft('" + screenFraction + "');"); } /** * I/O Conference Map JavaScript interface. */ private interface MapJsi { void openContentInfo(String test); void onMapReady(); } private WebChromeClient mWebChromeClient = new WebChromeClient() { public void onConsoleMessage(String message, int lineNumber, String sourceID) { Log.i(TAG, "JS Console message: (" + sourceID + ": " + lineNumber + ") " + message); } }; 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 void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Log.e(TAG, "Error " + errorCode + ": " + description); Toast.makeText(view.getContext(), "Error " + errorCode + ": " + description, Toast.LENGTH_LONG).show(); super.onReceivedError(view, errorCode, description, failingUrl); } }; private MapJsi mMapJsiImpl = new MapJsi() { public void openContentInfo(String roomId) { final String possibleTrackId = ParserUtils.translateTrackIdAlias(roomId); final Intent intent; if (ParserUtils.LOCAL_TRACK_IDS.contains(possibleTrackId)) { // This is a track; open up the sandbox for the track, since room IDs that are // track IDs are sandbox areas in the map. Uri trackVendorsUri = ScheduleContract.Tracks.buildVendorsUri(possibleTrackId); intent = new Intent(Intent.ACTION_VIEW, trackVendorsUri); } else { Uri roomUri = Rooms.buildSessionsDirUri(roomId); intent = new Intent(Intent.ACTION_VIEW, roomUri); } getActivity().runOnUiThread(new Runnable() { public void run() { ((BaseActivity) getActivity()).openActivityOrFragment(intent); } }); } public void onMapReady() { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "onMapReady"); } final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); String showRoomId = null; if (!mMapInitialized && intent.hasExtra(EXTRA_ROOM)) { showRoomId = intent.getStringExtra(EXTRA_ROOM); } if (showRoomId != null) { runJs("IoMap.showLocationById('" + escapeJsString(showRoomId) + "');"); } mMapInitialized = 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 BulletinActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new BulletinFragment(); } @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.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.BitmapUtils; import com.google.android.apps.iosched.util.CatchNotesHelper; import com.google.android.apps.iosched.util.FractionalTouchDelegate; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.UIUtils; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.RectF; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.StyleSpan; import android.util.Log; 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.widget.CompoundButton; import android.widget.ImageView; import android.widget.TabHost; import android.widget.TextView; /** * A fragment that shows detail information for a session, including session title, abstract, * time information, speaker photos and bios, etc. */ public class SessionDetailFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, CompoundButton.OnCheckedChangeListener { private static final String TAG = "SessionDetailFragment"; /** * Since sessions can belong tracks, the parent activity can send this extra specifying a * track URI that should be used for coloring the title-bar. */ public static final String EXTRA_TRACK = "com.google.android.iosched.extra.TRACK"; private static final String TAG_SUMMARY = "summary"; private static final String TAG_NOTES = "notes"; private static final String TAG_LINKS = "links"; private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD); private String mSessionId; private Uri mSessionUri; private Uri mTrackUri; private String mTitleString; private String mHashtag; private String mUrl; private TextView mTagDisplay; private String mRoomId; private ViewGroup mRootView; private TabHost mTabHost; private TextView mTitle; private TextView mSubtitle; private CompoundButton mStarred; private TextView mAbstract; private TextView mRequirements; private NotifyingAsyncQueryHandler mHandler; private boolean mSessionCursor = false; private boolean mSpeakersCursor = false; private boolean mHasSummaryContent = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSessionUri = intent.getData(); mTrackUri = resolveTrackUri(intent); if (mSessionUri == null) { return; } mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); updateNotesTab(); // Start listening for time updates to adjust "now" bar. TIME_TICK is // triggered once per minute, which is how we move the bar over time. final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addAction(Intent.ACTION_PACKAGE_REPLACED); filter.addDataScheme("package"); getActivity().registerReceiver(mPackageChangesReceiver, filter); } @Override public void onPause() { super.onPause(); getActivity().unregisterReceiver(mPackageChangesReceiver); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mSessionUri == null) { return; } // Start background queries to load session and track details final Uri speakersUri = ScheduleContract.Sessions.buildSpeakersDirUri(mSessionId); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mHandler.startQuery(SessionsQuery._TOKEN, mSessionUri, SessionsQuery.PROJECTION); mHandler.startQuery(TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION); mHandler.startQuery(SpeakersQuery._TOKEN, speakersUri, SpeakersQuery.PROJECTION); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_detail, null); mTabHost = (TabHost) mRootView.findViewById(android.R.id.tabhost); mTabHost.setup(); mTitle = (TextView) mRootView.findViewById(R.id.session_title); mSubtitle = (TextView) mRootView.findViewById(R.id.session_subtitle); mStarred = (CompoundButton) mRootView.findViewById(R.id.star_button); mStarred.setFocusable(true); mStarred.setClickable(true); // Larger target triggers star toggle final View starParent = mRootView.findViewById(R.id.header_session); FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f)); mAbstract = (TextView) mRootView.findViewById(R.id.session_abstract); mRequirements = (TextView) mRootView.findViewById(R.id.session_requirements); setupSummaryTab(); setupNotesTab(); setupLinksTab(); return mRootView; } /** * Build and add "summary" tab. */ private void setupSummaryTab() { // Summary content comes from existing layout mTabHost.addTab(mTabHost.newTabSpec(TAG_SUMMARY) .setIndicator(buildIndicator(R.string.session_summary)) .setContent(R.id.tab_session_summary)); } /** * Build a {@link View} to be used as a tab indicator, setting the requested string resource as * its label. * * @param textRes * @return View */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getActivity().getLayoutInflater() .inflate(R.layout.tab_indicator, (ViewGroup) mRootView.findViewById(android.R.id.tabs), false); indicator.setText(textRes); return indicator; } /** * Derive {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks#CONTENT_ITEM_TYPE} * {@link Uri} based on incoming {@link Intent}, using * {@link #EXTRA_TRACK} when set. * @param intent * @return Uri */ private Uri resolveTrackUri(Intent intent) { final Uri trackUri = intent.getParcelableExtra(EXTRA_TRACK); if (trackUri != null) { return trackUri; } else { return ScheduleContract.Sessions.buildTracksDirUri(mSessionId); } } /** * {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } if (token == SessionsQuery._TOKEN) { onSessionQueryComplete(cursor); } else if (token == TracksQuery._TOKEN) { onTrackQueryComplete(cursor); } else if (token == SpeakersQuery._TOKEN) { onSpeakersQueryComplete(cursor); } else { cursor.close(); } } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { try { mSessionCursor = true; if (!cursor.moveToFirst()) { return; } // 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 = UIUtils.formatSessionSubtitle(blockStart, blockEnd, roomName, getActivity()); mTitleString = cursor.getString(SessionsQuery.TITLE); mTitle.setText(mTitleString); mSubtitle.setText(subtitle); mUrl = cursor.getString(SessionsQuery.URL); if (TextUtils.isEmpty(mUrl)) { mUrl = ""; } mHashtag = cursor.getString(SessionsQuery.HASHTAG); mTagDisplay = (TextView) mRootView.findViewById(R.id.session_tags_button); if (!TextUtils.isEmpty(mHashtag)) { // Create the button text SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(getString(R.string.tag_stream) + " "); int boldStart = sb.length(); sb.append(getHashtagsString()); sb.setSpan(sBoldSpan, boldStart, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mTagDisplay.setText(sb); mTagDisplay.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(getActivity(), TagStreamActivity.class); intent.putExtra(TagStreamFragment.EXTRA_QUERY, getHashtagsString()); startActivity(intent); } }); } else { mTagDisplay.setVisibility(View.GONE); } mRoomId = cursor.getString(SessionsQuery.ROOM_ID); // Unregister around setting checked state to avoid triggering // listener since change isn't user generated. mStarred.setOnCheckedChangeListener(null); mStarred.setChecked(cursor.getInt(SessionsQuery.STARRED) != 0); mStarred.setOnCheckedChangeListener(this); final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT); if (!TextUtils.isEmpty(sessionAbstract)) { UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract); mAbstract.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { mAbstract.setVisibility(View.GONE); } final View requirementsBlock = mRootView.findViewById(R.id.session_requirements_block); final String sessionRequirements = cursor.getString(SessionsQuery.REQUIREMENTS); if (!TextUtils.isEmpty(sessionRequirements)) { UIUtils.setTextMaybeHtml(mRequirements, sessionRequirements); requirementsBlock.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { requirementsBlock.setVisibility(View.GONE); } // Show empty message when all data is loaded, and nothing to show if (mSpeakersCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sessions/" + mTitleString); updateLinksTab(cursor); updateNotesTab(); } finally { cursor.close(); } } /** * 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(); activityHelper.setActionBarTitle(cursor.getString(TracksQuery.TRACK_NAME)); activityHelper.setActionBarColor(cursor.getInt(TracksQuery.TRACK_COLOR)); } finally { cursor.close(); } } private void onSpeakersQueryComplete(Cursor cursor) { try { mSpeakersCursor = true; // TODO: remove any existing speakers from layout, since this cursor // might be from a data change notification. final ViewGroup speakersGroup = (ViewGroup) mRootView.findViewById(R.id.session_speakers_block); final LayoutInflater inflater = getActivity().getLayoutInflater(); boolean hasSpeakers = false; while (cursor.moveToNext()) { final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME); if (TextUtils.isEmpty(speakerName)) { continue; } final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL); final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY); final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL); final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT); String speakerHeader = speakerName; if (!TextUtils.isEmpty(speakerCompany)) { speakerHeader += ", " + speakerCompany; } final View speakerView = inflater .inflate(R.layout.speaker_detail, speakersGroup, false); final TextView speakerHeaderView = (TextView) speakerView .findViewById(R.id.speaker_header); final ImageView speakerImgView = (ImageView) speakerView .findViewById(R.id.speaker_image); final TextView speakerUrlView = (TextView) speakerView .findViewById(R.id.speaker_url); final TextView speakerAbstractView = (TextView) speakerView .findViewById(R.id.speaker_abstract); if (!TextUtils.isEmpty(speakerImageUrl)) { BitmapUtils.fetchImage(getActivity(), speakerImageUrl, null, null, new BitmapUtils.OnFetchCompleteListener() { public void onFetchComplete(Object cookie, Bitmap result) { if (result != null) { speakerImgView.setImageBitmap(result); } } }); } speakerHeaderView.setText(speakerHeader); UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract); if (!TextUtils.isEmpty(speakerUrl)) { UIUtils.setTextMaybeHtml(speakerUrlView, speakerUrl); speakerUrlView.setVisibility(View.VISIBLE); } else { speakerUrlView.setVisibility(View.GONE); } speakersGroup.addView(speakerView); hasSpeakers = true; mHasSummaryContent = true; } speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE); // Show empty message when all data is loaded, and nothing to show if (mSessionCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } } finally { if (null != cursor) { cursor.close(); } } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.session_detail_menu_items, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { final String shareString; final Intent intent; switch (item.getItemId()) { case R.id.menu_map: intent = new Intent(getActivity().getApplicationContext(), UIUtils.getMapActivityClass(getActivity())); intent.putExtra(MapFragment.EXTRA_ROOM, mRoomId); startActivity(intent); return true; case R.id.menu_share: // TODO: consider bringing in shortlink to session shareString = getString(R.string.share_template, mTitleString, getHashtagsString(), mUrl); intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, shareString); startActivity(Intent.createChooser(intent, getText(R.string.title_share))); return true; } return super.onOptionsItemSelected(item); } /** * Handle toggling of starred checkbox. */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final ContentValues values = new ContentValues(); values.put(ScheduleContract.Sessions.SESSION_STARRED, isChecked ? 1 : 0); mHandler.startUpdate(mSessionUri, values); // Because change listener is set to null during initialization, these won't fire on // pageview. AnalyticsUtils.getInstance(getActivity()).trackEvent( "Sandbox", isChecked ? "Starred" : "Unstarred", mTitleString, 0); } /** * Build and add "notes" tab. */ private void setupNotesTab() { // Make powered-by clickable ((TextView) mRootView.findViewById(R.id.notes_powered_by)).setMovementMethod( LinkMovementMethod.getInstance()); // Setup tab mTabHost.addTab(mTabHost.newTabSpec(TAG_NOTES) .setIndicator(buildIndicator(R.string.session_notes)) .setContent(R.id.tab_session_notes)); } /* * Event structure: * Category -> "Session Details" * Action -> "Create Note", "View Note", etc * Label -> Session's Title * Value -> 0. */ public void fireNotesEvent(int actionId) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Session Details", getActivity().getString(actionId), mTitleString, 0); } /* * Event structure: * Category -> "Session Details" * Action -> Link Text * Label -> Session's Title * Value -> 0. */ public void fireLinkEvent(int actionId) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Link Details", getActivity().getString(actionId), mTitleString, 0); } private void updateNotesTab() { final CatchNotesHelper helper = new CatchNotesHelper(getActivity()); final boolean notesInstalled = helper.isNotesInstalledAndMinimumVersion(); final Intent marketIntent = helper.notesMarketIntent(); final Intent newIntent = helper.createNoteIntent( getString(R.string.note_template, mTitleString, getHashtagsString())); final Intent viewIntent = helper.viewNotesIntent(getHashtagsString()); // Set icons and click listeners ((ImageView) mRootView.findViewById(R.id.notes_catch_market_icon)).setImageDrawable( UIUtils.getIconForIntent(getActivity(), marketIntent)); ((ImageView) mRootView.findViewById(R.id.notes_catch_new_icon)).setImageDrawable( UIUtils.getIconForIntent(getActivity(), newIntent)); ((ImageView) mRootView.findViewById(R.id.notes_catch_view_icon)).setImageDrawable( UIUtils.getIconForIntent(getActivity(), viewIntent)); // Set click listeners mRootView.findViewById(R.id.notes_catch_market_link).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(marketIntent); fireNotesEvent(R.string.notes_catch_market_title); } }); mRootView.findViewById(R.id.notes_catch_new_link).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(newIntent); fireNotesEvent(R.string.notes_catch_new_title); } }); mRootView.findViewById(R.id.notes_catch_view_link).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(viewIntent); fireNotesEvent(R.string.notes_catch_view_title); } }); // Show/hide elements mRootView.findViewById(R.id.notes_catch_market_link).setVisibility( notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_market_separator).setVisibility( notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_new_link).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_new_separator).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_view_link).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_view_separator).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); } /** * Build and add "summary" tab. */ private void setupLinksTab() { // Summary content comes from existing layout mTabHost.addTab(mTabHost.newTabSpec(TAG_LINKS) .setIndicator(buildIndicator(R.string.session_links)) .setContent(R.id.tab_session_links)); } private void updateLinksTab(Cursor cursor) { ViewGroup container = (ViewGroup) mRootView.findViewById(R.id.links_container); // Remove all views but the 'empty' view int childCount = container.getChildCount(); if (childCount > 1) { container.removeViews(1, childCount - 1); } LayoutInflater inflater = getLayoutInflater(null); boolean hasLinks = false; for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) { final String url = cursor.getString(SessionsQuery.LINKS_INDICES[i]); if (!TextUtils.isEmpty(url)) { hasLinks = true; ViewGroup linkContainer = (ViewGroup) inflater.inflate(R.layout.list_item_session_link, container, false); ((TextView) linkContainer.findViewById(R.id.link_text)).setText( SessionsQuery.LINKS_TITLES[i]); final int linkTitleIndex = i; linkContainer.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireLinkEvent(SessionsQuery.LINKS_TITLES[linkTitleIndex]); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } }); container.addView(linkContainer); // Create separator View separatorView = new ImageView(getActivity()); separatorView.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); separatorView.setBackgroundResource(android.R.drawable.divider_horizontal_bright); container.addView(separatorView); } } container.findViewById(R.id.empty_links).setVisibility(hasLinks ? View.GONE : View.VISIBLE); } private String getHashtagsString() { if (!TextUtils.isEmpty(mHashtag)) { return TagStreamFragment.CONFERENCE_HASHTAG + " #" + mHashtag; } else { return TagStreamFragment.CONFERENCE_HASHTAG; } } private BroadcastReceiver mPackageChangesReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateNotesTab(); } }; /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Sessions.SESSION_LEVEL, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_REQUIREMENTS, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SESSION_HASHTAG, ScheduleContract.Sessions.SESSION_SLUG, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_MODERATOR_URL, ScheduleContract.Sessions.SESSION_YOUTUBE_URL, ScheduleContract.Sessions.SESSION_PDF_URL, ScheduleContract.Sessions.SESSION_FEEDBACK_URL, ScheduleContract.Sessions.SESSION_NOTES_URL, ScheduleContract.Sessions.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, }; int BLOCK_START = 0; int BLOCK_END = 1; int LEVEL = 2; int TITLE = 3; int ABSTRACT = 4; int REQUIREMENTS = 5; int STARRED = 6; int HASHTAG = 7; int SLUG = 8; int URL = 9; int MODERATOR_URL = 10; int YOUTUBE_URL = 11; int PDF_URL = 12; int FEEDBACK_URL = 13; int NOTES_URL = 14; int ROOM_ID = 15; int ROOM_NAME = 16; int[] LINKS_INDICES = { URL, MODERATOR_URL, YOUTUBE_URL, PDF_URL, FEEDBACK_URL, NOTES_URL, }; int[] LINKS_TITLES = { R.string.session_link_main, R.string.session_link_moderator, R.string.session_link_youtube, R.string.session_link_pdf, R.string.session_link_feedback, R.string.session_link_notes, }; } /** * {@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; } private interface SpeakersQuery { int _TOKEN = 0x3; String[] PROJECTION = { ScheduleContract.Speakers.SPEAKER_NAME, ScheduleContract.Speakers.SPEAKER_IMAGE_URL, ScheduleContract.Speakers.SPEAKER_COMPANY, ScheduleContract.Speakers.SPEAKER_ABSTRACT, ScheduleContract.Speakers.SPEAKER_URL, }; int SPEAKER_NAME = 0; int SPEAKER_IMAGE_URL = 1; int SPEAKER_COMPANY = 2; int SPEAKER_ABSTRACT = 3; int SPEAKER_URL = 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; import com.google.android.apps.iosched.ui.tablet.NowPlayingMultiPaneActivity; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.UIUtils; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * A fragment used in {@link HomeActivity} that shows either a countdown, 'now playing' link to * current sessions, or 'thank you' text, at different times (before/during/after the conference). * It also shows a 'Realtime Search' button on phones, as a replacement for the * {@link TagStreamFragment} that is visible on tablets on the home screen. */ public class WhatsOnFragment extends Fragment { private Handler mMessageHandler = new Handler(); private TextView mCountdownTextView; private ViewGroup mRootView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_whats_on, container); refresh(); return mRootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); mMessageHandler.removeCallbacks(mCountdownRunnable); } private void refresh() { mMessageHandler.removeCallbacks(mCountdownRunnable); mRootView.removeAllViews(); final long currentTimeMillis = UIUtils.getCurrentTime(getActivity()); // Show Loading... and load the view corresponding to the current state if (currentTimeMillis < UIUtils.CONFERENCE_START_MILLIS) { setupBefore(); } else if (currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS) { setupAfter(); } else { setupDuring(); } if (!UIUtils.isHoneycombTablet(getActivity())) { View separator = new View(getActivity()); separator.setLayoutParams( new ViewGroup.LayoutParams(1, ViewGroup.LayoutParams.FILL_PARENT)); separator.setBackgroundResource(R.drawable.whats_on_separator); mRootView.addView(separator); View view = getActivity().getLayoutInflater().inflate( R.layout.whats_on_stream, mRootView, false); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Home Screen Dashboard", "Click", "Realtime Stream", 0); Intent intent = new Intent(getActivity(), TagStreamActivity.class); startActivity(intent); } }); mRootView.addView(view); } } private void setupBefore() { // Before conference, show countdown. mCountdownTextView = (TextView) getActivity().getLayoutInflater().inflate( R.layout.whats_on_countdown, mRootView, false); mRootView.addView(mCountdownTextView); mMessageHandler.post(mCountdownRunnable); } private void setupAfter() { // After conference, show canned text. getActivity().getLayoutInflater().inflate( R.layout.whats_on_thank_you, mRootView, true); } private void setupDuring() { // Conference in progress, show "Now Playing" link. View view = getActivity().getLayoutInflater().inflate( R.layout.whats_on_now_playing, mRootView, false); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), NowPlayingMultiPaneActivity.class)); } else { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(ScheduleContract.Sessions .buildSessionsAtDirUri(System.currentTimeMillis())); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.title_now_playing)); startActivity(intent); } } }); mRootView.addView(view); } /** * Event that updates countdown timer. Posts itself again to {@link #mMessageHandler} to * continue updating time. */ private Runnable mCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (UIUtils.CONFERENCE_START_MILLIS - System.currentTimeMillis()) / 1000); final boolean conferenceStarted = remainingSec == 0; if (conferenceStarted) { // Conference started while in countdown mode, switch modes and // bail on future countdown updates. mMessageHandler.postDelayed(new Runnable() { public void run() { refresh(); } }, 100); return; } final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str = getResources().getQuantityString( R.plurals.whats_on_countdown_title, days, days, DateUtils.formatElapsedTime(secs)); mCountdownTextView.setText(str); // Repost ourselves to keep updating countdown mMessageHandler.postDelayed(mCountdownRunnable, 1000); } }; }
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.BitmapUtils; import com.google.android.apps.iosched.util.FractionalTouchDelegate; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; 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.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; /** * A fragment that shows detail information for a sandbox company, including company name, * description, product description, logo, etc. */ public class VendorDetailFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, CompoundButton.OnCheckedChangeListener { private static final String TAG = "VendorDetailFragment"; private Uri mVendorUri; private String mTrackId; private ViewGroup mRootView; private TextView mName; private CompoundButton mStarred; private ImageView mLogo; private TextView mUrl; private TextView mDesc; private TextView mProductDesc; private String mNameString; private NotifyingAsyncQueryHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mVendorUri = intent.getData(); if (mVendorUri== null) { return; } setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mVendorUri == null) { return; } // Start background query to load vendor details mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mHandler.startQuery(mVendorUri, VendorsQuery.PROJECTION); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_vendor_detail, null); mName = (TextView) mRootView.findViewById(R.id.vendor_name); mStarred = (CompoundButton) mRootView.findViewById(R.id.star_button); mStarred.setFocusable(true); mStarred.setClickable(true); // Larger target triggers star toggle final View starParent = mRootView.findViewById(R.id.header_vendor); FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f)); mLogo = (ImageView) mRootView.findViewById(R.id.vendor_logo); mUrl = (TextView) mRootView.findViewById(R.id.vendor_url); mDesc = (TextView) mRootView.findViewById(R.id.vendor_desc); mProductDesc = (TextView) mRootView.findViewById(R.id.vendor_product_desc); return mRootView; } /** * Build a {@link android.view.View} to be used as a tab indicator, setting the requested string resource as * its label. * * @return View */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getActivity().getLayoutInflater() .inflate(R.layout.tab_indicator, (ViewGroup) mRootView.findViewById(android.R.id.tabs), false); indicator.setText(textRes); return indicator; } /** * {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } try { if (!cursor.moveToFirst()) { return; } mNameString = cursor.getString(VendorsQuery.NAME); mName.setText(mNameString); // Unregister around setting checked state to avoid triggering // listener since change isn't user generated. mStarred.setOnCheckedChangeListener(null); mStarred.setChecked(cursor.getInt(VendorsQuery.STARRED) != 0); mStarred.setOnCheckedChangeListener(this); // Start background fetch to load vendor logo final String logoUrl = cursor.getString(VendorsQuery.LOGO_URL); if (!TextUtils.isEmpty(logoUrl)) { BitmapUtils.fetchImage(getActivity(), logoUrl, null, null, new BitmapUtils.OnFetchCompleteListener() { public void onFetchComplete(Object cookie, Bitmap result) { if (result == null) { mLogo.setVisibility(View.GONE); } else { mLogo.setVisibility(View.VISIBLE); mLogo.setImageBitmap(result); } } }); } mUrl.setText(cursor.getString(VendorsQuery.URL)); mDesc.setText(cursor.getString(VendorsQuery.DESC)); mProductDesc.setText(cursor.getString(VendorsQuery.PRODUCT_DESC)); mTrackId = cursor.getString(VendorsQuery.TRACK_ID); // Assign track details when found // TODO: handle vendors not attached to track ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); activityHelper.setActionBarTitle(cursor.getString(VendorsQuery.TRACK_NAME)); activityHelper.setActionBarColor(cursor.getInt(VendorsQuery.TRACK_COLOR)); AnalyticsUtils.getInstance(getActivity()).trackPageView( "/Sandbox/Vendors/" + mNameString); } finally { cursor.close(); } } /** * Handle toggling of starred checkbox. */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final ContentValues values = new ContentValues(); values.put(ScheduleContract.Vendors.VENDOR_STARRED, isChecked ? 1 : 0); mHandler.startUpdate(mVendorUri, values); AnalyticsUtils.getInstance(getActivity()).trackEvent( "Sandbox", isChecked ? "Starred" : "Unstarred", mNameString, 0); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.map_menu_items, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_map) { // The room ID for the sandbox, in the map, is just the track ID final Intent intent = new Intent(getActivity().getApplicationContext(), UIUtils.getMapActivityClass(getActivity())); intent.putExtra(MapFragment.EXTRA_ROOM, ParserUtils.translateTrackIdAliasInverse(mTrackId)); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} query parameters. */ private interface VendorsQuery { String[] PROJECTION = { ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.VENDOR_LOCATION, ScheduleContract.Vendors.VENDOR_DESC, ScheduleContract.Vendors.VENDOR_URL, ScheduleContract.Vendors.VENDOR_PRODUCT_DESC, ScheduleContract.Vendors.VENDOR_LOGO_URL, ScheduleContract.Vendors.VENDOR_STARRED, ScheduleContract.Vendors.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int NAME = 0; int LOCATION = 1; int DESC = 2; int URL = 3; int PRODUCT_DESC = 4; int LOGO_URL = 5; int STARRED = 6; int TRACK_ID = 7; int TRACK_NAME = 8; int TRACK_COLOR = 9; } }
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.service.SyncService; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.DetachableResultReceiver; import com.google.android.apps.iosched.util.EulaHelper; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; /** * Front-door {@link Activity} that displays high-level features the schedule application offers to * users. Depending on whether the device is a phone or an Android 3.0+ tablet, different layouts * will be used. For example, on a phone, the primary content is a {@link DashboardFragment}, * whereas on a tablet, both a {@link DashboardFragment} and a {@link TagStreamFragment} are * displayed. */ public class HomeActivity extends BaseActivity { private static final String TAG = "HomeActivity"; private TagStreamFragment mTagStreamFragment; private SyncStatusUpdaterFragment mSyncStatusUpdaterFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!EulaHelper.hasAcceptedEula(this)) { EulaHelper.showEula(false, this); } AnalyticsUtils.getInstance(this).trackPageView("/Home"); setContentView(R.layout.activity_home); getActivityHelper().setupActionBar(null, 0); FragmentManager fm = getSupportFragmentManager(); mTagStreamFragment = (TagStreamFragment) fm.findFragmentById(R.id.fragment_tag_stream); mSyncStatusUpdaterFragment = (SyncStatusUpdaterFragment) fm .findFragmentByTag(SyncStatusUpdaterFragment.TAG); if (mSyncStatusUpdaterFragment == null) { mSyncStatusUpdaterFragment = new SyncStatusUpdaterFragment(); fm.beginTransaction().add(mSyncStatusUpdaterFragment, SyncStatusUpdaterFragment.TAG).commit(); triggerRefresh(); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupHomeActivity(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.refresh_menu_items, menu); super.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { triggerRefresh(); return true; } return super.onOptionsItemSelected(item); } private void triggerRefresh() { final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, SyncService.class); intent.putExtra(SyncService.EXTRA_STATUS_RECEIVER, mSyncStatusUpdaterFragment.mReceiver); startService(intent); if (mTagStreamFragment != null) { mTagStreamFragment.refresh(); } } private void updateRefreshStatus(boolean refreshing) { getActivityHelper().setRefreshActionButtonCompatState(refreshing); } /** * A non-UI fragment, retained across configuration changes, that updates its activity's UI * when sync status changes. */ public static class SyncStatusUpdaterFragment extends Fragment implements DetachableResultReceiver.Receiver { public static final String TAG = SyncStatusUpdaterFragment.class.getName(); private boolean mSyncing = false; private DetachableResultReceiver mReceiver; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); mReceiver = new DetachableResultReceiver(new Handler()); mReceiver.setReceiver(this); } /** {@inheritDoc} */ public void onReceiveResult(int resultCode, Bundle resultData) { HomeActivity activity = (HomeActivity) getActivity(); if (activity == null) { return; } switch (resultCode) { case SyncService.STATUS_RUNNING: { mSyncing = true; break; } case SyncService.STATUS_FINISHED: { mSyncing = false; break; } case SyncService.STATUS_ERROR: { // Error happened down in SyncService, show as toast. mSyncing = false; final String errorText = getString(R.string.toast_sync_error, resultData .getString(Intent.EXTRA_TEXT)); Toast.makeText(activity, errorText, Toast.LENGTH_LONG).show(); break; } } activity.updateRefreshStatus(mSyncing); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ((HomeActivity) getActivity()).updateRefreshStatus(mSyncing); } } }
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.Sessions; 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 android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; /** * An activity that shows currently playing sessions in a two-pane view. */ public class NowPlayingMultiPaneActivity extends BaseMultiPaneActivity { private SessionsFragment mSessionsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(); intent.setData(Sessions.buildSessionsAtDirUri(System.currentTimeMillis())); setContentView(R.layout.activity_now_playing); 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_container_sessions, mSessionsFragment, "sessions") .commit(); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById( R.id.fragment_container_now_playing_detail); if (detailContainer != null && detailContainer.getChildCount() > 1) { findViewById(android.R.id.empty).setVisibility(View.GONE); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch( String activityClassName) { 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_now_playing_detail); } return null; } private void clearSelectedItems() { if (mSessionsFragment != null) { mSessionsFragment.clearCheckedPosition(); } } }
Java