code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Menu; import android.view.MenuItem; import android.widget.SearchView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.util.UIUtils; public class SessionsActivity extends SimpleSinglePaneActivity implements SessionsFragment.Callbacks { @Override protected Fragment onCreatePane() { return new SessionsFragment(); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.search, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setQueryRefinementEnabled(true); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.ui.SandboxDetailFragment; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; public class SandboxDetailActivity extends SimpleSinglePaneActivity implements SandboxDetailFragment.Callbacks, TrackInfoHelperFragment.Callbacks, ImageLoader.ImageLoaderProvider { private String mTrackId = null; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImageLoader = new ImageLoader(this, R.drawable.sandbox_logo_empty) .setMaxImageSize(getResources().getDimensionPixelSize( R.dimen.sandbox_company_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); } @Override protected Fragment onCreatePane() { return new SandboxDetailFragment(); } @Override public Intent getParentActivityIntent() { // Up to this company's track details, or Home if no track is available if (mTrackId != null) { return new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { return new Intent(this, HomeActivity.class); } } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { mTrackId = trackId; setTitle(track.name); setActionBarTrackIcon(track.name, track.color); } @Override public void onTrackIdAvailable(final String trackId) { new Handler().post(new Runnable() { @Override public void run() { FragmentManager fm = getSupportFragmentManager(); if (fm.findFragmentByTag("track_info") == null) { fm.beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri( ScheduleContract.Tracks.buildTrackUri(trackId)), "track_info") .commit(); } } }); } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.content.Intent; import android.support.v4.app.Fragment; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; public class MapActivity extends SimpleSinglePaneActivity implements MapFragment.Callbacks { @Override protected Fragment onCreatePane() { return new MapFragment(); } @Override public void onSessionRoomSelected(String roomId, String roomTitle) { Intent roomIntent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Rooms.buildSessionsDirUri(roomId)); roomIntent.putExtra(Intent.EXTRA_TITLE, roomTitle); startActivity(roomIntent); } @Override public void onSandboxRoomSelected(String trackId, String roomTitle) { Intent intent = new Intent(this,TrackDetailActivity.class); intent.setData( ScheduleContract.Tracks.buildSandboxUri(trackId)); intent.putExtra(Intent.EXTRA_TITLE, roomTitle); startActivity(intent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.view.Menu; import android.view.MenuItem; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.provider.ScheduleContract.Sessions.QUERY_PARAMETER_FILTER; import static com.google.android.apps.iosched.provider.ScheduleContract.Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY; import static com.google.android.apps.iosched.provider.ScheduleContract.Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY; import static com.google.android.apps.iosched.util.LogUtils.LOGD; public class TrackDetailActivity extends BaseActivity implements ActionBar.TabListener, ViewPager.OnPageChangeListener, SessionsFragment.Callbacks, SandboxFragment.Callbacks, TrackInfoHelperFragment.Callbacks { private static final int TAB_SESSIONS = 100; private static final int TAB_OFFICE_HOURS = 101; private static final int TAB_SANDBOX = 102; private ViewPager mViewPager; private String mTrackId; private String mHashtag; private List<Integer> mTabs = new ArrayList<Integer>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_track_detail); Uri trackUri = getIntent().getData(); mTrackId = ScheduleContract.Tracks.getTrackId(trackUri); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(new TrackDetailPagerAdapter(getSupportFragmentManager())); mViewPager.setOnPageChangeListener(this); mViewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); mViewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width)); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromTrackUri(trackUri), "track_info") .commit(); } } @Override public Intent getParentActivityIntent() { return new Intent(this, HomeActivity.class) .putExtra(HomeActivity.EXTRA_DEFAULT_TAB, HomeActivity.TAB_EXPLORE); } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int position) { getSupportActionBar().setSelectedNavigationItem(position); int titleId = -1; switch (position) { case 0: titleId = R.string.title_sessions; break; case 1: titleId = R.string.title_office_hours; break; case 2: titleId = R.string.title_sandbox; break; } String title = getString(titleId); EasyTracker.getTracker().sendView(title + ": " + getTitle()); LOGD("Tracker", title + ": " + getTitle()); } @Override public void onPageScrollStateChanged(int i) { } private class TrackDetailPagerAdapter extends FragmentPagerAdapter { public TrackDetailPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { boolean allTracks = (ScheduleContract.Tracks.ALL_TRACK_ID.equals(mTrackId)); switch (mTabs.get(position)) { case TAB_SESSIONS: { Fragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, (allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(mTrackId)) .buildUpon() .appendQueryParameter(QUERY_PARAMETER_FILTER, QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY) .build() ))); return fragment; } case TAB_OFFICE_HOURS: { Fragment fragment = new SessionsFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, (allTracks ? ScheduleContract.Sessions.CONTENT_URI : ScheduleContract.Tracks.buildSessionsUri(mTrackId)) .buildUpon() .appendQueryParameter(QUERY_PARAMETER_FILTER, QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY) .build()))); return fragment; } case TAB_SANDBOX: default: { Fragment fragment = new SandboxFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(new Intent( Intent.ACTION_VIEW, allTracks ? ScheduleContract.Sandbox.CONTENT_URI : ScheduleContract.Tracks.buildSandboxUri(mTrackId)))); return fragment; } } } @Override public int getCount() { return mTabs.size(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.track_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_social_stream: Intent intent = new Intent(this, SocialStreamActivity.class); intent.putExtra(SocialStreamFragment.EXTRA_QUERY, UIUtils.getSessionHashtagsString(mHashtag)); startActivity(intent); break; } return super.onOptionsItemSelected(item); } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { setTitle(track.name); setActionBarTrackIcon(track.name, track.color); mHashtag = track.hashtag; switch (track.meta) { case ScheduleContract.Tracks.TRACK_META_SESSIONS_ONLY: mTabs.add(TAB_SESSIONS); break; case ScheduleContract.Tracks.TRACK_META_SANDBOX_OFFICE_HOURS_ONLY: mTabs.add(TAB_OFFICE_HOURS); mTabs.add(TAB_SANDBOX); break; case ScheduleContract.Tracks.TRACK_META_OFFICE_HOURS_ONLY: mTabs.add(TAB_OFFICE_HOURS); break; case ScheduleContract.Tracks.TRACK_META_NONE: default: mTabs.add(TAB_SESSIONS); mTabs.add(TAB_OFFICE_HOURS); mTabs.add(TAB_SANDBOX); break; } mViewPager.getAdapter().notifyDataSetChanged(); if (mTabs.size() > 1) { setHasTabs(); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); for (int tab : mTabs) { int titleResId; switch (tab) { case TAB_SANDBOX: titleResId = R.string.title_sandbox; break; case TAB_OFFICE_HOURS: titleResId = R.string.title_office_hours; break; case TAB_SESSIONS: default: titleResId = R.string.title_sessions; break; } actionBar.addTab(actionBar.newTab().setText(titleResId).setTabListener(this)); } } } @Override public boolean onSessionSelected(String sessionId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(sessionId))); return false; } @Override public boolean onCompanySelected(String companyId) { startActivity(new Intent(Intent.ACTION_VIEW, ScheduleContract.Sandbox.buildCompanyUri(companyId))); return false; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.apps.iosched.ui.phone; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.TaskStackBuilder; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.*; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; public class SessionDetailActivity extends SimpleSinglePaneActivity implements TrackInfoHelperFragment.Callbacks, ImageLoader.ImageLoaderProvider { private String mTrackId = null; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { UIUtils.tryTranslateHttpIntent(this); BeamUtils.tryUpdateIntentFromBeam(this); super.onCreate(savedInstanceState); if (savedInstanceState == null) { Uri sessionUri = getIntent().getData(); BeamUtils.setBeamSessionUri(this, sessionUri); getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromSessionUri(sessionUri), "track_info") .commit(); } mImageLoader = new ImageLoader(this, R.drawable.person_image_empty) .setMaxImageSize(getResources().getDimensionPixelSize(R.dimen.speaker_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); } @Override protected Fragment onCreatePane() { return new SessionDetailFragment(); } @Override public Intent getParentActivityIntent() { // Up to this session's track details, or Home if no track is available if (mTrackId != null) { return new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.buildTrackUri(mTrackId)); } else { return new Intent(this, HomeActivity.class); } } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { mTrackId = trackId; setTitle(track.name); setActionBarTrackIcon(track.name, track.color); } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
Java
/* * Copyright 2012 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.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Feedback; import com.google.android.apps.iosched.util.AccountUtils; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesClient; import com.google.android.gms.plus.PlusClient; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.*; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.SeekBar; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that lets the user submit feedback about a given session. */ public class SessionFeedbackFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener { private static final String TAG = makeLogTag(SessionDetailFragment.class); // Set this boolean extra to true to show a variable height header public static final String EXTRA_VARIABLE_HEIGHT_HEADER = "com.google.android.iosched.extra.VARIABLE_HEIGHT_HEADER"; private String mSessionId; private Uri mSessionUri; private String mTitleString; private TextView mTitle; private PlusClient mPlusClient; private boolean mVariableHeightHeader = false; private RatingBarHelper mSessionRatingFeedbackBar; private RatingBarHelper mQ1FeedbackBar; private RatingBarHelper mQ2FeedbackBar; private RatingBarHelper mQ3FeedbackBar; private RadioGroup mQ4RadioGroup; private EditText mComments; public SessionFeedbackFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final String chosenAccountName = AccountUtils.getChosenAccountName(getActivity()); mPlusClient = new PlusClient.Builder(getActivity(), this, this) .clearScopes() .setAccountName(chosenAccountName) .build(); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSessionUri = intent.getData(); if (mSessionUri == null) { return; } mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri); mVariableHeightHeader = intent.getBooleanExtra(EXTRA_VARIABLE_HEIGHT_HEADER, false); LoaderManager manager = getLoaderManager(); manager.restartLoader(0, null, this); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_feedback, null); mTitle = (TextView) rootView.findViewById(R.id.session_title); mSessionRatingFeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_rating_container)); mQ1FeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_feedback_q1_container)); mQ2FeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_feedback_q2_container)); mQ3FeedbackBar = RatingBarHelper.create(rootView.findViewById( R.id.session_feedback_q3_container)); mQ4RadioGroup = (RadioGroup) rootView.findViewById(R.id.session_feedback_q4); mComments = (EditText) rootView.findViewById(R.id.session_feedback_comments); if (mVariableHeightHeader) { View headerView = rootView.findViewById(R.id.header_session); ViewGroup.LayoutParams layoutParams = headerView.getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT; headerView.setLayoutParams(layoutParams); } rootView.findViewById(R.id.submit_feedback_button).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { submitAllFeedback(); EasyTracker.getTracker().sendEvent("Session", "Feedback", mTitleString, 0L); LOGD("Tracker", "Feedback: " + mTitleString); getActivity().finish(); } }); return rootView; } @Override public void onStart() { super.onStart(); mPlusClient.connect(); } @Override public void onStop() { super.onStop(); mPlusClient.disconnect(); } @Override public void onConnected(Bundle connectionHint) { } @Override public void onDisconnected() { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { // Don't show an error just for the +1 button. Google Play services errors // should be caught at a higher level in the app } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { if (!cursor.moveToFirst()) { return; } mTitleString = cursor.getString(SessionsQuery.TITLE); // Format time block this session occupies mTitle.setText(mTitleString); EasyTracker.getTracker().sendView("Feedback: " + mTitleString); LOGD("Tracker", "Feedback: " + mTitleString); } /* ALL THE FEEDBACKS */ void submitAllFeedback() { int rating = mSessionRatingFeedbackBar.getValue() + 1; int q1Answer = mQ1FeedbackBar.getValue() + 1; int q2Answer = mQ2FeedbackBar.getValue() + 1; int q3Answer = mQ3FeedbackBar.getValue() + 1; // Don't add +1, since this is effectively a boolean. index 0 = false, 1 = true, // -1 means no answer was given. int q4Answer = getCheckedRadioIndex(mQ4RadioGroup); String comments = mComments.getText().toString(); String answers = mSessionId + ", " + rating + ", " + q1Answer + ", " + q2Answer + ", " + q3Answer + ", " + q4Answer + ", " + comments; LOGD(TAG, answers); ContentValues values = new ContentValues(); values.put(Feedback.SESSION_ID, mSessionId); values.put(Feedback.UPDATED, System.currentTimeMillis()); values.put(Feedback.SESSION_RATING, rating); values.put(Feedback.ANSWER_RELEVANCE, q1Answer); values.put(Feedback.ANSWER_CONTENT, q2Answer); values.put(Feedback.ANSWER_SPEAKER, q3Answer); values.put(Feedback.ANSWER_WILLUSE, q4Answer); values.put(Feedback.COMMENTS, comments); getActivity().getContentResolver() .insert(ScheduleContract.Feedback.buildFeedbackUri(mSessionId), values); } int getCheckedRadioIndex(RadioGroup rg) { int radioId = rg.getCheckedRadioButtonId(); View rb = rg.findViewById(radioId); return rg.indexOfChild(rb); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mSessionUri, SessionsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (!isAdded()) { return; } onSessionQueryComplete(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) {} /** * Helper class for building a rating bar from a {@link SeekBar}. */ private static class RatingBarHelper implements SeekBar.OnSeekBarChangeListener { private SeekBar mBar; private boolean mTrackingTouch; private TextView[] mLabels; public static RatingBarHelper create(View container) { return new RatingBarHelper(container); } private RatingBarHelper(View container) { // Force the seekbar to multiples of 100 mBar = (SeekBar) container.findViewById(R.id.rating_bar); mLabels = new TextView[]{ (TextView) container.findViewById(R.id.rating_bar_label_1), (TextView) container.findViewById(R.id.rating_bar_label_2), (TextView) container.findViewById(R.id.rating_bar_label_3), (TextView) container.findViewById(R.id.rating_bar_label_4), (TextView) container.findViewById(R.id.rating_bar_label_5), }; mBar.setMax(400); mBar.setProgress(200); onProgressChanged(mBar, 200, false); mBar.setOnSeekBarChangeListener(this); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int value = Math.round(progress / 100f); if (fromUser) { seekBar.setProgress(value * 100); } if (!mTrackingTouch) { for (int i = 0; i < mLabels.length; i++) { mLabels[i].setSelected(i == value); } } } @Override public void onStartTrackingTouch(SeekBar seekBar) { mTrackingTouch = true; for (TextView mLabel : mLabels) { mLabel.setSelected(false); } } @Override public void onStopTrackingTouch(SeekBar seekBar) { int value = getValue(); mTrackingTouch = false; for (int i = 0; i < mLabels.length; i++) { mLabels[i].setSelected(i == value); } } public int getValue() { return mBar.getProgress() / 100; } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { String[] PROJECTION = { ScheduleContract.Sessions.SESSION_TITLE, }; int TITLE = 0; } }
Java
/* * Copyright 2013 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.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.Checkable; import android.widget.LinearLayout; public class CheckableLinearLayout extends LinearLayout implements Checkable { private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked}; private boolean mChecked = false; public CheckableLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public boolean isChecked() { return mChecked; } public void setChecked(boolean b) { if (b != mChecked) { mChecked = b; refreshDrawableState(); } } public void toggle() { setChecked(!mChecked); } @Override public int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CHECKED_STATE_SET); } return drawableState; } }
Java
/* * Copyright 2013 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; public class TrackInfo { public String id; public String name; public int color; public String trackAbstract; public int level; public int meta; public String hashtag; }
Java
/* * Copyright 2013 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.Context; import android.content.res.Resources; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.support.v4.app.FragmentActivity; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.format.DateUtils; import android.text.style.StyleSpan; import android.util.DisplayMetrics; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.R.drawable; import com.google.android.apps.iosched.util.ImageLoader; import com.google.api.services.plus.model.Activity; import java.util.ArrayList; import java.util.List; import static com.google.api.services.plus.model.Activity.PlusObject.Attachments.Thumbnails; /** * Renders a Google+-like stream item. */ class PlusStreamRowViewBinder { private static class ViewHolder { // Author and metadata box private View authorContainer; private ImageView userImage; private TextView userName; private TextView time; // Author's content private TextView content; // Original share box private View originalContainer; private TextView originalAuthor; private TextView originalContent; // Media box private View mediaContainer; private ImageView mediaBackground; private ImageView mediaOverlay; private TextView mediaTitle; private TextView mediaSubtitle; // Interactions box private View interactionsContainer; private TextView plusOnes; private TextView shares; private TextView comments; } private static int PLACEHOLDER_USER_IMAGE = 0; private static int PLACEHOLDER_MEDIA_IMAGE = 1; public static ImageLoader getPlusStreamImageLoader(FragmentActivity activity, Resources resources) { DisplayMetrics metrics = resources.getDisplayMetrics(); int largestWidth = metrics.widthPixels > metrics.heightPixels ? metrics.widthPixels : metrics.heightPixels; // Create list of placeholder drawables (this ImageLoader requires two different // placeholder images). ArrayList<Drawable> placeHolderDrawables = new ArrayList<Drawable>(2); placeHolderDrawables.add(PLACEHOLDER_USER_IMAGE, resources.getDrawable(drawable.person_image_empty)); placeHolderDrawables.add(PLACEHOLDER_MEDIA_IMAGE, new ColorDrawable( resources.getColor(R.color.plus_empty_image_background_color))); // Create ImageLoader instance return new ImageLoader(activity, placeHolderDrawables) .setMaxImageSize(largestWidth); } public static void bindActivityView(final View rootView, Activity activity, ImageLoader imageLoader, boolean singleSourceMode) { // Prepare view holder. ViewHolder tempViews = (ViewHolder) rootView.getTag(); final ViewHolder views; if (tempViews != null) { views = tempViews; } else { views = new ViewHolder(); rootView.setTag(views); // Author and metadata box views.authorContainer = rootView.findViewById(R.id.stream_author_container); views.userImage = (ImageView) rootView.findViewById(R.id.stream_user_image); views.userName = (TextView) rootView.findViewById(R.id.stream_user_name); views.time = (TextView) rootView.findViewById(R.id.stream_time); // Author's content views.content = (TextView) rootView.findViewById(R.id.stream_content); // Original share box views.originalContainer = rootView.findViewById( R.id.stream_original_container); views.originalAuthor = (TextView) rootView.findViewById( R.id.stream_original_author); views.originalContent = (TextView) rootView.findViewById( R.id.stream_original_content); // Media box views.mediaContainer = rootView.findViewById(R.id.stream_media_container); views.mediaBackground = (ImageView) rootView.findViewById( R.id.stream_media_background); views.mediaOverlay = (ImageView) rootView.findViewById(R.id.stream_media_overlay); views.mediaTitle = (TextView) rootView.findViewById(R.id.stream_media_title); views.mediaSubtitle = (TextView) rootView.findViewById(R.id.stream_media_subtitle); // Interactions box views.interactionsContainer = rootView.findViewById( R.id.stream_interactions_container); views.plusOnes = (TextView) rootView.findViewById(R.id.stream_plus_ones); views.shares = (TextView) rootView.findViewById(R.id.stream_shares); views.comments = (TextView) rootView.findViewById(R.id.stream_comments); } final Context context = rootView.getContext(); final Resources res = context.getResources(); // Determine if this is a reshare (affects how activity fields are to be interpreted). Activity.PlusObject.Actor originalAuthor = activity.getObject().getActor(); boolean isReshare = "share".equals(activity.getVerb()) && originalAuthor != null; // Author and metadata box views.authorContainer.setVisibility(singleSourceMode ? View.GONE : View.VISIBLE); views.userName.setText(activity.getActor().getDisplayName()); // Find user profile image url String userImageUrl = null; if (activity.getActor().getImage() != null) { userImageUrl = activity.getActor().getImage().getUrl(); } // Load image from network in background thread using Volley library imageLoader.get(userImageUrl, views.userImage, PLACEHOLDER_USER_IMAGE); long thenUTC = activity.getUpdated().getValue() + activity.getUpdated().getTimeZoneShift() * 60000; views.time.setText(DateUtils.getRelativeTimeSpanString(thenUTC, System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS, DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_RELATIVE)); // Author's additional content String selfContent = isReshare ? activity.getAnnotation() : activity.getObject().getContent(); views.content.setMaxLines(singleSourceMode ? 1000 : 5); if (!TextUtils.isEmpty(selfContent)) { views.content.setVisibility(View.VISIBLE); views.content.setText(Html.fromHtml(selfContent)); } else { views.content.setVisibility(View.GONE); } // Original share box if (isReshare) { views.originalContainer.setVisibility(View.VISIBLE); // Set original author text, highlight author name final String author = res.getString( R.string.stream_originally_shared, originalAuthor.getDisplayName()); final SpannableStringBuilder spannableAuthor = new SpannableStringBuilder(author); spannableAuthor.setSpan(new StyleSpan(Typeface.BOLD), author.length() - originalAuthor.getDisplayName().length(), author.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); views.originalAuthor.setText(spannableAuthor, TextView.BufferType.SPANNABLE); String originalContent = activity.getObject().getContent(); views.originalContent.setMaxLines(singleSourceMode ? 1000 : 3); if (!TextUtils.isEmpty(originalContent)) { views.originalContent.setVisibility(View.VISIBLE); views.originalContent.setText(Html.fromHtml(originalContent)); } else { views.originalContent.setVisibility(View.GONE); } } else { views.originalContainer.setVisibility(View.GONE); } // Media box // Set media content. List<Activity.PlusObject.Attachments> attachments = activity.getObject().getAttachments(); if (attachments != null && attachments.size() > 0) { Activity.PlusObject.Attachments attachment = attachments.get(0); String objectType = attachment.getObjectType(); String imageUrl = attachment.getImage() != null ? attachment.getImage().getUrl() : null; if (imageUrl == null && attachment.getThumbnails() != null && attachment.getThumbnails().size() > 0) { Thumbnails thumb = attachment.getThumbnails().get(0); imageUrl = thumb.getImage() != null ? thumb.getImage().getUrl() : null; } // Load image from network in background thread using Volley library imageLoader.get(imageUrl, views.mediaBackground, PLACEHOLDER_MEDIA_IMAGE); boolean overlayStyle = false; views.mediaOverlay.setImageDrawable(null); if (("photo".equals(objectType) || "video".equals(objectType) || "album".equals(objectType)) && !TextUtils.isEmpty(imageUrl)) { overlayStyle = true; views.mediaOverlay.setImageResource("video".equals(objectType) ? R.drawable.ic_stream_media_overlay_video : R.drawable.ic_stream_media_overlay_photo); } else if ("article".equals(objectType) || "event".equals(objectType)) { overlayStyle = false; views.mediaTitle.setText(attachment.getDisplayName()); if (!TextUtils.isEmpty(attachment.getUrl())) { Uri uri = Uri.parse(attachment.getUrl()); views.mediaSubtitle.setText(uri.getHost()); } else { views.mediaSubtitle.setText(""); } } views.mediaContainer.setVisibility(View.VISIBLE); views.mediaContainer.setBackgroundResource( overlayStyle ? R.color.plus_stream_media_background : android.R.color.black); if (overlayStyle) { views.mediaBackground.clearColorFilter(); } else { views.mediaBackground.setColorFilter(res.getColor(R.color.plus_media_item_tint)); } views.mediaOverlay.setVisibility(overlayStyle ? View.VISIBLE : View.GONE); views.mediaTitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE); views.mediaSubtitle.setVisibility(overlayStyle ? View.GONE : View.VISIBLE); } else { views.mediaContainer.setVisibility(View.GONE); views.mediaBackground.setImageDrawable(null); views.mediaOverlay.setImageDrawable(null); } // Interactions box final int plusOneCount = (activity.getObject().getPlusoners() != null) ? activity.getObject().getPlusoners().getTotalItems().intValue() : 0; if (plusOneCount > 0) { views.plusOnes.setVisibility(View.VISIBLE); views.plusOnes.setText(getPlusOneString(plusOneCount)); } else { views.plusOnes.setVisibility(View.GONE); } final int commentCount = (activity.getObject().getReplies() != null) ? activity.getObject().getReplies().getTotalItems().intValue() : 0; if (commentCount > 0) { views.comments.setVisibility(View.VISIBLE); views.comments.setText(Integer.toString(commentCount)); } else { views.comments.setVisibility(View.GONE); } final int resharerCount = (activity.getObject().getResharers() != null) ? activity.getObject().getResharers().getTotalItems().intValue() : 0; if (resharerCount > 0) { views.shares.setVisibility(View.VISIBLE); views.shares.setText(Integer.toString(resharerCount)); } else { views.shares.setVisibility(View.GONE); } views.interactionsContainer.setVisibility( (plusOneCount > 0 || commentCount > 0 || resharerCount > 0) ? View.VISIBLE : View.GONE); } private static final String LRM_PLUS = "\u200E+"; private static String getPlusOneString(int count) { return LRM_PLUS + Integer.toString(count); } }
Java
/* * Copyright 2013 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.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceActivity; import com.google.android.apps.iosched.R; /** * Activity for customizing app settings. */ public class SettingsActivity extends PreferenceActivity { @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setupSimplePreferencesScreen(); } private void setupSimplePreferencesScreen() { // Add 'general' preferences. addPreferencesFromResource(R.xml.preferences); } }
Java
/* * Copyright 2013 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.ImageLoader; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.plus.model.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.ListView; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows announcements. */ public class AnnouncementsFragment extends ListFragment implements AbsListView.OnScrollListener, LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(AnnouncementsFragment.class); public static final String EXTRA_ADD_VERTICAL_MARGINS = "com.google.android.apps.iosched.extra.ADD_VERTICAL_MARGINS"; private static final String STATE_POSITION = "position"; private static final String STATE_TOP = "top"; private Cursor mCursor; private StreamAdapter mStreamAdapter; private int mListViewStatePosition; private int mListViewStateTop; private ImageLoader mImageLoader; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImageLoader = PlusStreamRowViewBinder.getPlusStreamImageLoader(getActivity(), getResources()); mCursor = null; mStreamAdapter = new StreamAdapter(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1); mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0); } else { mListViewStatePosition = -1; mListViewStateTop = 0; } return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.empty_announcements)); getLoaderManager().initLoader(0, null, this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ListView listView = getListView(); if (!UIUtils.isTablet(getActivity())) { view.setBackgroundColor(getResources().getColor(R.color.plus_stream_spacer_color)); } if (getArguments() != null && getArguments().getBoolean(EXTRA_ADD_VERTICAL_MARGINS, false)) { int verticalMargin = getResources().getDimensionPixelSize( R.dimen.plus_stream_padding_vertical); if (verticalMargin > 0) { listView.setClipToPadding(false); listView.setPadding(0, verticalMargin, 0, verticalMargin); } } listView.setOnScrollListener(this); listView.setDrawSelectorOnTop(true); listView.setDivider(getResources().getDrawable(android.R.color.transparent)); listView.setDividerHeight(getResources() .getDimensionPixelSize(R.dimen.page_margin_width)); TypedValue v = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true); listView.setSelector(v.resourceId); setListAdapter(mStreamAdapter); } @Override public void onSaveInstanceState(Bundle outState) { if (isAdded()) { View v = getListView().getChildAt(0); int top = (v == null) ? 0 : v.getTop(); outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition()); outState.putInt(STATE_TOP, top); } super.onSaveInstanceState(outState); } @Override public void onListItemClick(ListView l, View v, int position, long id) { if (mCursor == null) { return; } mCursor.moveToPosition(position); String url = mCursor.getString(AnnouncementsQuery.ANNOUNCEMENT_URL); Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), postDetailIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); startActivity(postDetailIntent); } @Override public void onScrollStateChanged(AbsListView listView, int scrollState) { // Pause disk cache access to ensure smoother scrolling if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { mImageLoader.stopProcessingQueue(); } else { mImageLoader.startProcessingQueue(); } } @Override public void onScroll(AbsListView absListView, int i, int i2, int i3) { } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(getActivity(), ScheduleContract.Announcements.CONTENT_URI, AnnouncementsQuery.PROJECTION, null, null, ScheduleContract.Announcements.DEFAULT_SORT); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { mCursor = cursor; mStreamAdapter.changeCursor(mCursor); mStreamAdapter.notifyDataSetChanged(); if (mListViewStatePosition != -1 && isAdded()) { getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop); mListViewStatePosition = -1; } } @Override public void onLoaderReset(Loader<Cursor> loader) { } private class StreamAdapter extends CursorAdapter { private JsonFactory mFactory = new GsonFactory(); private Map<Long, Activity> mActivityCache = new HashMap<Long, Activity>(); public StreamAdapter(Context context) { super(context, null, 0); } @Override public View newView(Context context, Cursor cursor, ViewGroup container) { return LayoutInflater.from(getActivity()).inflate( R.layout.list_item_stream_activity, container, false); } @Override public void bindView(View view, Context context, Cursor cursor) { long id = cursor.getLong(AnnouncementsQuery._ID); String activityJson = cursor.getString(AnnouncementsQuery.ANNOUNCEMENT_ACTIVITY_JSON); Activity activity = mActivityCache.get(id); // TODO: this should be async if (activity == null) { try { activity = mFactory.fromString(activityJson, Activity.class); } catch (IOException e) { LOGE(TAG, "Couldn't parse activity JSON: " + activityJson, e); } mActivityCache.put(id, activity); } PlusStreamRowViewBinder.bindActivityView(view, activity, mImageLoader, true); } } private interface AnnouncementsQuery { String[] PROJECTION = { ScheduleContract.Announcements._ID, ScheduleContract.Announcements.ANNOUNCEMENT_ACTIVITY_JSON, ScheduleContract.Announcements.ANNOUNCEMENT_URL, }; int _ID = 0; int ANNOUNCEMENT_ACTIVITY_JSON = 1; int ANNOUNCEMENT_URL = 2; } }
Java
/* * Copyright 2012 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.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.app.ShareCompat; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.text.TextUtils; import android.util.TypedValue; import android.view.*; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.NetUtils; import com.google.android.apps.iosched.util.UIUtils; import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.plus.Plus; import com.google.api.services.plus.model.Activity; import com.google.api.services.plus.model.ActivityFeed; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that renders Google+ search results for a given query, provided as the * {@link SocialStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no * search query is provided, the conference hashtag is used as the default query. */ public class SocialStreamFragment extends ListFragment implements AbsListView.OnScrollListener, LoaderManager.LoaderCallbacks<List<Activity>> { private static final String TAG = makeLogTag(SocialStreamFragment.class); public static final String EXTRA_QUERY = "com.google.android.apps.iosched.extra.QUERY"; public static final String EXTRA_ADD_VERTICAL_MARGINS = "com.google.android.apps.iosched.extra.ADD_VERTICAL_MARGINS"; private static final String STATE_POSITION = "position"; private static final String STATE_TOP = "top"; private static final long MAX_RESULTS_PER_REQUEST = 20; private static final String PLUS_RESULT_FIELDS = "nextPageToken,items(id,annotation,updated,url,verb,actor(displayName,image)," + "object(actor/displayName,attachments(displayName,image/url,objectType," + "thumbnails(image/url,url),url),content,plusoners/totalItems,replies/totalItems," + "resharers/totalItems))"; private static final int STREAM_LOADER_ID = 0; private String mSearchString; private List<Activity> mStream = new ArrayList<Activity>(); private StreamAdapter mStreamAdapter = new StreamAdapter(); private int mListViewStatePosition; private int mListViewStateTop; private ImageLoader mImageLoader; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); // mSearchString can be populated before onCreate() by called refresh(String) if (TextUtils.isEmpty(mSearchString)) { mSearchString = intent.getStringExtra(EXTRA_QUERY); } if (TextUtils.isEmpty(mSearchString)) { mSearchString = UIUtils.CONFERENCE_HASHTAG; } if (!mSearchString.startsWith("#")) { mSearchString = "#" + mSearchString; } mImageLoader = PlusStreamRowViewBinder.getPlusStreamImageLoader(getActivity(), getResources()); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (savedInstanceState != null) { mListViewStatePosition = savedInstanceState.getInt(STATE_POSITION, -1); mListViewStateTop = savedInstanceState.getInt(STATE_TOP, 0); } else { mListViewStatePosition = -1; mListViewStateTop = 0; } return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.empty_social_stream)); // In support library r8, calling initLoader for a fragment in a FragmentPagerAdapter // in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we do this in onActivityCreated. getLoaderManager().initLoader(STREAM_LOADER_ID, null, this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); final ListView listView = getListView(); if (!UIUtils.isTablet(getActivity())) { view.setBackgroundColor(getResources().getColor(R.color.plus_stream_spacer_color)); } if (getArguments() != null && getArguments().getBoolean(EXTRA_ADD_VERTICAL_MARGINS, false)) { int verticalMargin = getResources().getDimensionPixelSize( R.dimen.plus_stream_padding_vertical); if (verticalMargin > 0) { listView.setClipToPadding(false); listView.setPadding(0, verticalMargin, 0, verticalMargin); } } listView.setOnScrollListener(this); listView.setDrawSelectorOnTop(true); listView.setDivider(getResources().getDrawable(android.R.color.transparent)); listView.setDividerHeight(getResources() .getDimensionPixelSize(R.dimen.page_margin_width)); TypedValue v = new TypedValue(); getActivity().getTheme().resolveAttribute(R.attr.activatableItemBackground, v, true); listView.setSelector(v.resourceId); setListAdapter(mStreamAdapter); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.social_stream, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_compose: Intent intent = ShareCompat.IntentBuilder.from(getActivity()) .setType("text/plain") .setText(mSearchString + "\n\n") .getIntent(); UIUtils.preferPackageForIntent(getActivity(), intent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); startActivity(intent); EasyTracker.getTracker().sendEvent("Home Screen Dashboard", "Click", "Post to G+", 0L); LOGD("Tracker", "Home Screen Dashboard: Click, post to g+"); return true; } return false; } @Override public void onPrepareOptionsMenu(Menu menu) { } @Override public void onDestroyOptionsMenu() { } @Override public void onSaveInstanceState(Bundle outState) { if (isAdded()) { View v = getListView().getChildAt(0); int top = (v == null) ? 0 : v.getTop(); outState.putInt(STATE_POSITION, getListView().getFirstVisiblePosition()); outState.putInt(STATE_TOP, top); } super.onSaveInstanceState(outState); } public void refresh(String newQuery) { mSearchString = newQuery; refresh(true); } public void refresh() { refresh(false); } public void refresh(boolean forceRefresh) { if (isStreamLoading() && !forceRefresh) { return; } // clear current items mStream.clear(); mStreamAdapter.notifyDataSetInvalidated(); if (isAdded()) { Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); ((StreamLoader) loader).init(mSearchString); } loadMoreResults(); } public void loadMoreResults() { if (isAdded()) { Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { loader.forceLoad(); } } } @Override public void onListItemClick(ListView l, View v, int position, long id) { Activity activity = mStream.get(position); Intent postDetailIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(activity.getUrl())); postDetailIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); UIUtils.preferPackageForIntent(getActivity(), postDetailIntent, UIUtils.GOOGLE_PLUS_PACKAGE_NAME); startActivity(postDetailIntent); } @Override public void onScrollStateChanged(AbsListView listView, int scrollState) { // Pause disk cache access to ensure smoother scrolling if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) { mImageLoader.stopProcessingQueue(); } else { mImageLoader.startProcessingQueue(); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (!isStreamLoading() && streamHasMoreResults() && visibleItemCount != 0 && firstVisibleItem + visibleItemCount >= totalItemCount - 1) { loadMoreResults(); } } @Override public Loader<List<Activity>> onCreateLoader(int id, Bundle args) { return new StreamLoader(getActivity(), mSearchString); } @Override public void onLoadFinished(Loader<List<Activity>> listLoader, List<Activity> activities) { if (activities != null) { mStream = activities; } mStreamAdapter.notifyDataSetChanged(); if (mListViewStatePosition != -1 && isAdded()) { getListView().setSelectionFromTop(mListViewStatePosition, mListViewStateTop); mListViewStatePosition = -1; } } @Override public void onLoaderReset(Loader<List<Activity>> listLoader) { } private boolean isStreamLoading() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).isLoading(); } } return true; } private boolean streamHasMoreResults() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).hasMoreResults(); } } return false; } private boolean streamHasError() { if (isAdded()) { final Loader loader = getLoaderManager().getLoader(STREAM_LOADER_ID); if (loader != null) { return ((StreamLoader) loader).hasError(); } } return false; } private static class StreamLoader extends AsyncTaskLoader<List<Activity>> { List<Activity> mActivities; private String mSearchString; private String mNextPageToken; private boolean mIsLoading; private boolean mHasError; public StreamLoader(Context context, String searchString) { super(context); init(searchString); } private void init(String searchString) { mSearchString = searchString; mHasError = false; mNextPageToken = null; mIsLoading = true; mActivities = null; } @Override public List<Activity> loadInBackground() { mIsLoading = true; // Set up the HTTP transport and JSON factory HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = new GsonFactory(); // Set up the main Google+ class Plus plus = new Plus.Builder(httpTransport, jsonFactory, null) .setApplicationName(NetUtils.getUserAgent(getContext())) .setGoogleClientRequestInitializer( new CommonGoogleClientRequestInitializer(Config.API_KEY)) .build(); ActivityFeed activities = null; try { activities = plus.activities().search(mSearchString) .setPageToken(mNextPageToken) .setOrderBy("recent") .setMaxResults(MAX_RESULTS_PER_REQUEST) .setFields(PLUS_RESULT_FIELDS) .execute(); mHasError = false; mNextPageToken = activities.getNextPageToken(); } catch (IOException e) { e.printStackTrace(); mHasError = true; mNextPageToken = null; } return (activities != null) ? activities.getItems() : null; } @Override public void deliverResult(List<Activity> activities) { mIsLoading = false; if (activities != null) { if (mActivities == null) { mActivities = activities; } else { mActivities.addAll(activities); } } if (isStarted()) { // Need to return new ArrayList for some reason or onLoadFinished() is not called super.deliverResult(mActivities == null ? null : new ArrayList<Activity>(mActivities)); } } @Override protected void onStartLoading() { if (mActivities != null) { // If we already have results and are starting up, deliver what we already have. deliverResult(null); } else { forceLoad(); } } @Override protected void onStopLoading() { mIsLoading = false; cancelLoad(); } @Override protected void onReset() { super.onReset(); onStopLoading(); mActivities = null; } public boolean isLoading() { return mIsLoading; } public boolean hasMoreResults() { return mNextPageToken != null; } public boolean hasError() { return mHasError; } public void setSearchString(String searchString) { mSearchString = searchString; } public void refresh() { reset(); startLoading(); } } private class StreamAdapter extends BaseAdapter { private static final int VIEW_TYPE_ACTIVITY = 0; private static final int VIEW_TYPE_LOADING = 1; @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return getItemViewType(position) == VIEW_TYPE_ACTIVITY; } @Override public int getViewTypeCount() { return 2; } @Override public boolean hasStableIds() { return true; } @Override public int getCount() { return mStream.size() + ( // show the status list row if... ((isStreamLoading() && mStream.size() == 0) // ...this is the first load || streamHasMoreResults() // ...or there's another page || streamHasError()) // ...or there's an error ? 1 : 0); } @Override public int getItemViewType(int position) { return (position >= mStream.size()) ? VIEW_TYPE_LOADING : VIEW_TYPE_ACTIVITY; } @Override public Object getItem(int position) { return (getItemViewType(position) == VIEW_TYPE_ACTIVITY) ? mStream.get(position) : null; } @Override public long getItemId(int position) { // TODO: better unique ID heuristic return (getItemViewType(position) == VIEW_TYPE_ACTIVITY) ? mStream.get(position).getId().hashCode() : -1; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (getItemViewType(position) == VIEW_TYPE_LOADING) { if (convertView == null) { convertView = getLayoutInflater(null).inflate( R.layout.list_item_stream_status, parent, false); } if (streamHasError()) { convertView.findViewById(android.R.id.progress).setVisibility(View.GONE); ((TextView) convertView.findViewById(android.R.id.text1)).setText( R.string.stream_error); } else { convertView.findViewById(android.R.id.progress).setVisibility(View.VISIBLE); ((TextView) convertView.findViewById(android.R.id.text1)).setText( R.string.loading); } return convertView; } else { Activity activity = (Activity) getItem(position); if (convertView == null) { convertView = getLayoutInflater(null).inflate( R.layout.list_item_stream_activity, parent, false); } PlusStreamRowViewBinder.bindActivityView(convertView, activity, mImageLoader, false); return convertView; } } } }
Java
/* * Copyright 2013 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 static com.google.android.apps.iosched.util.LogUtils.makeLogTag; import java.io.*; import java.util.concurrent.ConcurrentLinkedQueue; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.RectF; import android.util.Log; import com.google.android.gms.maps.model.Tile; import com.google.android.gms.maps.model.TileProvider; import com.larvalabs.svgandroid.SVG; import com.larvalabs.svgandroid.SVGParser; public class SVGTileProvider implements TileProvider { private static final String TAG = makeLogTag(SVGTileProvider.class); private static final int POOL_MAX_SIZE = 5; private static final int BASE_TILE_SIZE = 256; private final TileGeneratorPool mPool; private final Matrix mBaseMatrix; private final int mScale; private final int mDimension; private byte[] mSvgFile; public SVGTileProvider(File file, float dpi) throws IOException { mScale = Math.round(dpi + .3f); // Make it look nice on N7 (1.3 dpi) mDimension = BASE_TILE_SIZE * mScale; mPool = new TileGeneratorPool(POOL_MAX_SIZE); mSvgFile = readFile(file); RectF limits = SVGParser.getSVGFromInputStream(new ByteArrayInputStream(mSvgFile)).getLimits(); mBaseMatrix = new Matrix(); mBaseMatrix.setPolyToPoly( new float[]{ 0, 0, limits.width(), 0, limits.width(), limits.height() }, 0, new float[]{ 40.95635986328125f, 98.94217824936158f, 40.95730018615723f, 98.94123077396628f, 40.95791244506836f, 98.94186019897214f }, 0, 3); } @Override public Tile getTile(int x, int y, int zoom) { TileGenerator tileGenerator = mPool.get(); byte[] tileData = tileGenerator.getTileImageData(x, y, zoom); mPool.restore(tileGenerator); return new Tile(mDimension, mDimension, tileData); } private class TileGeneratorPool { private final ConcurrentLinkedQueue<TileGenerator> mPool = new ConcurrentLinkedQueue<TileGenerator>(); private final int mMaxSize; private TileGeneratorPool(int maxSize) { mMaxSize = maxSize; } public TileGenerator get() { TileGenerator i = mPool.poll(); if (i == null) { return new TileGenerator(); } return i; } public void restore(TileGenerator tileGenerator) { if (mPool.size() < mMaxSize && mPool.offer(tileGenerator)) { return; } // pool is too big or returning to pool failed, so just try to clean // up. tileGenerator.cleanUp(); } } public class TileGenerator { private Bitmap mBitmap; private SVG mSvg; private ByteArrayOutputStream mStream; public TileGenerator() { mBitmap = Bitmap.createBitmap(mDimension, mDimension, Bitmap.Config.ARGB_8888); mStream = new ByteArrayOutputStream(mDimension * mDimension * 4); mSvg = SVGParser.getSVGFromInputStream(new ByteArrayInputStream(mSvgFile)); } public byte[] getTileImageData(int x, int y, int zoom) { mStream.reset(); Matrix matrix = new Matrix(mBaseMatrix); float scale = (float) (Math.pow(2, zoom) * mScale); matrix.postScale(scale, scale); matrix.postTranslate(-x * mDimension, -y * mDimension); mBitmap.eraseColor(Color.TRANSPARENT); Canvas c = new Canvas(mBitmap); c.setMatrix(matrix); mSvg.getPicture().draw(c); BufferedOutputStream stream = new BufferedOutputStream(mStream); mBitmap.compress(Bitmap.CompressFormat.PNG, 0, stream); try { stream.close(); } catch (IOException e) { Log.e(TAG, "Error while closing tile byte stream."); e.printStackTrace(); } return mStream.toByteArray(); } /** * Attempt to free memory and remove references. */ public void cleanUp() { mBitmap.recycle(); mBitmap = null; mSvg = null; try { mStream.close(); } catch (IOException e) { // ignore } mStream = null; } } private static byte[] readFile(File file) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(file)); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int n; while ((n = in.read(buffer)) != -1) { baos.write(buffer, 0, n); } return baos.toByteArray(); } finally { in.close(); } } }
Java
/* * Copyright 2012 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; import android.view.Menu; import android.view.MenuItem; import com.google.android.apps.iosched.R; public class SocialStreamActivity extends SimpleSinglePaneActivity { @Override protected Fragment onCreatePane() { setIntent(getIntent().putExtra(SocialStreamFragment.EXTRA_ADD_VERTICAL_MARGINS, true)); return new SocialStreamFragment(); } @Override protected int getContentViewResId() { return R.layout.activity_plus_stream; } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); setTitle(getIntent().getStringExtra(SocialStreamFragment.EXTRA_QUERY)); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.social_stream_standalone, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_refresh: ((SocialStreamFragment) getFragment()).refresh(); return true; } return super.onOptionsItemSelected(item); } }
Java
/* * Copyright 2013 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.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.TaskStackBuilder; /** * Helper 'proxy' activity that simply accepts an activity intent and synthesize a back-stack * for it, per Android's design guidelines for navigation from widgets and notifications. */ public class TaskStackBuilderProxyActivity extends Activity { private static final String EXTRA_INTENTS = "com.google.android.apps.iosched.extra.INTENTS"; public static Intent getTemplate(Context context) { return new Intent(context, TaskStackBuilderProxyActivity.class) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } public static Intent getFillIntent(Intent... intents) { return new Intent().putExtra(EXTRA_INTENTS, intents); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TaskStackBuilder builder = TaskStackBuilder.create(this); Intent proxyIntent = getIntent(); if (!proxyIntent.hasExtra(EXTRA_INTENTS)) { finish(); return; } for (Parcelable parcelable : proxyIntent.getParcelableArrayExtra(EXTRA_INTENTS)) { builder.addNextIntent((Intent) parcelable); } builder.startActivities(); finish(); } }
Java
/* * Copyright 2012 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.res.Configuration; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.*; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A base activity that handles common functionality in the app. */ public abstract class BaseActivity extends ActionBarActivity { private static final String TAG = makeLogTag(BaseActivity.class); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EasyTracker.getInstance().setContext(this); if (!AccountUtils.isAuthenticated(this) || !PrefUtils.isSetupDone(this)) { LogUtils.LOGD(TAG, "exiting:" + " isAuthenticated=" + AccountUtils.isAuthenticated(this) + " isSetupDone=" + PrefUtils.isSetupDone(this)); AccountUtils.startAuthenticationFlow(this, getIntent()); finish(); } } @Override protected void onResume() { super.onResume(); // Verifies the proper version of Google Play Services exists on the device. PlayServicesUtils.checkGooglePlaySevices(this); } protected void setHasTabs() { if (!UIUtils.isTablet(this) && getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) { // Only show the tab bar's shadow getSupportActionBar().setBackgroundDrawable(getResources().getDrawable( R.drawable.actionbar_background_noshadow)); } } /** * Sets the icon. */ protected void setActionBarTrackIcon(String trackName, int trackColor) { if (trackColor == 0) { getSupportActionBar().setIcon(R.drawable.actionbar_icon); return; } new UIUtils.TrackIconAsyncTask(trackName, trackColor) { @Override protected void onPostExecute(Bitmap bitmap) { BitmapDrawable outDrawable = new BitmapDrawable(getResources(), bitmap); getSupportActionBar().setIcon(outDrawable); } }.execute(this); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ protected static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } /** * Converts a fragment arguments bundle into an intent. */ public static Intent fragmentArgumentsToIntent(Bundle arguments) { Intent intent = new Intent(); if (arguments == null) { return intent; } final Uri data = arguments.getParcelable("_uri"); if (data != null) { intent.setData(data); } intent.putExtras(arguments); intent.removeExtra("_uri"); return intent; } @Override public void onStart() { super.onStart(); EasyTracker.getInstance().activityStart(this); } @Override public void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); } }
Java
/* * Copyright 2012 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.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.Rect; import android.provider.BaseColumns; import android.support.v4.app.FragmentActivity; import android.support.v4.widget.CursorAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.BitmapCache; import com.google.android.apps.iosched.util.UIUtils; /** * 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 static final int LEVEL_2_SECTION_HEADER_ITEM_ID = ALL_ITEM_ID - 1; private Activity mActivity; private boolean mHasAllItem; private int mFirstLevel2CursorPosition = -1; private BitmapCache mBitmapCache; private boolean mIsDropDown; public TracksAdapter(FragmentActivity activity, boolean isDropDown) { super(activity, null, 0); mActivity = activity; mIsDropDown = isDropDown; // Fetch track icon size in pixels. int trackIconSize = activity.getResources().getDimensionPixelSize(R.dimen.track_icon_source_size); // Cache size is total pixels by 4 bytes (as format is ARGB_8888) by 20 (max icons to hold // in the cache) converted to KB. int cacheSize = trackIconSize * trackIconSize * 4 * 20 / 1024; // Create a BitmapCache to hold the track icons. mBitmapCache = BitmapCache.getInstance(activity.getSupportFragmentManager(), UIUtils.TRACK_ICONS_TAG, cacheSize); } @Override public void changeCursor(Cursor cursor) { updateSpecialItemPositions(cursor); super.changeCursor(cursor); } @Override public Cursor swapCursor(Cursor newCursor) { updateSpecialItemPositions(newCursor); return super.swapCursor(newCursor); } public void setHasAllItem(boolean hasAllItem) { mHasAllItem = hasAllItem; updateSpecialItemPositions(getCursor()); } private void updateSpecialItemPositions(Cursor cursor) { mFirstLevel2CursorPosition = -1; if (cursor != null && !cursor.isClosed()) { cursor.moveToFirst(); while (cursor.moveToNext()) { if (cursor.getInt(TracksQuery.TRACK_LEVEL) == 2) { mFirstLevel2CursorPosition = cursor.getPosition(); break; } } } } public boolean isAllTracksItem(int position) { return mHasAllItem && position == 0; } public boolean isLevel2Header(int position) { return mFirstLevel2CursorPosition >= 0 && position - (mHasAllItem ? 1 : 0) == mFirstLevel2CursorPosition; } public int adapterPositionToCursorPosition(int position) { position -= (mHasAllItem ? 1 : 0); if (mFirstLevel2CursorPosition >= 0 && position > mFirstLevel2CursorPosition) { --position; } return position; } @Override public int getCount() { int superCount = super.getCount(); if (superCount == 0) { return 0; } return superCount + (mFirstLevel2CursorPosition >= 0 ? 1 : 0) + (mHasAllItem ? 1 : 0); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isAllTracksItem(position)) { 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(R.string.all_tracks) + ")"); convertView.findViewById(android.R.id.icon1).setVisibility(View.INVISIBLE); return convertView; } else if (isLevel2Header(position)) { TextView view = (TextView) convertView; if (view == null) { view = (TextView) mActivity.getLayoutInflater().inflate( R.layout.list_item_track_header, parent, false); if (mIsDropDown) { Rect r = new Rect(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom()); view.setBackgroundResource(R.drawable.track_header_bottom_border); view.setPadding(r.left, r.top, r.right, r.bottom); } } view.setText(R.string.other_tracks); return view; } return super.getView(adapterPositionToCursorPosition(position), convertView, parent); } @Override public Object getItem(int position) { if (isAllTracksItem(position) || isLevel2Header(position)) { return null; } return super.getItem(adapterPositionToCursorPosition(position)); } @Override public long getItemId(int position) { if (isAllTracksItem(position)) { return ALL_ITEM_ID; } else if (isLevel2Header(position)) { return LEVEL_2_SECTION_HEADER_ITEM_ID; } return super.getItemId(adapterPositionToCursorPosition(position)); } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return position < (mHasAllItem ? 1 : 0) || !isLevel2Header(position) && super.isEnabled(adapterPositionToCursorPosition(position)); } @Override public int getViewTypeCount() { // Add an item type for the "All" item and section header. return super.getViewTypeCount() + 2; } @Override public int getItemViewType(int position) { if (isAllTracksItem(position)) { return getViewTypeCount() - 1; } else if (isLevel2Header(position)) { return getViewTypeCount() - 2; } return super.getItemViewType(adapterPositionToCursorPosition(position)); } /** {@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) { String trackName = cursor.getString(TracksQuery.TRACK_NAME); final TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText(trackName); // Assign track color and icon to visible block final ImageView iconView = (ImageView) view.findViewById(android.R.id.icon1); new UIUtils.TrackIconViewAsyncTask(iconView, trackName, cursor.getInt(TracksQuery.TRACK_COLOR), mBitmapCache).execute(context); } /** {@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, ScheduleContract.Tracks.TRACK_LEVEL, ScheduleContract.Tracks.TRACK_META, }; 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.TRACK_LEVEL, ScheduleContract.Tracks.TRACK_META, ScheduleContract.Tracks.SESSIONS_COUNT, }; String[] PROJECTION_WITH_OFFICE_HOURS_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.TRACK_LEVEL, ScheduleContract.Tracks.TRACK_META, ScheduleContract.Tracks.OFFICE_HOURS_COUNT, }; String[] PROJECTION_WITH_SANDBOX_COUNT = { BaseColumns._ID, ScheduleContract.Tracks.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_ABSTRACT, ScheduleContract.Tracks.TRACK_COLOR, ScheduleContract.Tracks.TRACK_LEVEL, ScheduleContract.Tracks.TRACK_META, ScheduleContract.Tracks.SANDBOX_COUNT, }; int _ID = 0; int TRACK_ID = 1; int TRACK_NAME = 2; int TRACK_ABSTRACT = 3; int TRACK_COLOR = 4; int TRACK_LEVEL = 5; int TRACK_META = 6; } }
Java
/* * Copyright 2013 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 accept a scroll listener. */ public class ObservableScrollView extends ScrollView { private Callbacks mCallbacks; 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 (mCallbacks != null) { mCallbacks.onScrollChanged(); } } @Override public int computeVerticalScrollRange() { return super.computeVerticalScrollRange(); } public void setCallbacks(Callbacks listener) { mCallbacks = listener; } public static interface Callbacks { public void onScrollChanged(); } }
Java
/* * Copyright 2012 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.Checkable; import android.widget.FrameLayout; public class CheckableFrameLayout extends FrameLayout implements Checkable { private boolean mChecked; public CheckableFrameLayout(Context context) { super(context); } public CheckableFrameLayout(Context context, AttributeSet attrs) { super(context, attrs); } public CheckableFrameLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } private static final int[] CheckedStateSet = { android.R.attr.state_checked }; @Override public boolean isChecked() { return mChecked; } @Override public void setChecked(boolean checked) { mChecked = checked; refreshDrawableState(); } @Override public void toggle() { setChecked(!mChecked); } @Override protected int[] onCreateDrawableState(int extraSpace) { final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); if (isChecked()) { mergeDrawableStates(drawableState, CheckedStateSet); } return drawableState; } }
Java
/* * Copyright 2013 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.text.TextUtils; import android.util.AttributeSet; import android.widget.TextView; /** * A simple {@link TextView} subclass that uses {@link TextUtils#ellipsize(CharSequence, * android.text.TextPaint, float, android.text.TextUtils.TruncateAt, boolean, * android.text.TextUtils.EllipsizeCallback)} to truncate the displayed text. This is used in * {@link com.google.android.apps.iosched.ui.PlusStreamRowViewBinder} when displaying G+ post text * which is converted from HTML to a {@link android.text.SpannableString} and sometimes causes * issues for the built-in TextView ellipsize function. */ public class EllipsizedTextView extends TextView { private static final int MAX_ELLIPSIZE_LINES = 100; private int mMaxLines; public EllipsizedTextView(Context context) { this(context, null, 0); } public EllipsizedTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public EllipsizedTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Attribute initialization final TypedArray a = context.obtainStyledAttributes(attrs, new int[]{ android.R.attr.maxLines }, defStyle, 0); mMaxLines = a.getInteger(0, 1); a.recycle(); } @Override public void setText(CharSequence text, BufferType type) { CharSequence newText = getWidth() == 0 || mMaxLines > MAX_ELLIPSIZE_LINES ? text : TextUtils.ellipsize(text, getPaint(), getWidth() * mMaxLines, TextUtils.TruncateAt.END, false, null); super.setText(newText, type); } @Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { super.onSizeChanged(width, height, oldWidth, oldHeight); if (width > 0 && oldWidth != width) { setText(getText()); } } @Override public void setMaxLines(int maxlines) { super.setMaxLines(maxlines); mMaxLines = maxlines; } }
Java
/* * Copyright 2012 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.Bitmap; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; 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.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.widget.ImageView; /** * An {@link android.widget.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 Paint mBlackPaint; private Paint mMaskedPaint; private Rect mBounds; private RectF mBoundsF; private Drawable mBorderDrawable; private Drawable mMaskDrawable; private ColorMatrixColorFilter mDesaturateColorFilter; private boolean mDesaturateOnPress = false; private boolean mCacheValid = false; private Bitmap mCacheBitmap; private int mCachedWidth; private int mCachedHeight; 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.setCallback(this); } mBorderDrawable = a.getDrawable(R.styleable.BezelImageView_borderDrawable); if (mBorderDrawable != null) { mBorderDrawable.setCallback(this); } mDesaturateOnPress = a.getBoolean(R.styleable.BezelImageView_desaturateOnPress, mDesaturateOnPress); a.recycle(); // Other initialization mBlackPaint = new Paint(); mBlackPaint.setColor(0xff000000); mMaskedPaint = new Paint(); mMaskedPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); // Always want a cache allocated. mCacheBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); if (mDesaturateOnPress) { // Create a desaturate color filter for pressed state. ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); mDesaturateColorFilter = new ColorMatrixColorFilter(cm); } } @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); if (mBorderDrawable != null) { mBorderDrawable.setBounds(mBounds); } if (mMaskDrawable != null) { mMaskDrawable.setBounds(mBounds); } if (changed) { mCacheValid = false; } return changed; } @Override protected void onDraw(Canvas canvas) { if (mBounds == null) { return; } int width = mBounds.width(); int height = mBounds.height(); if (width == 0 || height == 0) { return; } if (!mCacheValid || width != mCachedWidth || height != mCachedHeight) { // Need to redraw the cache if (width == mCachedWidth && height == mCachedHeight) { // Have a correct-sized bitmap cache already allocated. Just erase it. mCacheBitmap.eraseColor(0); } else { // Allocate a new bitmap with the correct dimensions. mCacheBitmap.recycle(); //noinspection AndroidLintDrawAllocation mCacheBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCachedWidth = width; mCachedHeight = height; } Canvas cacheCanvas = new Canvas(mCacheBitmap); if (mMaskDrawable != null) { int sc = cacheCanvas.save(); mMaskDrawable.draw(cacheCanvas); mMaskedPaint.setColorFilter((mDesaturateOnPress && isPressed()) ? mDesaturateColorFilter : null); cacheCanvas.saveLayer(mBoundsF, mMaskedPaint, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG); super.onDraw(cacheCanvas); cacheCanvas.restoreToCount(sc); } else if (mDesaturateOnPress && isPressed()) { int sc = cacheCanvas.save(); cacheCanvas.drawRect(0, 0, mCachedWidth, mCachedHeight, mBlackPaint); mMaskedPaint.setColorFilter(mDesaturateColorFilter); cacheCanvas.saveLayer(mBoundsF, mMaskedPaint, Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.FULL_COLOR_LAYER_SAVE_FLAG); super.onDraw(cacheCanvas); cacheCanvas.restoreToCount(sc); } else { super.onDraw(cacheCanvas); } if (mBorderDrawable != null) { mBorderDrawable.draw(cacheCanvas); } } // Draw from cache canvas.drawBitmap(mCacheBitmap, mBounds.left, mBounds.top, null); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); if (mBorderDrawable != null && mBorderDrawable.isStateful()) { mBorderDrawable.setState(getDrawableState()); } if (mMaskDrawable != null && mMaskDrawable.isStateful()) { mMaskDrawable.setState(getDrawableState()); } if (isDuplicateParentStateEnabled()) { ViewCompat.postInvalidateOnAnimation(this); } } @Override public void invalidateDrawable(Drawable who) { if (who == mBorderDrawable || who == mMaskDrawable) { invalidate(); } else { super.invalidateDrawable(who); } } @Override protected boolean verifyDrawable(Drawable who) { return who == mBorderDrawable || who == mMaskDrawable || super.verifyDrawable(who); } }
Java
/* * Copyright 2012 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.os.Handler; import android.support.v7.app.ActionBarActivity; import android.support.v7.view.ActionMode; import android.util.Pair; import android.util.SparseBooleanArray; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.ListView; import java.util.HashSet; /** * Utilities for handling multiple selection in list views. Contains functionality similar to * {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL} but that works with {@link ActionBarActivity} and * backward-compatible action bars. */ public class MultiSelectionUtil { public static Controller attachMultiSelectionController(final ListView listView, final ActionBarActivity activity, final MultiChoiceModeListener listener) { return Controller.attach(listView, activity, listener); } public static class Controller implements ActionMode.Callback, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener { private Handler mHandler = new Handler(); private ActionMode mActionMode; private ListView mListView = null; private ActionBarActivity mActivity = null; private MultiChoiceModeListener mListener = null; private HashSet<Long> mTempIdsToCheckOnRestore; private HashSet<Pair<Integer, Long>> mItemsToCheck; private AdapterView.OnItemClickListener mOldItemClickListener; private Controller() { } public static Controller attach(ListView listView, ActionBarActivity activity, MultiChoiceModeListener listener) { Controller controller = new Controller(); controller.mListView = listView; controller.mActivity = activity; controller.mListener = listener; listView.setOnItemLongClickListener(controller); return controller; } private void readInstanceState(Bundle savedInstanceState) { mTempIdsToCheckOnRestore = null; if (savedInstanceState != null) { long[] checkedIds = savedInstanceState.getLongArray(getStateKey()); if (checkedIds != null && checkedIds.length > 0) { mTempIdsToCheckOnRestore = new HashSet<Long>(); for (long id : checkedIds) { mTempIdsToCheckOnRestore.add(id); } } } } public void tryRestoreInstanceState(Bundle savedInstanceState) { readInstanceState(savedInstanceState); tryRestoreInstanceState(); } public void finish() { if (mActionMode != null) { mActionMode.finish(); } } public void tryRestoreInstanceState() { if (mTempIdsToCheckOnRestore == null || mListView.getAdapter() == null) { return; } boolean idsFound = false; Adapter adapter = mListView.getAdapter(); for (int pos = adapter.getCount() - 1; pos >= 0; pos--) { if (mTempIdsToCheckOnRestore.contains(adapter.getItemId(pos))) { idsFound = true; if (mItemsToCheck == null) { mItemsToCheck = new HashSet<Pair<Integer, Long>>(); } mItemsToCheck.add( new Pair<Integer, Long>(pos, adapter.getItemId(pos))); } } if (idsFound) { // We found some IDs that were checked. Let's now restore the multi-selection // state. mTempIdsToCheckOnRestore = null; // clear out this temp field mActionMode = mActivity.startSupportActionMode(Controller.this); } } public boolean saveInstanceState(Bundle outBundle) { // TODO: support non-stable IDs by persisting positions instead of IDs if (mActionMode != null && mListView.getAdapter().hasStableIds()) { long[] checkedIds = mListView.getCheckedItemIds(); outBundle.putLongArray(getStateKey(), checkedIds); return true; } return false; } private String getStateKey() { return MultiSelectionUtil.class.getSimpleName() + "_" + mListView.getId(); } @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { if (mListener.onCreateActionMode(actionMode, menu)) { mActionMode = actionMode; mOldItemClickListener = mListView.getOnItemClickListener(); mListView.setOnItemClickListener(Controller.this); mListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE); mHandler.removeCallbacks(mSetChoiceModeNoneRunnable); if (mItemsToCheck != null) { for (Pair<Integer, Long> posAndId : mItemsToCheck) { mListView.setItemChecked(posAndId.first, true); mListener.onItemCheckedStateChanged(mActionMode, posAndId.first, posAndId.second, true); } } return true; } return false; } @Override public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { if (mListener.onPrepareActionMode(actionMode, menu)) { mActionMode = actionMode; return true; } return false; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { return mListener.onActionItemClicked(actionMode, menuItem); } @Override public void onDestroyActionMode(ActionMode actionMode) { mListener.onDestroyActionMode(actionMode); SparseBooleanArray checkedPositions = mListView.getCheckedItemPositions(); if (checkedPositions != null) { for (int i = 0; i < checkedPositions.size(); i++) { mListView.setItemChecked(checkedPositions.keyAt(i), false); } } mListView.setOnItemClickListener(mOldItemClickListener); mActionMode = null; mHandler.post(mSetChoiceModeNoneRunnable); } private Runnable mSetChoiceModeNoneRunnable = new Runnable() { @Override public void run() { mListView.setChoiceMode(AbsListView.CHOICE_MODE_NONE); } }; @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { boolean checked = mListView.isItemChecked(position); mListener.onItemCheckedStateChanged(mActionMode, position, id, checked); int numChecked = 0; SparseBooleanArray checkedItemPositions = mListView.getCheckedItemPositions(); if (checkedItemPositions != null) { for (int i = 0; i < checkedItemPositions.size(); i++) { numChecked += checkedItemPositions.valueAt(i) ? 1 : 0; } } if (numChecked <= 0) { mActionMode.finish(); } } @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { if (mActionMode != null) { return false; } mItemsToCheck = new HashSet<Pair<Integer, Long>>(); mItemsToCheck.add(new Pair<Integer, Long>(position, id)); mActionMode = mActivity.startSupportActionMode(Controller.this); return true; } } /** * @see android.widget.AbsListView.MultiChoiceModeListener */ public static interface MultiChoiceModeListener extends ActionMode.Callback { /** * @see android.widget.AbsListView.MultiChoiceModeListener#onItemCheckedStateChanged( * android.view.ActionMode, int, long, boolean) */ public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked); } }
Java
/* * Copyright 2012 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.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; 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.ImageView; import android.widget.TextView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * A fragment that shows detail information for a sandbox company, including * company name, description, product description, logo, etc. */ public class SandboxDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private static final String TAG = makeLogTag(SandboxDetailFragment.class); private Uri mCompanyUri; private TextView mName; private TextView mSubtitle; private ImageView mLogo; private TextView mUrl; private TextView mDesc; private ImageLoader mImageLoader; private int mCompanyImageSize; private Drawable mCompanyPlaceHolderImage; private StringBuilder mBuffer = new StringBuilder(); private String mRoomId; private String mCompanyName; public interface Callbacks { public void onTrackIdAvailable(String trackId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public void onTrackIdAvailable(String trackId) {} }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mCompanyUri = intent.getData(); if (mCompanyUri == null) { return; } mCompanyImageSize = getResources().getDimensionPixelSize(R.dimen.sandbox_company_image_size); mCompanyPlaceHolderImage = getResources().getDrawable(R.drawable.sandbox_logo_empty); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mCompanyUri == null) { return; } if (getActivity() instanceof ImageLoader.ImageLoaderProvider) { mImageLoader = ((ImageLoader.ImageLoaderProvider) getActivity()).getImageLoaderInstance(); } // Start background query to load sandbox company details getLoaderManager().initLoader(SandboxQuery._TOKEN, null, this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.sandbox_detail, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { SessionsHelper helper = new SessionsHelper(getActivity()); switch (item.getItemId()) { case R.id.menu_map: if (mRoomId != null && mCompanyName != null) { EasyTracker.getTracker().sendEvent( "Sandbox", "Map", mCompanyName, 0L); LOGD("Tracker", "Map: " + mCompanyName); helper.startMapActivity(mRoomId); return true; } } return false; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_sandbox_detail, null); mName = (TextView) rootView.findViewById(R.id.company_name); mLogo = (ImageView) rootView.findViewById(R.id.company_logo); mUrl = (TextView) rootView.findViewById(R.id.company_url); mDesc = (TextView) rootView.findViewById(R.id.company_desc); mSubtitle = (TextView) rootView.findViewById(R.id.company_subtitle); return rootView; } void buildUiFromCursor(Cursor cursor) { if (getActivity() == null) { return; } if (!cursor.moveToFirst()) { return; } mCompanyName = cursor.getString(SandboxQuery.NAME); mName.setText(mCompanyName); // Start background fetch to load company logo final String logoUrl = cursor.getString(SandboxQuery.LOGO_URL); if (!TextUtils.isEmpty(logoUrl) && mImageLoader != null) { mImageLoader.get(UIUtils.getConferenceImageUrl(logoUrl), mLogo, mCompanyPlaceHolderImage, mCompanyImageSize, mCompanyImageSize); mLogo.setVisibility(View.VISIBLE); } else { mLogo.setVisibility(View.GONE); } mRoomId = cursor.getString(SandboxQuery.ROOM_ID); // Set subtitle: time and room long blockStart = cursor.getLong(SandboxQuery.BLOCK_START); long blockEnd = cursor.getLong(SandboxQuery.BLOCK_END); String roomName = cursor.getString(SandboxQuery.ROOM_NAME); final String subtitle = UIUtils.formatSessionSubtitle( "Sandbox", blockStart, blockEnd, roomName, mBuffer, getActivity()); mSubtitle.setText(subtitle); mUrl.setText(cursor.getString(SandboxQuery.URL)); mDesc.setText(cursor.getString(SandboxQuery.DESC)); String trackId = cursor.getString(SandboxQuery.TRACK_ID); EasyTracker.getTracker().sendView("Sandbox Company: " + mCompanyName); LOGD("Tracker", "Sandbox Company: " + mCompanyName); mCallbacks.onTrackIdAvailable(trackId); } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} * query parameters. */ private interface SandboxQuery { int _TOKEN = 0x4; String[] PROJECTION = { ScheduleContract.Sandbox.COMPANY_NAME, ScheduleContract.Sandbox.COMPANY_DESC, ScheduleContract.Sandbox.COMPANY_URL, ScheduleContract.Sandbox.COMPANY_LOGO_URL, ScheduleContract.Sandbox.TRACK_ID, ScheduleContract.Sandbox.BLOCK_START, ScheduleContract.Sandbox.BLOCK_END, ScheduleContract.Sandbox.ROOM_NAME, ScheduleContract.Sandbox.ROOM_ID }; int NAME = 0; int DESC = 1; int URL = 2; int LOGO_URL = 3; int TRACK_ID = 4; int BLOCK_START = 5; int BLOCK_END = 6; int ROOM_NAME = 7; int ROOM_ID = 8; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { return new CursorLoader(getActivity(), mCompanyUri, SandboxQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { buildUiFromCursor(cursor); } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
Java
/* * Copyright 2012 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.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.support.v7.app.ActionBarActivity; import android.support.v7.view.ActionMode; import android.text.Spannable; import android.text.TextUtils; import android.util.SparseBooleanArray; import android.view.*; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.PrefUtils; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import java.util.ArrayList; import java.util.List; import static com.google.android.apps.iosched.util.LogUtils.*; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; import static com.google.android.apps.iosched.util.UIUtils.formatSessionSubtitle; /** * A {@link ListFragment} showing a list of sessions. */ public class SessionsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor>, MultiSelectionUtil.MultiChoiceModeListener { private static final String TAG = makeLogTag(SessionsFragment.class); private static final String STATE_SELECTED_ID = "selectedId"; private CursorAdapter mAdapter; private String mSelectedSessionId; private MenuItem mStarredMenuItem; private MenuItem mMapMenuItem; private MenuItem mShareMenuItem; private MenuItem mSocialStreamMenuItem; private int mSessionQueryToken; private Handler mHandler = new Handler(); private MultiSelectionUtil.Controller mMultiSelectionController; // instance state while view is destroyed but fragment is alive private Bundle mViewDestroyedInstanceState; public interface Callbacks { /** Return true to select (activate) the session in the list, false otherwise. */ public boolean onSessionSelected(String sessionId); } private static Callbacks sDummyCallbacks = new Callbacks() { @Override public boolean onSessionSelected(String sessionId) { return true; } }; private Callbacks mCallbacks = sDummyCallbacks; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { mSelectedSessionId = savedInstanceState.getString(STATE_SELECTED_ID); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // As of support library r12, calling initLoader for a fragment in a FragmentPagerAdapter // in the fragment's onCreate may cause the same LoaderManager to be dealt to multiple // fragments because their mIndex is -1 (haven't been added to the activity yet). Thus, // we call reloadFromArguments (which calls restartLoader/initLoader) in onActivityCreated. reloadFromArguments(getArguments()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_list_with_empty_container_inset, container, false); TextView emptyView = new TextView(getActivity(), null, R.attr.emptyText); emptyView.setText(UIUtils.shouldShowLiveSessionsOnly(getActivity()) ? R.string.empty_live_streamed_sessions : R.string.empty_sessions); ((ViewGroup) rootView.findViewById(android.R.id.empty)).addView(emptyView); mMultiSelectionController = MultiSelectionUtil.attachMultiSelectionController( (ListView) rootView.findViewById(android.R.id.list), (ActionBarActivity) getActivity(), this); if (savedInstanceState == null && isMenuVisible()) { savedInstanceState = mViewDestroyedInstanceState; } mMultiSelectionController.tryRestoreInstanceState(savedInstanceState); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); if (mMultiSelectionController != null) { mMultiSelectionController.finish(); } mMultiSelectionController = null; } void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments setListAdapter(null); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); Uri sessionsUri = intent.getData(); if (sessionsUri == null) { sessionsUri = ScheduleContract.Sessions.CONTENT_URI; } if (!ScheduleContract.Sessions.isSearchUri(sessionsUri)) { mAdapter = new SessionsAdapter(getActivity()); mSessionQueryToken = SessionsQuery._TOKEN; } else { mAdapter = new SearchAdapter(getActivity()); mSessionQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Force start background query to load sessions getLoaderManager().restartLoader(mSessionQueryToken, arguments, this); } public void setSelectedSessionId(String id) { mSelectedSessionId = id; if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.setBackgroundColor(Color.WHITE); final ListView listView = getListView(); listView.setSelector(android.R.color.transparent); listView.setCacheColorHint(Color.WHITE); } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (!(activity instanceof Callbacks)) { throw new ClassCastException("Activity must implement fragment's callbacks."); } mCallbacks = (Callbacks) activity; activity.getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(activity); sp.registerOnSharedPreferenceChangeListener(mPrefChangeListener); } @Override public void onDetach() { super.onDetach(); mCallbacks = sDummyCallbacks; getActivity().getContentResolver().unregisterContentObserver(mObserver); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); sp.unregisterOnSharedPreferenceChangeListener(mPrefChangeListener); } @Override public void onResume() { super.onResume(); mHandler.post(mRefreshSessionsRunnable); } @Override public void onPause() { super.onPause(); mHandler.removeCallbacks(mRefreshSessionsRunnable); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSelectedSessionId != null) { outState.putString(STATE_SELECTED_ID, mSelectedSessionId); } if (mMultiSelectionController != null) { mMultiSelectionController.saveInstanceState(outState); } } @Override public void setMenuVisibility(boolean menuVisible) { super.setMenuVisibility(menuVisible); if (mMultiSelectionController == null) { return; } // Hide the action mode when the fragment becomes invisible if (!menuVisible) { Bundle bundle = new Bundle(); if (mMultiSelectionController.saveInstanceState(bundle)) { mViewDestroyedInstanceState = bundle; mMultiSelectionController.finish(); } } else if (mViewDestroyedInstanceState != null) { mMultiSelectionController.tryRestoreInstanceState(mViewDestroyedInstanceState); mViewDestroyedInstanceState = null; } } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); String sessionId = cursor.getString(cursor.getColumnIndex( ScheduleContract.Sessions.SESSION_ID)); if (mCallbacks.onSessionSelected(sessionId)) { mSelectedSessionId = sessionId; mAdapter.notifyDataSetChanged(); } } // LoaderCallbacks interface @Override public Loader<Cursor> onCreateLoader(int id, Bundle data) { final Intent intent = BaseActivity.fragmentArgumentsToIntent(data); Uri sessionsUri = intent.getData(); if (sessionsUri == null) { sessionsUri = ScheduleContract.Sessions.CONTENT_URI; } Loader<Cursor> loader = null; String liveStreamedOnlySelection = UIUtils.shouldShowLiveSessionsOnly(getActivity()) ? "IFNULL(" + ScheduleContract.Sessions.SESSION_LIVESTREAM_URL + ",'')!=''" : null; if (id == SessionsQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SessionsQuery.PROJECTION, liveStreamedOnlySelection, null, ScheduleContract.Sessions.DEFAULT_SORT); } else if (id == SearchQuery._TOKEN) { loader = new CursorLoader(getActivity(), sessionsUri, SearchQuery.PROJECTION, liveStreamedOnlySelection, null, ScheduleContract.Sessions.DEFAULT_SORT); } return loader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return; } int token = loader.getId(); if (token == SessionsQuery._TOKEN || token == SearchQuery._TOKEN) { mAdapter.changeCursor(cursor); Bundle arguments = getArguments(); if (arguments != null && arguments.containsKey("_uri")) { String uri = arguments.get("_uri").toString(); if(uri != null && uri.contains("blocks")) { String title = arguments.getString(Intent.EXTRA_TITLE); if (title == null) { title = (String) this.getActivity().getTitle(); } EasyTracker.getTracker().sendView("Session Block: " + title); LOGD("Tracker", "Session Block: " + title); } } } else { LOGD(TAG, "Query complete, Not Actionable: " + token); cursor.close(); } mMultiSelectionController.tryRestoreInstanceState(); } @Override public void onLoaderReset(Loader<Cursor> loader) { } private List<Integer> getCheckedSessionPositions() { List<Integer> checkedSessionPositions = new ArrayList<Integer>(); ListView listView = getListView(); if (listView == null) { return checkedSessionPositions; } SparseBooleanArray checkedPositionsBool = listView.getCheckedItemPositions(); for (int i = 0; i < checkedPositionsBool.size(); i++) { if (checkedPositionsBool.valueAt(i)) { checkedSessionPositions.add(checkedPositionsBool.keyAt(i)); } } return checkedSessionPositions; } // MultiChoiceModeListener interface @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { List<Integer> checkedSessionPositions = getCheckedSessionPositions(); SessionsHelper helper = new SessionsHelper(getActivity()); mode.finish(); switch (item.getItemId()) { case R.id.menu_map: { // multiple selection not supported int position = checkedSessionPositions.get(0); Cursor cursor = (Cursor) mAdapter.getItem(position); String roomId = cursor.getString(SessionsQuery.ROOM_ID); helper.startMapActivity(roomId); String title = cursor.getString(SessionsQuery.TITLE); EasyTracker.getTracker().sendEvent( "Session", "Mapped", title, 0L); LOGV(TAG, "Starred: " + title); return true; } case R.id.menu_star: { // multiple selection supported boolean starred = false; int numChanged = 0; for (int position : checkedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(position); String title = cursor.getString(SessionsQuery.TITLE); String sessionId = cursor.getString(SessionsQuery.SESSION_ID); Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); starred = cursor.getInt(SessionsQuery.STARRED) == 0; helper.setSessionStarred(sessionUri, starred, title); ++numChanged; EasyTracker.getTracker().sendEvent( "Session", starred ? "Starred" : "Unstarred", title, 0L); LOGV(TAG, "Starred: " + title); } Toast.makeText( getActivity(), getResources().getQuantityString(starred ? R.plurals.toast_added_to_schedule : R.plurals.toast_removed_from_schedule, numChanged, numChanged), Toast.LENGTH_SHORT).show(); setSelectedSessionStarred(starred); return true; } case R.id.menu_share: { // multiple selection not supported int position = checkedSessionPositions.get(0); // On ICS+ devices, we normally won't reach this as ShareActionProvider will handle // sharing. Cursor cursor = (Cursor) mAdapter.getItem(position); new SessionsHelper(getActivity()).shareSession(getActivity(), R.string.share_template, cursor.getString(SessionsQuery.TITLE), cursor.getString(SessionsQuery.HASHTAGS), cursor.getString(SessionsQuery.URL)); return true; } case R.id.menu_social_stream: // multiple selection not supported int position = checkedSessionPositions.get(0); Cursor cursor = (Cursor) mAdapter.getItem(position); String hashtags = cursor.getString(SessionsQuery.HASHTAGS); helper.startSocialStream(hashtags); return true; default: LOGW(TAG, "CAB unknown selection=" + item.getItemId()); return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.sessions_context, menu); mStarredMenuItem = menu.findItem(R.id.menu_star); mMapMenuItem = menu.findItem(R.id.menu_map); mShareMenuItem = menu.findItem(R.id.menu_share); mSocialStreamMenuItem = menu.findItem(R.id.menu_social_stream); return true; } @Override public void onDestroyActionMode(ActionMode mode) {} @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return true; } @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { List<Integer> checkedSessionPositions = getCheckedSessionPositions(); int numSelectedSessions = checkedSessionPositions.size(); mode.setTitle(getResources().getQuantityString( R.plurals.title_selected_sessions, numSelectedSessions, numSelectedSessions)); if (numSelectedSessions == 1) { // activate all the menu items mMapMenuItem.setVisible(true); mShareMenuItem.setVisible(true); mStarredMenuItem.setVisible(true); position = checkedSessionPositions.get(0); Cursor cursor = (Cursor) mAdapter.getItem(position); boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; String hashtags = cursor.getString(SessionsQuery.HASHTAGS); mSocialStreamMenuItem.setVisible(!TextUtils.isEmpty(hashtags)); setSelectedSessionStarred(starred); } else { mMapMenuItem.setVisible(false); mShareMenuItem.setVisible(false); mSocialStreamMenuItem.setVisible(false); boolean allStarred = true; boolean allUnstarred = true; for (int pos : checkedSessionPositions) { Cursor cursor = (Cursor) mAdapter.getItem(pos); boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; allStarred = allStarred && starred; allUnstarred = allUnstarred && !starred; } if (allStarred) { setSelectedSessionStarred(true); mStarredMenuItem.setVisible(true); } else if (allUnstarred) { setSelectedSessionStarred(false); mStarredMenuItem.setVisible(true); } else { mStarredMenuItem.setVisible(false); } } } private void setSelectedSessionStarred(boolean starred) { mStarredMenuItem.setTitle(starred ? R.string.description_remove_schedule : R.string.description_add_schedule); mStarredMenuItem.setIcon(starred ? R.drawable.ic_action_remove_schedule : R.drawable.ic_action_add_schedule); } private final Runnable mRefreshSessionsRunnable = new Runnable() { public void run() { if (mAdapter != null) { // This is used to refresh session title colors. mAdapter.notifyDataSetChanged(); } // Check again on the next quarter hour, with some padding to // account for network // time differences. long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000; mHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour); } }; private final SharedPreferences.OnSharedPreferenceChangeListener mPrefChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sp, String key) { if (isAdded() && mAdapter != null) { if (PrefUtils.PREF_LOCAL_TIMES.equals(key)) { PrefUtils.isUsingLocalTime(getActivity(), true); // force update mAdapter.notifyDataSetInvalidated(); } else if (PrefUtils.PREF_ATTENDEE_AT_VENUE.equals(key)) { PrefUtils.isAttendeeAtVenue(getActivity(), true); // force update mAdapter.notifyDataSetInvalidated(); } } } }; private final ContentObserver mObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (!isAdded()) { return; } Loader<Cursor> loader = getLoaderManager().getLoader(mSessionQueryToken); if (loader != null) { loader.forceLoad(); } } }; /** * {@link CursorAdapter} that renders a {@link SessionsQuery}. */ private class SessionsAdapter extends CursorAdapter { StringBuilder mBuffer = new StringBuilder(); public SessionsAdapter(Context context) { super(context, null, 0); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId == null) { return; } UIUtils.setActivatedCompat(view, sessionId.equals(mSelectedSessionId)); final TextView titleView = (TextView) view.findViewById(R.id.session_title); final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle); final String sessionTitle = cursor.getString(SessionsQuery.TITLE); titleView.setText(sessionTitle); // Format time block this session occupies final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END); final String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = formatSessionSubtitle( sessionTitle, blockStart, blockEnd, roomName, mBuffer, context); final boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; view.findViewById(R.id.indicator_in_schedule).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); final boolean hasLivestream = !TextUtils.isEmpty( cursor.getString(SessionsQuery.LIVESTREAM_URL)); // Show past/present/future and livestream status for this block. UIUtils.updateTimeAndLivestreamBlockUI(context, blockStart, blockEnd, hasLivestream, titleView, subtitleView, subtitle); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null, 0); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { UIUtils.setActivatedCompat(view, cursor.getString(SessionsQuery.SESSION_ID) .equals(mSelectedSessionId)); ((TextView) view.findViewById(R.id.session_title)).setText(cursor .getString(SearchQuery.TITLE)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.session_subtitle)).setText(styledSnippet); final boolean starred = cursor.getInt(SearchQuery.STARRED) != 0; view.findViewById(R.id.indicator_in_schedule).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} * query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Rooms.ROOM_NAME, ScheduleContract.Rooms.ROOM_ID, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int BLOCK_START = 4; int BLOCK_END = 5; int ROOM_NAME = 6; int ROOM_ID = 7; int HASHTAGS = 8; int URL = 9; int LIVESTREAM_URL = 10; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} * search query parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SEARCH_SNIPPET, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int SEARCH_SNIPPET = 4; } }
Java
/* * Copyright 2012 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.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Presentation; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Color; import android.media.MediaRouter; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v7.app.ActionBar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.ViewPager; import android.support.v4.widget.CursorAdapter; import android.text.TextUtils; import android.view.*; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; import android.widget.Toast; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.Config; import com.google.android.apps.iosched.R; 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.Tracks; import com.google.android.apps.iosched.util.SessionsHelper; import com.google.android.apps.iosched.util.UIUtils; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerSupportFragment; import java.util.ArrayList; import java.util.HashMap; import static com.google.android.apps.iosched.util.LogUtils.LOGD; import static com.google.android.apps.iosched.util.LogUtils.LOGE; import static com.google.android.apps.iosched.util.LogUtils.makeLogTag; /** * An activity that displays the session live stream video which is pulled in from YouTube. The * UI adapts for both phone and tablet. As we want to prevent the YouTube player from restarting * and buffering again on orientation change, we handle configuration changes manually. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SessionLivestreamActivity extends BaseActivity implements LoaderCallbacks<Cursor>, YouTubePlayer.OnInitializedListener, YouTubePlayer.PlayerStateChangeListener, YouTubePlayer.OnFullscreenListener, ActionBar.OnNavigationListener { private static final String TAG = makeLogTag(SessionLivestreamActivity.class); private static final String EXTRA_PREFIX = "com.google.android.iosched.extra."; private static final int YOUTUBE_RECOVERY_RESULT = 1; private static final String LOADER_SESSIONS_ARG = "futureSessions"; public static final String EXTRA_YOUTUBE_URL = EXTRA_PREFIX + "youtube_url"; public static final String EXTRA_TRACK = EXTRA_PREFIX + "track"; public static final String EXTRA_TITLE = EXTRA_PREFIX + "title"; public static final String EXTRA_ABSTRACT = EXTRA_PREFIX + "abstract"; public static final String KEYNOTE_TRACK_NAME = "Keynote"; private static final String TAG_SESSION_SUMMARY = "session_summary"; private static final String TAG_CAPTIONS = "captions"; private static final int TABNUM_SESSION_SUMMARY = 0; private static final int TABNUM_SOCIAL_STREAM = 1; private static final int TABNUM_LIVE_CAPTIONS = 2; private static final String EXTRA_TAB_STATE = "tag"; private static final int STREAM_REFRESH_TIME = 5 * 60 * 1000; // 5 minutes private boolean mIsTablet; private boolean mIsFullscreen = false; private boolean mLoadFromExtras = false; private boolean mTrackPlay = true; private TabHost mTabHost; private TabsAdapter mTabsAdapter; private YouTubePlayer mYouTubePlayer; private YouTubePlayerSupportFragment mYouTubeFragment; private LinearLayout mPlayerContainer; private String mYouTubeVideoId; private LinearLayout mMainLayout; private LinearLayout mVideoLayout; private LinearLayout mExtraLayout; private FrameLayout mPresentationControls; private FrameLayout mSummaryLayout; private FrameLayout mFullscreenCaptions; private MenuItem mCaptionsMenuItem; private MenuItem mShareMenuItem; private MenuItem mPresentationMenuItem; private Runnable mShareMenuDeferredSetup; private Runnable mSessionSummaryDeferredSetup; private SessionShareData mSessionShareData; private boolean mSessionsFound; private boolean isKeynote = false; private Handler mHandler = new Handler(); private int mYouTubeFullscreenFlags; private LivestreamAdapter mLivestreamAdapter; private Uri mSessionUri; private String mSessionId; private String mTrackName; private MediaRouter mMediaRouter; private YouTubePresentation mPresentation; private MediaRouter.SimpleCallback mMediaRouterCallback; @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override protected void onCreate(Bundle savedInstanceState) { if (UIUtils.hasICS()) { // We can't use this mode on HC as compatible ActionBar doesn't work well with the YT // player in full screen mode (no overlays allowed). requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); } super.onCreate(savedInstanceState); setContentView(R.layout.activity_session_livestream); mIsTablet = UIUtils.isHoneycombTablet(this); // Set up YouTube player mYouTubeFragment = (YouTubePlayerSupportFragment) getSupportFragmentManager().findFragmentById(R.id.livestream_player); mYouTubeFragment.initialize(Config.YOUTUBE_API_KEY, this); // Views that are common over all layouts mMainLayout = (LinearLayout) findViewById(R.id.livestream_mainlayout); mPresentationControls = (FrameLayout) findViewById(R.id.presentation_controls); adjustMainLayoutForActionBar(); mPlayerContainer = (LinearLayout) findViewById(R.id.livestream_player_container); mFullscreenCaptions = (FrameLayout) findViewById(R.id.fullscreen_captions); final LayoutParams params = (LayoutParams) mFullscreenCaptions.getLayoutParams(); params.setMargins(0, getActionBarHeightPx(), 0, getActionBarHeightPx()); mFullscreenCaptions.setLayoutParams(params); ViewPager viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setOffscreenPageLimit(2); if (!mIsTablet) { viewPager.setPageMarginDrawable(R.drawable.grey_border_inset_lr); } viewPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin_width)); // Set up tabs w/ViewPager mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabHost.setup(); mTabsAdapter = new TabsAdapter(this, mTabHost, viewPager); if (mIsTablet) { // Tablet UI specific views getSupportFragmentManager().beginTransaction().add(R.id.livestream_summary, new SessionSummaryFragment(), TAG_SESSION_SUMMARY).commit(); mVideoLayout = (LinearLayout) findViewById(R.id.livestream_videolayout); mExtraLayout = (LinearLayout) findViewById(R.id.livestream_extralayout); mSummaryLayout = (FrameLayout) findViewById(R.id.livestream_summary); } else { // Handset UI specific views mTabsAdapter.addTab( getString(R.string.session_livestream_info), new SessionSummaryFragment(), TABNUM_SESSION_SUMMARY); } mTabsAdapter.addTab(getString(R.string.title_stream), new SocialStreamFragment(), TABNUM_SOCIAL_STREAM); mTabsAdapter.addTab(getString(R.string.session_livestream_captions), new SessionLiveCaptionsFragment(), TABNUM_LIVE_CAPTIONS); if (savedInstanceState != null) { mTabHost.setCurrentTabByTag(savedInstanceState.getString(EXTRA_TAB_STATE)); } // Reload all other data in this activity reloadFromIntent(getIntent()); // Update layout based on current configuration updateLayout(getResources().getConfiguration()); // Set up action bar if (!mLoadFromExtras) { // Start sessions query to populate action bar navigation spinner getSupportLoaderManager().initLoader(SessionsQuery._TOKEN, null, this); // Set up action bar mLivestreamAdapter = new LivestreamAdapter(getSupportActionBar().getThemedContext()); final ActionBar actionBar = getSupportActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(mLivestreamAdapter, this); actionBar.setDisplayShowTitleEnabled(false); } // Media Router and Presentation set up if (UIUtils.hasJellyBeanMR1()) { mMediaRouterCallback = new MediaRouter.SimpleCallback() { @Override public void onRouteSelected(MediaRouter router, int type, MediaRouter.RouteInfo info) { LOGD(TAG, "onRouteSelected: type=" + type + ", info=" + info); updatePresentation(); } @Override public void onRouteUnselected(MediaRouter router, int type, MediaRouter.RouteInfo info) { LOGD(TAG, "onRouteUnselected: type=" + type + ", info=" + info); updatePresentation(); } @Override public void onRoutePresentationDisplayChanged(MediaRouter router, MediaRouter.RouteInfo info) { LOGD(TAG, "onRoutePresentationDisplayChanged: info=" + info); updatePresentation(); } }; mMediaRouter = (MediaRouter) getSystemService(Context.MEDIA_ROUTER_SERVICE); final ImageButton playPauseButton = (ImageButton) findViewById(R.id.play_pause_button); playPauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mYouTubePlayer != null) { if (mYouTubePlayer.isPlaying()) { mYouTubePlayer.pause(); playPauseButton.setImageResource(R.drawable.ic_livestream_play); } else { mYouTubePlayer.play(); playPauseButton.setImageResource(R.drawable.ic_livestream_pause); } } } }); updatePresentation(); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override protected void onResume() { super.onResume(); if (mSessionSummaryDeferredSetup != null) { mSessionSummaryDeferredSetup.run(); mSessionSummaryDeferredSetup = null; } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); if (UIUtils.hasJellyBeanMR1()) { mMediaRouter.addCallback(MediaRouter.ROUTE_TYPE_LIVE_VIDEO, mMediaRouterCallback); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override protected void onPause() { super.onPause(); mHandler.removeCallbacks(mStreamRefreshRunnable); if (UIUtils.hasJellyBeanMR1()) { mMediaRouter.removeCallback(mMediaRouterCallback); } } @Override public void onStop() { super.onStop(); // Dismiss the presentation when the activity is not visible if (mPresentation != null) { LOGD(TAG, "Dismissing presentation because the activity is no longer visible."); mPresentation.dismiss(); mPresentation = null; } } /** * Reloads all data in the activity and fragments from a given intent * @param intent The intent to load from */ private void reloadFromIntent(Intent intent) { final String youtubeUrl = intent.getStringExtra(EXTRA_YOUTUBE_URL); // Check if youtube url is set as an extra first if (youtubeUrl != null) { mLoadFromExtras = true; String trackName = intent.getStringExtra(EXTRA_TRACK); String actionBarTitle; if (trackName == null) { actionBarTitle = getString(R.string.session_livestream_title); } else { isKeynote = KEYNOTE_TRACK_NAME.equals(trackName); actionBarTitle = trackName + " - " + getString(R.string.session_livestream_title); } getSupportActionBar().setTitle(actionBarTitle); updateSessionViews(youtubeUrl, intent.getStringExtra(EXTRA_TITLE), intent.getStringExtra(EXTRA_ABSTRACT), UIUtils.CONFERENCE_HASHTAG, trackName); } else { // Otherwise load from session uri reloadFromUri(intent.getData()); } } /** * Reloads all data in the activity and fragments from a given uri * @param newUri The session uri to load from */ private void reloadFromUri(Uri newUri) { mSessionUri = newUri; if (mSessionUri != null && mSessionUri.getPathSegments().size() >= 2) { mSessionId = Sessions.getSessionId(mSessionUri); getSupportLoaderManager().restartLoader(SessionSummaryQuery._TOKEN, null, this); } else { // No session uri, get out mSessionUri = null; finish(); } } /** * Helper method to start this activity using only extras (rather than session uri). * @param context The package context * @param youtubeUrl The youtube url or video id to load * @param track The track title (appears as part of action bar title), can be null * @param title The title to show in the session info fragment, can be null * @param sessionAbstract The session abstract to show in the session info fragment, can be null */ public static void startFromExtras(Context context, String youtubeUrl, String track, String title, String sessionAbstract) { if (youtubeUrl == null) { return; } final Intent i = new Intent(); i.setClass(context, SessionLivestreamActivity.class); i.putExtra(EXTRA_YOUTUBE_URL, youtubeUrl); i.putExtra(EXTRA_TRACK, track); i.putExtra(EXTRA_TITLE, title); i.putExtra(EXTRA_ABSTRACT, sessionAbstract); context.startActivity(i); } /** * Start a keynote live stream from extras. This sets the track name correctly so captions * will be correctly displayed. * * This will play the video given in youtubeUrl, however if a number ranging from 1-99 is * passed in this param instead it will be parsed and used to lookup a youtube ID from a * google spreadsheet using the param as the spreadsheet row number. */ public static void startKeynoteFromExtras(Context context, String youtubeUrl, String title, String sessionAbstract) { startFromExtras(context, youtubeUrl, KEYNOTE_TRACK_NAME, title, sessionAbstract); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mTabHost != null) { outState.putString(EXTRA_TAB_STATE, mTabHost.getCurrentTabTag()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.session_livestream, menu); mCaptionsMenuItem = menu.findItem(R.id.menu_captions); mPresentationMenuItem = menu.findItem(R.id.menu_presentation); mPresentationMenuItem.setVisible(mPresentation != null); updatePresentationMenuItem(mPresentation != null); mShareMenuItem = menu.findItem(R.id.menu_share); if (mShareMenuDeferredSetup != null) { mShareMenuDeferredSetup.run(); } if (!mIsTablet && Configuration.ORIENTATION_LANDSCAPE == getResources().getConfiguration().orientation) { mCaptionsMenuItem.setVisible(true); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_captions: if (mIsFullscreen) { if (mFullscreenCaptions.getVisibility() == View.GONE) { mFullscreenCaptions.setVisibility(View.VISIBLE); SessionLiveCaptionsFragment captionsFragment; captionsFragment = (SessionLiveCaptionsFragment) getSupportFragmentManager().findFragmentByTag(TAG_CAPTIONS); if (captionsFragment == null) { captionsFragment = new SessionLiveCaptionsFragment(); captionsFragment.setDarkTheme(true); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(R.id.fullscreen_captions, captionsFragment, TAG_CAPTIONS); ft.commit(); } captionsFragment.setTrackName(mTrackName); return true; } } mFullscreenCaptions.setVisibility(View.GONE); break; case R.id.menu_share: if (mSessionShareData != null) { new SessionsHelper(this).shareSession(this, R.string.share_livestream_template, mSessionShareData.title, mSessionShareData.hashtag, mSessionShareData.sessionUrl); return true; } break; case R.id.menu_presentation: if (mPresentation != null) { mPresentation.dismiss(); } else { updatePresentation(); } break; } return super.onOptionsItemSelected(item); } @Override public void onConfigurationChanged(Configuration newConfig) { // Need to handle configuration changes so as not to interrupt YT player and require // buffering again updateLayout(newConfig); super.onConfigurationChanged(newConfig); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { final Cursor cursor = (Cursor) mLivestreamAdapter.getItem(itemPosition); String trackName = cursor.getString(SessionsQuery.TRACK_NAME); int trackColor = cursor.getInt(SessionsQuery.TRACK_COLOR); setActionBarTrackIcon(trackName, trackColor); final String sessionId = cursor.getString(SessionsQuery.SESSION_ID); if (sessionId != null) { reloadFromUri(Sessions.buildSessionUri(sessionId)); return true; } return false; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { switch (id) { case SessionSummaryQuery._TOKEN: return new CursorLoader(this, Sessions.buildWithTracksUri(mSessionId), SessionSummaryQuery.PROJECTION, null, null, null); case SessionsQuery._TOKEN: boolean futureSessions = false; if (args != null) { futureSessions = args.getBoolean(LOADER_SESSIONS_ARG, false); } final long currentTime = UIUtils.getCurrentTime(this); String selection = Sessions.LIVESTREAM_SELECTION + " and "; String[] selectionArgs; if (!futureSessions) { selection += Sessions.AT_TIME_SELECTION; selectionArgs = Sessions.buildAtTimeSelectionArgs(currentTime); } else { selection += Sessions.UPCOMING_SELECTION; selectionArgs = Sessions.buildUpcomingSelectionArgs(currentTime); } return new CursorLoader(this, Sessions.buildWithTracksUri(), SessionsQuery.PROJECTION, selection, selectionArgs, null); } return null; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { switch (loader.getId()) { case SessionSummaryQuery._TOKEN: loadSession(data); break; case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(data); if (data != null && data.getCount() > 0) { mSessionsFound = true; final int selected = locateSelectedItem(data); getSupportActionBar().setSelectedNavigationItem(selected); } else if (mSessionsFound) { mSessionsFound = false; final Bundle bundle = new Bundle(); bundle.putBoolean(LOADER_SESSIONS_ARG, true); getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, bundle, this); } else { finish(); } break; } } /** * Locates which item should be selected in the action bar drop-down spinner based on the * current active session uri * @param data The data * @return The row num of the item that should be selected or 0 if not found */ private int locateSelectedItem(Cursor data) { int selected = 0; if (data != null && (mSessionId != null || mTrackName != null)) { final boolean findNextSessionByTrack = mTrackName != null; while (data.moveToNext()) { if (findNextSessionByTrack) { if (mTrackName.equals(data.getString(SessionsQuery.TRACK_NAME))) { selected = data.getPosition(); mTrackName = null; break; } } else { if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) { selected = data.getPosition(); } } } } return selected; } @Override public void onLoaderReset(Loader<Cursor> loader) { switch (loader.getId()) { case SessionsQuery._TOKEN: mLivestreamAdapter.swapCursor(null); break; } } @Override public void onFullscreen(boolean fullscreen) { layoutFullscreenVideo(fullscreen); } @Override public void onLoading() { } @Override public void onLoaded(String s) { } @Override public void onAdStarted() { } @Override public void onVideoStarted() { } @Override public void onVideoEnded() { } @Override public void onError(YouTubePlayer.ErrorReason errorReason) { Toast.makeText(this, R.string.session_livestream_error_playback, Toast.LENGTH_LONG).show(); LOGE(TAG, errorReason.toString()); } private void loadSession(Cursor data) { if (data != null && data.moveToFirst()) { mTrackName = data.getString(SessionSummaryQuery.TRACK_NAME); if (TextUtils.isEmpty(mTrackName)) { mTrackName = KEYNOTE_TRACK_NAME; isKeynote = true; } final long currentTime = UIUtils.getCurrentTime(this); if (currentTime > data.getLong(SessionSummaryQuery.BLOCK_END)) { getSupportLoaderManager().restartLoader(SessionsQuery._TOKEN, null, this); return; } updateTagStreamFragment(data.getString(SessionSummaryQuery.HASHTAGS)); updateSessionViews( data.getString(SessionSummaryQuery.LIVESTREAM_URL), data.getString(SessionSummaryQuery.TITLE), data.getString(SessionSummaryQuery.ABSTRACT), data.getString(SessionSummaryQuery.HASHTAGS), mTrackName); } } /** * Updates views that rely on session data from explicit strings. */ private void updateSessionViews(final String youtubeUrl, final String title, final String sessionAbstract, final String hashTag, final String trackName) { if (youtubeUrl == null) { // Get out, nothing to do here finish(); return; } mTrackName = trackName; String youtubeVideoId = youtubeUrl; if (youtubeUrl.startsWith("http")) { final Uri youTubeUri = Uri.parse(youtubeUrl); youtubeVideoId = youTubeUri.getQueryParameter("v"); } // Play the video playVideo(youtubeVideoId); if (mTrackPlay) { EasyTracker.getTracker().sendView("Live Streaming: " + title); LOGD("Tracker", "Live Streaming: " + title); } final String newYoutubeUrl = Config.YOUTUBE_SHARE_URL_PREFIX + youtubeVideoId; mSessionShareData = new SessionShareData(title, hashTag, newYoutubeUrl); mShareMenuDeferredSetup = new Runnable() { @Override public void run() { new SessionsHelper(SessionLivestreamActivity.this) .tryConfigureShareMenuItem(mShareMenuItem, R.string.share_livestream_template, title, hashTag, newYoutubeUrl); } }; if (mShareMenuItem != null) { mShareMenuDeferredSetup.run(); mShareMenuDeferredSetup = null; } mSessionSummaryDeferredSetup = new Runnable() { @Override public void run() { updateSessionSummaryFragment(title, sessionAbstract); updateSessionLiveCaptionsFragment(trackName); } }; if (!mLoadFromExtras) { mSessionSummaryDeferredSetup.run(); mSessionSummaryDeferredSetup = null; } } private void updateSessionSummaryFragment(String title, String sessionAbstract) { SessionSummaryFragment sessionSummaryFragment = null; if (mIsTablet) { sessionSummaryFragment = (SessionSummaryFragment) getSupportFragmentManager().findFragmentByTag(TAG_SESSION_SUMMARY); } else { if (mTabsAdapter.mFragments.containsKey(TABNUM_SESSION_SUMMARY)) { sessionSummaryFragment = (SessionSummaryFragment) mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY); } } if (sessionSummaryFragment != null) { sessionSummaryFragment.setSessionSummaryInfo( isKeynote ? getString(R.string.session_livestream_keynote_title, title) : title, (isKeynote && TextUtils.isEmpty(sessionAbstract)) ? getString(R.string.session_livestream_keynote_desc) : sessionAbstract); } } private Runnable mStreamRefreshRunnable = new Runnable() { @Override public void run() { if (mTabsAdapter != null && mTabsAdapter.mFragments != null && mTabsAdapter.mFragments.containsKey(TABNUM_SOCIAL_STREAM)) { final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); socialStreamFragment.refresh(); } mHandler.postDelayed(mStreamRefreshRunnable, STREAM_REFRESH_TIME); } }; private void updateTagStreamFragment(String trackHashTag) { String hashTags = UIUtils.CONFERENCE_HASHTAG; if (!TextUtils.isEmpty(trackHashTag)) { hashTags += " " + trackHashTag; } if (mTabsAdapter.mFragments.containsKey(TABNUM_SOCIAL_STREAM)) { final SocialStreamFragment socialStreamFragment = (SocialStreamFragment) mTabsAdapter.mFragments.get(TABNUM_SOCIAL_STREAM); socialStreamFragment.refresh(hashTags); } } private void updateSessionLiveCaptionsFragment(String trackName) { if (mTabsAdapter.mFragments.containsKey(TABNUM_LIVE_CAPTIONS)) { final SessionLiveCaptionsFragment captionsFragment = (SessionLiveCaptionsFragment) mTabsAdapter.mFragments.get(TABNUM_LIVE_CAPTIONS); captionsFragment.setTrackName(trackName); } } private void playVideo(String videoId) { if ((TextUtils.isEmpty(mYouTubeVideoId) || !mYouTubeVideoId.equals(videoId)) && !TextUtils.isEmpty(videoId)) { mYouTubeVideoId = videoId; if (mYouTubePlayer != null) { mYouTubePlayer.loadVideo(mYouTubeVideoId); } mTrackPlay = true; if (mSessionShareData != null) { mSessionShareData.sessionUrl = Config.YOUTUBE_SHARE_URL_PREFIX + mYouTubeVideoId; } } } @Override public Intent getParentActivityIntent() { if (mLoadFromExtras || isKeynote || mSessionUri == null) { return new Intent(this, HomeActivity.class); } else { return new Intent(Intent.ACTION_VIEW, mSessionUri); } } @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) { // Set up YouTube player mYouTubePlayer = youTubePlayer; mYouTubePlayer.setPlayerStateChangeListener(this); mYouTubePlayer.setFullscreen(mIsFullscreen); mYouTubePlayer.setOnFullscreenListener(this); // YouTube player flags: use a custom full screen layout; let the YouTube player control // the system UI (hiding navigation controls, ActionBar etc); and let the YouTube player // handle the orientation state of the activity. mYouTubeFullscreenFlags = YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT | YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI | YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION; // On smaller screen devices always switch to full screen in landscape mode if (!mIsTablet) { mYouTubeFullscreenFlags |= YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE; } // Apply full screen flags setFullscreenFlags(); // If a presentation display is available, set YouTube player style to minimal if (mPresentation != null) { mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL); } // Load the requested video if (!TextUtils.isEmpty(mYouTubeVideoId)) { mYouTubePlayer.loadVideo(mYouTubeVideoId); } updatePresentation(); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) { LOGE(TAG, result.toString()); if (result.isUserRecoverableError()) { result.getErrorDialog(this, YOUTUBE_RECOVERY_RESULT).show(); } else { String errorMessage = getString(R.string.session_livestream_error_init, result.toString()); Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == YOUTUBE_RECOVERY_RESULT) { if (mYouTubeFragment != null) { mYouTubeFragment.initialize(Config.YOUTUBE_API_KEY, this); } } } /** * Updates the layout based on the provided configuration */ private void updateLayout(Configuration config) { if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) { if (mIsTablet) { layoutTabletForLandscape(); } else { layoutPhoneForLandscape(); } } else { if (mIsTablet) { layoutTabletForPortrait(); } else { layoutPhoneForPortrait(); } } } private void layoutPhoneForLandscape() { layoutFullscreenVideo(true); } private void layoutPhoneForPortrait() { layoutFullscreenVideo(false); if (mTabsAdapter.mFragments.containsKey(TABNUM_SESSION_SUMMARY)) { ((SessionSummaryFragment) mTabsAdapter.mFragments.get(TABNUM_SESSION_SUMMARY)).updateViews(); } } private void layoutTabletForLandscape() { mMainLayout.setOrientation(LinearLayout.HORIZONTAL); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.height = LayoutParams.MATCH_PARENT; videoLayoutParams.width = 0; videoLayoutParams.weight = 1; mVideoLayout.setLayoutParams(videoLayoutParams); final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams(); extraLayoutParams.height = LayoutParams.MATCH_PARENT; extraLayoutParams.width = 0; extraLayoutParams.weight = 1; mExtraLayout.setLayoutParams(extraLayoutParams); } private void layoutTabletForPortrait() { mMainLayout.setOrientation(LinearLayout.VERTICAL); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.width = LayoutParams.MATCH_PARENT; if (mLoadFromExtras) { // Loading from extras, let the top fragment wrap_content videoLayoutParams.height = LayoutParams.WRAP_CONTENT; videoLayoutParams.weight = 0; } else { // Otherwise the session description will be longer, give it some space videoLayoutParams.height = 0; videoLayoutParams.weight = 7; } mVideoLayout.setLayoutParams(videoLayoutParams); final LayoutParams extraLayoutParams = (LayoutParams) mExtraLayout.getLayoutParams(); extraLayoutParams.width = LayoutParams.MATCH_PARENT; extraLayoutParams.height = 0; extraLayoutParams.weight = 5; mExtraLayout.setLayoutParams(extraLayoutParams); } private void layoutFullscreenVideo(boolean fullscreen) { if (mIsFullscreen != fullscreen) { mIsFullscreen = fullscreen; if (mIsTablet) { // Tablet specific full screen layout layoutTabletFullscreen(fullscreen); } else { // Phone specific full screen layout layoutPhoneFullscreen(fullscreen); } // Full screen layout changes for all form factors final LayoutParams params = (LayoutParams) mPlayerContainer.getLayoutParams(); if (fullscreen) { if (mCaptionsMenuItem != null) { mCaptionsMenuItem.setVisible(true); } params.height = LayoutParams.MATCH_PARENT; mMainLayout.setPadding(0, 0, 0, 0); } else { getSupportActionBar().show(); if (mCaptionsMenuItem != null) { mCaptionsMenuItem.setVisible(false); } mFullscreenCaptions.setVisibility(View.GONE); params.height = LayoutParams.WRAP_CONTENT; adjustMainLayoutForActionBar(); } View youTubePlayerView = mYouTubeFragment.getView(); if (youTubePlayerView != null) { ViewGroup.LayoutParams playerParams = mYouTubeFragment.getView().getLayoutParams(); playerParams.height = fullscreen ? LayoutParams.MATCH_PARENT : LayoutParams.WRAP_CONTENT; youTubePlayerView.setLayoutParams(playerParams); } mPlayerContainer.setLayoutParams(params); } } private void adjustMainLayoutForActionBar() { if (UIUtils.hasICS()) { // On ICS+ we use FEATURE_ACTION_BAR_OVERLAY so full screen mode doesn't need to // re-adjust layouts when hiding action bar. To account for this we add action bar // height pack to the padding when not in full screen mode. mMainLayout.setPadding(0, getActionBarHeightPx(), 0, 0); } } /** * Adjusts tablet layouts for full screen video. * * @param fullscreen True to layout in full screen, false to switch to regular layout */ private void layoutTabletFullscreen(boolean fullscreen) { if (fullscreen) { mExtraLayout.setVisibility(View.GONE); mSummaryLayout.setVisibility(View.GONE); mVideoLayout.setPadding(0, 0, 0, 0); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(0, 0, 0, 0); mVideoLayout.setLayoutParams(videoLayoutParams); } else { final int padding = getResources().getDimensionPixelSize(R.dimen.multipane_half_padding); mExtraLayout.setVisibility(View.VISIBLE); mSummaryLayout.setVisibility(View.VISIBLE); mVideoLayout.setBackgroundResource(R.drawable.grey_frame_on_white); final LayoutParams videoLayoutParams = (LayoutParams) mVideoLayout.getLayoutParams(); videoLayoutParams.setMargins(padding, padding, padding, padding); mVideoLayout.setLayoutParams(videoLayoutParams); } } /** * Adjusts phone layouts for full screen video. */ private void layoutPhoneFullscreen(boolean fullscreen) { if (fullscreen) { mTabHost.setVisibility(View.GONE); if (mYouTubePlayer != null) { mYouTubePlayer.setFullscreen(true); } } else { mTabHost.setVisibility(View.VISIBLE); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } } private int getActionBarHeightPx() { int[] attrs = new int[] { android.R.attr.actionBarSize }; return (int) getTheme().obtainStyledAttributes(attrs).getDimension(0, 0f); } /** * Adapter that backs the action bar drop-down spinner. */ private class LivestreamAdapter extends CursorAdapter { LayoutInflater mLayoutInflater; public LivestreamAdapter(Context context) { super(context, null, 0); if (UIUtils.hasICS()) { mLayoutInflater = (LayoutInflater) getSupportActionBar().getThemedContext() .getSystemService(LAYOUT_INFLATER_SERVICE); } else { mLayoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); } } @Override public Object getItem(int position) { mCursor.moveToPosition(position); return mCursor; } @Override public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the drop-down spinner views return mLayoutInflater.inflate( R.layout.spinner_item_session_livestream, parent, false); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // Inflate view that appears in the selected spinner return mLayoutInflater.inflate(android.R.layout.simple_spinner_item, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { // Bind view that appears in the selected spinner or in the drop-down final TextView titleView = (TextView) view.findViewById(android.R.id.text1); final TextView subTitleView = (TextView) view.findViewById(android.R.id.text2); String trackName = cursor.getString(SessionsQuery.TRACK_NAME); if (TextUtils.isEmpty(trackName)) { trackName = getString(R.string.app_name); } else { trackName = getString(R.string.session_livestream_track_title, trackName); } String sessionTitle = cursor.getString(SessionsQuery.TITLE); if (subTitleView != null) { // Drop-down view titleView.setText(trackName); subTitleView.setText(sessionTitle); } else { // Selected view titleView.setText(getString(R.string.session_livestream_title) + ": " + trackName); } } } /** * Adapter that backs the ViewPager tabs on the phone UI. */ private static class TabsAdapter extends FragmentPagerAdapter implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener { private final FragmentActivity mContext; private final TabHost mTabHost; private final ViewPager mViewPager; public final HashMap<Integer, Fragment> mFragments; private final ArrayList<Integer> mTabNums; private int tabCount = 0; static class DummyTabFactory implements TabHost.TabContentFactory { private final Context mContext; public DummyTabFactory(Context context) { mContext = context; } @Override public View createTabContent(String tag) { View v = new View(mContext); v.setMinimumWidth(0); v.setMinimumHeight(0); return v; } } @SuppressLint("UseSparseArrays") public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) { super(activity.getSupportFragmentManager()); mFragments = new HashMap<Integer, Fragment>(3); mContext = activity; mTabHost = tabHost; mViewPager = pager; mTabHost.setOnTabChangedListener(this); mViewPager.setAdapter(this); mViewPager.setOnPageChangeListener(this); mTabNums = new ArrayList<Integer>(3); } public void addTab(String tabTitle, Fragment newFragment, int tabId) { ViewGroup tabWidget = (ViewGroup) mTabHost.findViewById(android.R.id.tabs); TextView tabIndicatorView = (TextView) mContext.getLayoutInflater().inflate( R.layout.tab_indicator_color, tabWidget, false); tabIndicatorView.setText(tabTitle); final TabHost.TabSpec tabSpec = mTabHost.newTabSpec(String.valueOf(tabCount++)); tabSpec.setIndicator(tabIndicatorView); tabSpec.setContent(new DummyTabFactory(mContext)); mTabHost.addTab(tabSpec); mFragments.put(tabId, newFragment); mTabNums.add(tabId); notifyDataSetChanged(); } @Override public int getCount() { return mFragments.size(); } @Override public Fragment getItem(int position) { return mFragments.get(mTabNums.get(position)); } @Override public void onTabChanged(String tabId) { int position = mTabHost.getCurrentTab(); mViewPager.setCurrentItem(position); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { // Unfortunately when TabHost changes the current tab, it kindly also takes care of // putting focus on it when not in touch mode. The jerk. This hack tries to prevent // this from pulling focus out of our ViewPager. TabWidget widget = mTabHost.getTabWidget(); int oldFocusability = widget.getDescendantFocusability(); widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); mTabHost.setCurrentTab(position); widget.setDescendantFocusability(oldFocusability); } @Override public void onPageScrollStateChanged(int state) { } } /** * Simple fragment that inflates a session summary layout that displays session title and * abstract. */ public static class SessionSummaryFragment extends Fragment { private TextView mTitleView; private TextView mAbstractView; private String mTitle; private String mAbstract; public SessionSummaryFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_session_summary, null); mTitleView = (TextView) view.findViewById(R.id.session_title); mAbstractView = (TextView) view.findViewById(R.id.session_abstract); updateViews(); return view; } public void setSessionSummaryInfo(String sessionTitle, String sessionAbstract) { mTitle = sessionTitle; mAbstract = sessionAbstract; updateViews(); } public void updateViews() { if (mTitleView != null && mAbstractView != null) { mTitleView.setText(mTitle); if (!TextUtils.isEmpty(mAbstract)) { mAbstractView.setVisibility(View.VISIBLE); mAbstractView.setText(mAbstract); } else { mAbstractView.setVisibility(View.GONE); } } } } /** * Simple fragment that shows the live captions. */ public static class SessionLiveCaptionsFragment extends Fragment { private static final String CAPTIONS_DARK_THEME_URL_PARAM = "&theme=dark"; private FrameLayout mContainer; private WebView mWebView; private TextView mNoCaptionsTextView; private boolean mDarkTheme = false; private String mSessionTrack; public SessionLiveCaptionsFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_session_captions, null); mContainer = (FrameLayout) view.findViewById(R.id.session_caption_container); if (!UIUtils.isTablet(getActivity())) { mContainer.setBackgroundColor(Color.WHITE); } mNoCaptionsTextView = (TextView) view.findViewById(android.R.id.empty); mWebView = (WebView) view.findViewById(R.id.session_caption_area); mWebView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { // Disable text selection in WebView (doesn't work well with the YT player // triggering full screen chrome after a timeout) return true; } }); mWebView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { showNoCaptionsAvailable(); } }); updateViews(); return view; } public void setTrackName(String sessionTrack) { mSessionTrack = sessionTrack; updateViews(); } public void setDarkTheme(boolean dark) { mDarkTheme = dark; } @SuppressLint("SetJavaScriptEnabled") public void updateViews() { if (mWebView != null && !TextUtils.isEmpty(mSessionTrack)) { if (mDarkTheme) { mWebView.setBackgroundColor(Color.BLACK); mContainer.setBackgroundColor(Color.BLACK); mNoCaptionsTextView.setTextColor(Color.WHITE); } else { mWebView.setBackgroundColor(Color.WHITE); mContainer.setBackgroundResource(R.drawable.grey_frame_on_white); } String captionsUrl; final String trackLowerCase = mSessionTrack.toLowerCase(); if (mSessionTrack.equals(KEYNOTE_TRACK_NAME)|| trackLowerCase.equals(Config.PRIMARY_LIVESTREAM_TRACK)) { // if keynote or primary track, use primary captions url captionsUrl = Config.PRIMARY_LIVESTREAM_CAPTIONS_URL; } else if (trackLowerCase.equals(Config.SECONDARY_LIVESTREAM_TRACK)) { // else if secondary track use secondary captions url captionsUrl = Config.SECONDARY_LIVESTREAM_CAPTIONS_URL; } else { // otherwise we don't have captions captionsUrl = null; } if (captionsUrl != null) { if (mDarkTheme) { captionsUrl += CAPTIONS_DARK_THEME_URL_PARAM; } mWebView.getSettings().setJavaScriptEnabled(true); mWebView.loadUrl(captionsUrl); mNoCaptionsTextView.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } else { showNoCaptionsAvailable(); } } } private void showNoCaptionsAvailable() { mWebView.setVisibility(View.GONE); mNoCaptionsTextView.setVisibility(View.VISIBLE); } } /* * Presentation and Media Router methods and classes. This allows use of an externally * connected display to show video content full screen while still showing the regular views * on the primary device display. */ /** * Updates the presentation display. If a suitable external display is attached. The video * will be displayed on that screen instead. If not, the video will be displayed normally. */ private void updatePresentation() { updatePresentation(false); } /** * Updates the presentation display. If a suitable external display is attached. The video * will be displayed on that screen instead. If not, the video will be displayed normally. * @param forceDismiss If true, the external display will be dismissed even if it is still * available. This is useful for if the user wants to explicitly toggle * the external display off even if it's still connected. Setting this to * false will adjust the display based on if a suitable external display * is available or not. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private void updatePresentation(boolean forceDismiss) { if (!UIUtils.hasJellyBeanMR1()) { return; } // Get the current route and its presentation display MediaRouter.RouteInfo route = mMediaRouter.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_VIDEO); Display presentationDisplay = route != null ? route.getPresentationDisplay() : null; // Dismiss the current presentation if the display has changed if (mPresentation != null && (mPresentation.getDisplay() != presentationDisplay || forceDismiss)) { hidePresentation(); } // Show a new presentation if needed. if (mPresentation == null && presentationDisplay != null && !forceDismiss) { showPresentation(presentationDisplay); } // Show/hide toggle presentation action item if (mPresentationMenuItem != null) { mPresentationMenuItem.setVisible(presentationDisplay != null); } } /** * Shows the Presentation on the designated Display. Some UI components are also updated: * a play/pause button is displayed where the video would normally be; the YouTube player style * is updated to MINIMAL (more suitable for an external display); and an action item is updated * to indicate the external display is being used. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private void showPresentation(Display presentationDisplay) { LOGD(TAG, "Showing video presentation on display: " + presentationDisplay); if (mIsFullscreen) { if (!mIsTablet) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } if (mYouTubePlayer != null) { mYouTubePlayer.setFullscreen(false); } } View presentationView = mYouTubeFragment.getView(); ((ViewGroup) presentationView.getParent()).removeView(presentationView); mPresentation = new YouTubePresentation(this, presentationDisplay, presentationView); mPresentation.setOnDismissListener(mOnDismissListener); try { mPresentation.show(); mPresentationControls.setVisibility(View.VISIBLE); updatePresentationMenuItem(true); if (mYouTubePlayer != null) { mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL); mYouTubePlayer.play(); setFullscreenFlags(true); } } catch (WindowManager.InvalidDisplayException e) { LOGE(TAG, "Couldn't show presentation! Display was removed in the meantime.", e); hidePresentation(); } } /** * Hides the Presentation. Some UI components are also updated: * the video view is returned to its normal place on the primary display; the YouTube player * style is updated to the default; and an action item is updated to indicate the external * display is no longer in use. */ private void hidePresentation() { LOGD(TAG, "Hiding video presentation"); View presentationView = mPresentation.getYouTubeFragmentView(); ((ViewGroup) presentationView.getParent()).removeView(presentationView); mPlayerContainer.addView(presentationView); mPresentationControls.setVisibility(View.GONE); updatePresentationMenuItem(false); mPresentation.dismiss(); mPresentation = null; if (mYouTubePlayer != null) { mYouTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT); mYouTubePlayer.play(); setFullscreenFlags(false); } } /** * Updates the presentation action item. Toggles the icon between two drawables to indicate * if the external display is currently being used or not. * * @param enabled If the external display is enabled or not. */ private void updatePresentationMenuItem(boolean enabled) { if (mPresentationMenuItem != null) { mPresentationMenuItem.setIcon( enabled ? R.drawable.ic_media_route_on_holo_light : R.drawable.ic_media_route_off_holo_light); } } /** * Applies YouTube player full screen flags. Calls through to * {@link #setFullscreenFlags(boolean)}. */ private void setFullscreenFlags() { setFullscreenFlags(true); } /** * Applies YouTube player full screen flags plus forces portrait orientation on small screens * when presentation (secondary display) is enabled (as the full screen layout won't have * anything to display when an external display is connected). * * @param usePresentationMode Whether or not to use presentation mode. This is used when an * external display is connected and the user toggles between * presentation mode. */ private void setFullscreenFlags(boolean usePresentationMode) { if (mYouTubePlayer != null) { if (usePresentationMode && mPresentation != null && !mIsTablet) { mYouTubePlayer.setFullscreenControlFlags(0); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { mYouTubePlayer.setFullscreenControlFlags(mYouTubeFullscreenFlags); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } } } /** * Listens for when the Presentation (which is a type of Dialog) is dismissed. */ private final DialogInterface.OnDismissListener mOnDismissListener = new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (dialog == mPresentation) { LOGD(TAG, "Presentation was dismissed."); updatePresentation(true); } } }; /** * The main subclass of Presentation that is used to show content on an externally connected * display. There is no way to add a {@link android.app.Fragment}, and therefore a * YouTubePlayerFragment to a {@link android.app.Presentation} (which is just a subclass of * {@link android.app.Dialog}) so instead we pass in a View directly which is the extracted * YouTubePlayerView from the {@link SessionLivestreamActivity} YouTubePlayerFragment. Not * ideal and fairly hacky but there aren't any better alternatives unfortunately. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private final static class YouTubePresentation extends Presentation { private View mYouTubeFragmentView; public YouTubePresentation(Context context, Display display, View presentationView) { super(context, display); mYouTubeFragmentView = presentationView; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(mYouTubeFragmentView); } public View getYouTubeFragmentView() { return mYouTubeFragmentView; } } private static class SessionShareData { String title; String hashtag; String sessionUrl; public SessionShareData(String title, String hashTag, String url) { this.title = title; hashtag = hashTag; sessionUrl = url; } } /** * Single session query */ public interface SessionSummaryQuery { final static int _TOKEN = 0; final static String[] PROJECTION = { ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_HASHTAGS, ScheduleContract.Sessions.SESSION_LIVESTREAM_URL, Tracks.TRACK_NAME, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; final static int ID = 0; final static int TITLE = 1; final static int ABSTRACT = 2; final static int HASHTAGS = 3; final static int LIVESTREAM_URL = 4; final static int TRACK_NAME = 5; final static int BLOCK_START= 6; final static int BLOCK_END = 7; } /** * List of sessions query */ public interface SessionsQuery { final static int _TOKEN = 1; final static String[] PROJECTION = { BaseColumns._ID, Sessions.SESSION_ID, Sessions.SESSION_TITLE, Tracks.TRACK_NAME, Tracks.TRACK_COLOR, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, }; final static int _ID = 0; final static int SESSION_ID = 1; final static int TITLE = 2; final static int TRACK_NAME = 3; final static int TRACK_COLOR = 4; final static int BLOCK_START= 5; final static int BLOCK_END = 6; } }
Java
/* * Copyright 2012 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.Context; import android.database.DataSetObserver; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.Arrays; import java.util.Comparator; public class SimpleSectionedListAdapter extends BaseAdapter { private boolean mValid = true; private int mSectionResourceId; private LayoutInflater mLayoutInflater; private ListAdapter mBaseAdapter; private SparseArray<Section> mSections = new SparseArray<Section>(); public static class Section { int firstPosition; int sectionedPosition; CharSequence title; public Section(int firstPosition, CharSequence title) { this.firstPosition = firstPosition; this.title = title; } public CharSequence getTitle() { return title; } } public SimpleSectionedListAdapter(Context context, int sectionResourceId, ListAdapter baseAdapter) { mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mSectionResourceId = sectionResourceId; mBaseAdapter = baseAdapter; mBaseAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { mValid = !mBaseAdapter.isEmpty(); notifyDataSetChanged(); } @Override public void onInvalidated() { mValid = false; notifyDataSetInvalidated(); } }); } public void setSections(Section[] sections) { mSections.clear(); Arrays.sort(sections, new Comparator<Section>() { @Override public int compare(Section o, Section o1) { return (o.firstPosition == o1.firstPosition) ? 0 : ((o.firstPosition < o1.firstPosition) ? -1 : 1); } }); int offset = 0; // offset positions for the headers we're adding for (Section section : sections) { section.sectionedPosition = section.firstPosition + offset; mSections.append(section.sectionedPosition, section); ++offset; } notifyDataSetChanged(); } public int positionToSectionedPosition(int position) { int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).firstPosition > position) { break; } ++offset; } return position + offset; } public int sectionedPositionToPosition(int sectionedPosition) { if (isSectionHeaderPosition(sectionedPosition)) { return ListView.INVALID_POSITION; } int offset = 0; for (int i = 0; i < mSections.size(); i++) { if (mSections.valueAt(i).sectionedPosition > sectionedPosition) { break; } --offset; } return sectionedPosition + offset; } public boolean isSectionHeaderPosition(int position) { return mSections.get(position) != null; } @Override public int getCount() { return (mValid ? mBaseAdapter.getCount() + mSections.size() : 0); } @Override public Object getItem(int position) { return isSectionHeaderPosition(position) ? mSections.get(position) : mBaseAdapter.getItem(sectionedPositionToPosition(position)); } @Override public long getItemId(int position) { return isSectionHeaderPosition(position) ? Integer.MAX_VALUE - mSections.indexOfKey(position) : mBaseAdapter.getItemId(sectionedPositionToPosition(position)); } @Override public int getItemViewType(int position) { return isSectionHeaderPosition(position) ? getViewTypeCount() - 1 : mBaseAdapter.getItemViewType(position); } @Override public boolean isEnabled(int position) { //noinspection SimplifiableConditionalExpression return isSectionHeaderPosition(position) ? false : mBaseAdapter.isEnabled(sectionedPositionToPosition(position)); } @Override public int getViewTypeCount() { return mBaseAdapter.getViewTypeCount() + 1; // the section headings } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean hasStableIds() { return mBaseAdapter.hasStableIds(); } @Override public boolean isEmpty() { return mBaseAdapter.isEmpty(); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (isSectionHeaderPosition(position)) { TextView view = (TextView) convertView; if (view == null) { view = (TextView) mLayoutInflater.inflate(mSectionResourceId, parent, false); } view.setText(mSections.get(position).title); return view; } else { return mBaseAdapter.getView(sectionedPositionToPosition(position), convertView, parent); } } }
Java
/* * Copyright 2012 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.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.NavUtils; import android.view.MenuItem; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.HomeActivity; import com.google.android.apps.iosched.ui.SessionFeedbackFragment; import com.google.android.apps.iosched.ui.SimpleSinglePaneActivity; import com.google.android.apps.iosched.ui.TrackInfo; import com.google.android.apps.iosched.ui.TrackInfoHelperFragment; import com.google.android.apps.iosched.util.BeamUtils; public class SessionFeedbackActivity extends SimpleSinglePaneActivity implements TrackInfoHelperFragment.Callbacks { private String mSessionId = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { Uri sessionUri = getIntent().getData(); BeamUtils.setBeamSessionUri(this, sessionUri); getSupportFragmentManager().beginTransaction() .add(TrackInfoHelperFragment.newFromSessionUri(sessionUri), "track_info") .commit(); } mSessionId = ScheduleContract.Sessions.getSessionId(getIntent().getData()); } @Override protected int getContentViewResId() { return R.layout.activity_letterboxed_when_large; } @Override protected Fragment onCreatePane() { return new SessionFeedbackFragment(); } @Override public Intent getParentActivityIntent() { // Up to this session's track details, or Home if no track is available if (mSessionId != null) { return new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(mSessionId)); } else { return new Intent(this, HomeActivity.class); } } @Override public void onTrackInfoAvailable(String trackId, TrackInfo track) { setTitle(track.name); setActionBarTrackIcon(track.name, track.color); } }
Java
/* * Copyright 2012 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.annotation.TargetApi; import android.app.SearchManager; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.Html; import android.view.Menu; import android.view.MenuItem; import android.widget.SearchView; import com.google.analytics.tracking.android.EasyTracker; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.util.BeamUtils; import com.google.android.apps.iosched.util.ImageLoader; import com.google.android.apps.iosched.util.ReflectionUtils; import com.google.android.apps.iosched.util.UIUtils; import static com.google.android.apps.iosched.util.LogUtils.LOGD; /** * An activity that shows session search results. This activity can be either single * or multi-pane, depending on the device configuration. */ public class SearchActivity extends BaseActivity implements SessionsFragment.Callbacks, ImageLoader.ImageLoaderProvider { private boolean mTwoPane; private SessionsFragment mSessionsFragment; private Fragment mDetailFragment; private ImageLoader mImageLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); mTwoPane = (findViewById(R.id.fragment_container_detail) != null); FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentById(R.id.fragment_container_master); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); fm.beginTransaction() .add(R.id.fragment_container_master, mSessionsFragment) .commit(); } mDetailFragment = fm.findFragmentById(R.id.fragment_container_detail); mImageLoader = new ImageLoader(this, R.drawable.person_image_empty) .setMaxImageSize(getResources().getDimensionPixelSize(R.dimen.speaker_image_size)) .setFadeInImage(UIUtils.hasHoneycombMR1()); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); onNewIntent(getIntent()); } @Override public void onNewIntent(Intent intent) { setIntent(intent); String query = intent.getStringExtra(SearchManager.QUERY); setTitle(Html.fromHtml(getString(R.string.title_search_query, query))); mSessionsFragment.reloadFromArguments(intentToFragmentArguments( new Intent(Intent.ACTION_VIEW, Sessions.buildSearchUri(query)))); EasyTracker.getTracker().sendView("Search: " + query); LOGD("Tracker", "Search: " + query); updateDetailBackground(); } @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB) public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.search, menu); final MenuItem searchItem = menu.findItem(R.id.menu_search); if (searchItem != null && UIUtils.hasHoneycomb()) { SearchView searchView = (SearchView) searchItem.getActionView(); if (searchView != null) { SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setQueryRefinementEnabled(true); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { ReflectionUtils.tryInvoke(searchItem, "collapseActionView"); return false; } @Override public boolean onQueryTextChange(String s) { return false; } }); searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() { @Override public boolean onSuggestionSelect(int i) { return false; } @Override public boolean onSuggestionClick(int i) { ReflectionUtils.tryInvoke(searchItem, "collapseActionView"); return false; } }); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_search: if (!UIUtils.hasHoneycomb()) { startSearch(null, false, Bundle.EMPTY, false); return true; } break; } return super.onOptionsItemSelected(item); } private void updateDetailBackground() { if (mTwoPane) { findViewById(R.id.fragment_container_detail).setBackgroundResource( (mDetailFragment == null) ? R.drawable.grey_frame_on_white_empty_sessions : R.drawable.grey_frame_on_white); } } @Override public boolean onSessionSelected(String sessionId) { Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); Intent detailIntent = new Intent(Intent.ACTION_VIEW, sessionUri); if (mTwoPane) { BeamUtils.setBeamSessionUri(this, sessionUri); SessionDetailFragment fragment = new SessionDetailFragment(); fragment.setArguments(BaseActivity.intentToFragmentArguments(detailIntent)); getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container_detail, fragment) .commit(); mDetailFragment = fragment; updateDetailBackground(); return true; } else { startActivity(detailIntent); return false; } } @Override public ImageLoader getImageLoaderInstance() { return mImageLoader; } }
Java
/** * Copyright 2012 Google * * 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.gcm.server.api; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import com.google.android.apps.iosched.gcm.server.db.models.Device; import com.google.android.apps.iosched.gcm.server.device.MessageSender; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.logging.Logger; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Send message to all registered devices */ @SuppressWarnings("serial") public class SendMessageServlet extends BaseServlet { private static final Logger LOG = Logger.getLogger(SendMessageServlet.class.getName()); /** Authentication key for incoming message requests */ private static final String[][] AUTHORIZED_KEYS = { {"YOUR_API_KEYS_HERE", "developers.google.com"}, {"YOUR_API_KEYS_HERE", "googleapis.com/googledevelopers"}, {"YOUR_API_KEYS_HERE", "Device Key"} }; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Authenticate request String authKey = null; String authHeader = req.getHeader("Authorization"); String squelch = null; if (authHeader != null) { // Use 'Authorization: key=...' header String splitHeader[] = authHeader.split("="); if ("key".equals(splitHeader[0])) { authKey = splitHeader[1]; } } if (authKey == null) { // Valid auth key not found. Check for 'key' query parameter. // Note: This is included for WebHooks support, but will consume message body! authKey = req.getParameter("key"); squelch = req.getParameter("squelch"); } String authorizedUser = null; for (String[] candidateKey : AUTHORIZED_KEYS) { if (candidateKey[0].equals(authKey)) { authorizedUser = candidateKey[1]; break; } } if (authorizedUser == null) { send(resp, 403, "Not authorized"); return; } // Extract URL components String result = req.getPathInfo(); if (result == null) { send(resp, 400, "Bad request (check request format)"); return; } String[] components = result.split("/"); if (components.length != 3) { send(resp, 400, "Bad request (check request format)"); return; } String target = components[1]; String action = components[2]; // Extract extraData String payload = readBody(req); // Override: add jitter for server update requests // if ("sync_schedule".equals(action)) { // payload = "{ \"sync_jitter\": 21600000 }"; // } // Request decoding complete. Log request parameters LOG.info("Authorized User: " + authorizedUser + "\nTarget: " + target + "\nAction: " + action + "\nSquelch: " + (squelch != null ? squelch : "null") + "\nExtra Data: " + payload); // Send broadcast message MessageSender sender = new MessageSender(getServletConfig()); if ("global".equals(target)) { List<Device> allDevices = DeviceStore.getAllDevices(); if (allDevices == null || allDevices.isEmpty()) { send(resp, 404, "No devices registered"); } else { int resultCount = allDevices.size(); LOG.info("Selected " + resultCount + " devices"); sender.multicastSend(allDevices, action, squelch, payload); send(resp, 200, "Message queued: " + resultCount + " devices"); } } else { // Send message to one device List<Device> userDevices = DeviceStore.findDevicesByGPlusId(target); if (userDevices == null || userDevices.isEmpty()) { send(resp, 404, "User not found"); } else { int resultCount = userDevices.size(); LOG.info("Selected " + resultCount + " devices"); sender.multicastSend(userDevices, action, squelch, payload); send(resp, 200, "Message queued: " + resultCount + " devices"); } } } private String readBody(HttpServletRequest req) throws IOException { ServletInputStream inputStream = req.getInputStream(); java.util.Scanner s = new java.util.Scanner(inputStream).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } private static void send(HttpServletResponse resp, int status, String body) throws IOException { if (status >= 400) { LOG.warning(body); } else { LOG.info(body); } // Prevent frame hijacking resp.addHeader("X-FRAME-OPTIONS", "DENY"); // Write response data resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); out.print(body); resp.setStatus(status); } }
Java
/* * Copyright 2013 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.gcm.server.db.models; import com.googlecode.objectify.Key; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import java.util.List; @Entity public class MulticastMessage { @Id private Long id; private String action; private String extraData; private List<String> destinations; public Key<MulticastMessage> getKey() { return Key.create(MulticastMessage.class, id); } public Long getId() { return id; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getExtraData() { return extraData; } public void setExtraData(String extraData) { this.extraData = extraData; } public List<String> getDestinations() { return destinations; } public void setDestinations(List<String> destinations) { this.destinations = destinations; } }
Java
/* * Copyright 2013 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.gcm.server.db.models; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; @Entity public class Device { @Id private String gcmId; @Index private String gPlusId; public String getGcmId() { return gcmId; } public void setGcmId(String gcmId) { this.gcmId = gcmId; } public String getGPlusId () { return gPlusId; } public void setGPlusId(String gPlusId) { this.gPlusId = gPlusId; } }
Java
/* * Copyright 2013 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.gcm.server.db; import com.google.android.apps.iosched.gcm.server.db.models.Device; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.Query; import java.util.List; import java.util.logging.Logger; import static com.google.android.apps.iosched.gcm.server.db.OfyService.ofy; public class DeviceStore { private static final Logger LOG = Logger.getLogger(DeviceStore.class.getName()); /** * Registers a device. * * @param gcmId device's registration id. */ public static void register(String gcmId, String gPlusId) { LOG.info("Registering device.\nG+ ID: " + gPlusId + "\nGCM ID: " + gcmId); Device oldDevice = findDeviceByGcmId(gcmId); if (oldDevice == null) { // Existing device not found (as expected) Device newDevice = new Device(); newDevice.setGcmId(gcmId); newDevice.setGPlusId(gPlusId); ofy().save().entity(newDevice); } else { // Existing device found LOG.warning(gcmId + " is already registered"); if (!gPlusId.equals(oldDevice.getGPlusId())) { LOG.info("gPlusId has changed from '" + oldDevice.getGPlusId() + "' to '" + gPlusId + "'"); oldDevice.setGPlusId(gPlusId); ofy().save().entity(oldDevice); } } } /** * Unregisters a device. * * @param gcmId device's registration id. */ public static void unregister(String gcmId) { Device device = findDeviceByGcmId(gcmId); if (device == null) { LOG.warning("Device " + gcmId + " already unregistered"); return; } LOG.info("Unregistering " + gcmId); ofy().delete().entity(device); } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldGcmId, String newGcmId) { LOG.info("Updating " + oldGcmId + " to " + newGcmId); Device oldDevice = findDeviceByGcmId(oldGcmId); if (oldDevice == null) { LOG.warning("No device for registration id " + oldGcmId); return; } // Device exists. Since we use the GCM key as the (immutable) primary key, // we must create a new entity. Device newDevice = new Device(); newDevice.setGcmId(newGcmId); newDevice.setGPlusId(oldDevice.getGPlusId()); ofy().save().entity(newDevice); ofy().delete().entity(oldDevice); } /** * Gets registered device count. */ public static int getDeviceCount() { return ofy().load().type(Device.class).count(); } public static List<Device> getAllDevices() { return ofy().load().type(Device.class).list(); } public static Device findDeviceByGcmId(String regId) { return ofy().load().type(Device.class).id(regId).get(); } public static List<Device> findDevicesByGPlusId(String target) { return ofy().load().type(Device.class).filter("gPlusId", target).list(); } }
Java
/* * Copyright 2012 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.gcm.server.db; import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage; import java.util.List; import java.util.logging.Logger; import static com.google.android.apps.iosched.gcm.server.db.OfyService.ofy; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class MessageStore { private static final Logger LOG = Logger.getLogger(MessageStore.class.getName()); private MessageStore() { throw new UnsupportedOperationException(); } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices * @param type message type * @param extraData additional message payload * @return ID for the persistent record */ public static Long createMulticast(List<String> devices, String type, String extraData) { LOG.info("Storing multicast for " + devices.size() + " devices. (type=" + type + ")"); MulticastMessage msg = new MulticastMessage(); msg.setDestinations(devices); msg.setAction(type); msg.setExtraData(extraData); ofy().save().entity(msg).now(); Long id = msg.getId(); LOG.fine("Multicast ID: " + id); return id; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param id ID for the persistent record */ public static MulticastMessage getMulticast(Long id) { return ofy().load().type(MulticastMessage.class).id(id).get(); } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param id ID for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(Long id, List<String> devices) { MulticastMessage msg = ofy().load().type(MulticastMessage.class).id(id).get(); if (msg == null) { LOG.severe("No entity for multicast ID: " + id); return; } msg.setDestinations(devices); ofy().save().entity(msg); } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param id ID for the persistent record. */ public static void deleteMulticast(Long id) { ofy().delete().type(MulticastMessage.class).id(id); } }
Java
/* * Copyright 2013 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.gcm.server.db; import com.google.android.apps.iosched.gcm.server.db.models.Device; import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; /** Static initializer for Objectify ORM service. * * <p>To use this class: com.google.android.apps.iosched.gcm.server.db.OfyService.ofy; * * <p>This is responsible for registering model classes with Objectify before any references * access to the ObjectifyService takes place. All models *must* be registered here, as Objectify * doesn't do classpath scanning (by design). */ public class OfyService { static { factory().register(Device.class); factory().register(MulticastMessage.class); } public static Objectify ofy() { return ObjectifyService.ofy(); } public static ObjectifyFactory factory() { return ObjectifyService.factory(); } }
Java
/* * Copyright 2012 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.gcm.server.db; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.DatastoreService; /** * Context initializer that loads the API key from a * {@value #PATH} file located in the classpath (typically under * {@code WEB-INF/classes}). */ public class ApiKeyInitializer implements ServletContextListener { public static final String API_KEY = "<ENTER_YOUR_KEY>"; public static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger mLogger = Logger.getLogger(getClass().getName()); @Override public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch(EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, API_KEY); datastore.put(entity); mLogger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } /** * Gets the access key. */ protected String getKey() { com.google.appengine.api.datastore.DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); String apiKey = ""; try { Entity entity = datastore.get(key); apiKey = (String) entity.getProperty(ACCESS_KEY_FIELD); } catch (EntityNotFoundException e) { mLogger.severe("Exception will retrieving the API Key" + e.toString()); } return apiKey; } @Override public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 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.gcm.server.cron; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class VacuumDbServlet extends BaseServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); resp.addHeader("X-FRAME-OPTIONS", "DENY"); // Print "OK" message PrintWriter out = resp.getWriter(); out.print("OK"); resp.setStatus(HttpServletResponse.SC_OK); } }
Java
/* * Copyright 2012 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.gcm.server.admin; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class AdminServlet extends BaseServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head><title>IOSched GCM Server</title>"); out.print("</head>"); String status = (String) req.getAttribute("status"); if (status != null) { out.print(status); } out.print("</body></html>"); out.print("<h2>" + DeviceStore.getDeviceCount() + " device(s) registered!</h2>"); out.print("<form method='POST' action='/scheduleupdate'>"); out.print("<table>"); out.print("<tr>"); out.print("<td>Key:</td>"); out.print("<td><input type='password' name='key' size='80'/></td>"); out.print("</tr>"); out.print("<tr>"); out.print("<td>Announcement:</td>"); out.print("<td><input type='text' name='announcement' size='80'/></td>"); out.print("</tr>"); out.print("</table>"); out.print("<br/>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); resp.addHeader("X-FRAME-OPTIONS", "DENY"); resp.setStatus(HttpServletResponse.SC_OK); } }
Java
/* * Copyright 2012 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.gcm.server.device; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.MessageStore; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message and notifies all registered devices. * * <p>This class should not be called directly. Instead, it's used as a helper * for the SendMessage task queue. */ @SuppressWarnings("serial") public class MulticastQueueWorker extends BaseServlet { private MessageSender mSender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); mSender = new MessageSender(config); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { Long multicastId = new Long(req.getParameter("multicastKey")); boolean success = mSender.sendMessage(multicastId); if (success) { taskDone(resp, multicastId); } else { retryTask(resp); } } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp, Long multicastId) { MessageStore.deleteMulticast(multicastId); resp.setStatus(200); } }
Java
/* * Copyright 2012 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.gcm.server.device; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "gcm_id"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); DeviceStore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2013 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.gcm.server.device; import com.google.android.apps.iosched.gcm.server.db.ApiKeyInitializer; import com.google.android.apps.iosched.gcm.server.db.MessageStore; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import com.google.android.apps.iosched.gcm.server.db.models.Device; import com.google.android.apps.iosched.gcm.server.db.models.MulticastMessage; import com.google.android.gcm.server.*; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import javax.servlet.ServletConfig; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; /** Utility class for sending individual messages to devices. * * This class is responsible for communication with the GCM server for purposes of sending * messages. * * @return true if success, false if */ public class MessageSender { private String mApiKey; private Sender mGcmService; private static final int TTL = (int) TimeUnit.MINUTES.toSeconds(300); protected final Logger mLogger = Logger.getLogger(getClass().getName()); /** Maximum devices in a multicast message */ private static final int MAX_DEVICES = 1000; public MessageSender(ServletConfig config) { mApiKey = (String) config.getServletContext().getAttribute( ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); mGcmService = new Sender(mApiKey); } public void multicastSend(List<Device> devices, String action, String squelch, String extraData) { Queue queue = QueueFactory.getQueue("MulticastMessagesQueue"); // Split messages into batches for multicast // GCM limits maximum devices per multicast request. AppEngine also limits the size of // lists stored in the datastore. int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; for (Device device : devices) { counter ++; // If squelch is set, device is the originator of this message, // and has asked us to squelch itself. This prevents message echos. if (!device.getGcmId().equals(squelch)) { // Device not squelched. partialDevices.add(device.getGcmId()); } int partialSize = partialDevices.size(); if (partialSize == MAX_DEVICES || counter == total) { // Send multicast message Long multicastKey = MessageStore.createMulticast(partialDevices, action, extraData); mLogger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/queue/send") .param("multicastKey", Long.toString(multicastKey)) .method(TaskOptions.Method.POST); queue.add(taskOptions); partialDevices.clear(); } } mLogger.fine("Queued message to " + total + " devices"); } boolean sendMessage(Long multicastId) { MulticastMessage msg = MessageStore.getMulticast(multicastId); List<String> devices = msg.getDestinations(); String action = msg.getAction(); Message.Builder builder = new Message.Builder().delayWhileIdle(true); if (action == null || action.length() == 0) { throw new IllegalArgumentException("Message action cannot be empty."); } builder.collapseKey(action) .addData("action", action) .addData("extraData", msg.getExtraData()) .timeToLive(TTL); Message message = builder.build(); MulticastResult multicastResult = null; try { // TODO(trevorjohns): We occasionally see null messages. (Maybe due to squelch?) // We should these from entering the send queue in the first place. In the meantime, // here's a hack to prevent this. if (devices != null) { multicastResult = mGcmService.sendNoRetry(message, devices); mLogger.info("Result: " + multicastResult); } else { mLogger.info("Null device list detected. Aborting."); return true; } } catch (IOException e) { mLogger.log(Level.SEVERE, "Exception posting " + message, e); return true; } boolean allDone = true; // check if any registration id must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = devices.get(i); DeviceStore.updateRegistration(regId, canonicalRegId); } } } if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retriableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = devices.get(i); mLogger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it DeviceStore.unregister(regId); } if (error.equals(Constants.ERROR_UNAVAILABLE)) { retriableRegIds.add(regId); } } } if (!retriableRegIds.isEmpty()) { // update task MessageStore.updateMulticast(multicastId, retriableRegIds); allDone = false; return false; } } if (allDone) { return true; } else { return false; } } }
Java
/* * Copyright 2012 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.gcm.server.device; import com.google.android.apps.iosched.gcm.server.BaseServlet; import com.google.android.apps.iosched.gcm.server.db.DeviceStore; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "gcm_id"; private static final String PARAMETER_USER_ID = "gplus_id"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String gcmId = getParameter(req, PARAMETER_REG_ID); String gPlusId = getParameter(req, PARAMETER_USER_ID); DeviceStore.register(gcmId, gPlusId); setSuccess(resp); } }
Java
/* * Copyright 2012 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.gcm.server; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. * * <p>Provides extra logging information when running in debug mode. */ @SuppressWarnings("serial") public abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (value == null || value.trim().isEmpty()) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean checkUser() { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); String authDomain = user.getAuthDomain(); if (authDomain.contains("google.com")) { return true; } else { return false; } } }
Java
package pl.polidea.treeview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; /** * Tree view, expandable multi-level. * * <pre> * attr ref pl.polidea.treeview.R.styleable#TreeViewList_collapsible * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_expanded * attr ref pl.polidea.treeview.R.styleable#TreeViewList_src_collapsed * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indent_width * attr ref pl.polidea.treeview.R.styleable#TreeViewList_handle_trackball_press * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_gravity * attr ref pl.polidea.treeview.R.styleable#TreeViewList_indicator_background * attr ref pl.polidea.treeview.R.styleable#TreeViewList_row_background * </pre> */ public class TreeViewList extends ListView { private static final int DEFAULT_COLLAPSED_RESOURCE = R.drawable.collapsed; private static final int DEFAULT_EXPANDED_RESOURCE = R.drawable.expanded; private static final int DEFAULT_INDENT = 0; private static final int DEFAULT_GRAVITY = Gravity.LEFT | Gravity.CENTER_VERTICAL; private Drawable expandedDrawable; private Drawable collapsedDrawable; private Drawable rowBackgroundDrawable; private Drawable indicatorBackgroundDrawable; private int indentWidth = 0; private int indicatorGravity = 0; private AbstractTreeViewAdapter< ? > treeAdapter; private boolean collapsible; private boolean handleTrackballPress; public TreeViewList(final Context context, final AttributeSet attrs) { this(context, attrs, R.style.treeViewListStyle); } public TreeViewList(final Context context) { this(context, null); } public TreeViewList(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); parseAttributes(context, attrs); } private void parseAttributes(final Context context, final AttributeSet attrs) { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TreeViewList); expandedDrawable = a.getDrawable(R.styleable.TreeViewList_src_expanded); if (expandedDrawable == null) { expandedDrawable = context.getResources().getDrawable( DEFAULT_EXPANDED_RESOURCE); } collapsedDrawable = a .getDrawable(R.styleable.TreeViewList_src_collapsed); if (collapsedDrawable == null) { collapsedDrawable = context.getResources().getDrawable( DEFAULT_COLLAPSED_RESOURCE); } indentWidth = a.getDimensionPixelSize( R.styleable.TreeViewList_indent_width, DEFAULT_INDENT); indicatorGravity = a.getInteger( R.styleable.TreeViewList_indicator_gravity, DEFAULT_GRAVITY); indicatorBackgroundDrawable = a .getDrawable(R.styleable.TreeViewList_indicator_background); rowBackgroundDrawable = a .getDrawable(R.styleable.TreeViewList_row_background); collapsible = a.getBoolean(R.styleable.TreeViewList_collapsible, true); handleTrackballPress = a.getBoolean( R.styleable.TreeViewList_handle_trackball_press, true); } @Override public void setAdapter(final ListAdapter adapter) { if (!(adapter instanceof AbstractTreeViewAdapter)) { throw new TreeConfigurationException( "The adapter is not of TreeViewAdapter type"); } treeAdapter = (AbstractTreeViewAdapter< ? >) adapter; syncAdapter(); super.setAdapter(treeAdapter); } private void syncAdapter() { treeAdapter.setCollapsedDrawable(collapsedDrawable); treeAdapter.setExpandedDrawable(expandedDrawable); treeAdapter.setIndicatorGravity(indicatorGravity); treeAdapter.setIndentWidth(indentWidth); treeAdapter.setIndicatorBackgroundDrawable(indicatorBackgroundDrawable); treeAdapter.setRowBackgroundDrawable(rowBackgroundDrawable); treeAdapter.setCollapsible(collapsible); if (handleTrackballPress) { setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(final AdapterView< ? > parent, final View view, final int position, final long id) { treeAdapter.handleItemClick(view, view.getTag()); } }); } else { setOnClickListener(null); } } public void setExpandedDrawable(final Drawable expandedDrawable) { this.expandedDrawable = expandedDrawable; syncAdapter(); treeAdapter.refresh(); } public void setCollapsedDrawable(final Drawable collapsedDrawable) { this.collapsedDrawable = collapsedDrawable; syncAdapter(); treeAdapter.refresh(); } public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { this.rowBackgroundDrawable = rowBackgroundDrawable; syncAdapter(); treeAdapter.refresh(); } public void setIndicatorBackgroundDrawable( final Drawable indicatorBackgroundDrawable) { this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; syncAdapter(); treeAdapter.refresh(); } public void setIndentWidth(final int indentWidth) { this.indentWidth = indentWidth; syncAdapter(); treeAdapter.refresh(); } public void setIndicatorGravity(final int indicatorGravity) { this.indicatorGravity = indicatorGravity; syncAdapter(); treeAdapter.refresh(); } public void setCollapsible(final boolean collapsible) { this.collapsible = collapsible; syncAdapter(); treeAdapter.refresh(); } public void setHandleTrackballPress(final boolean handleTrackballPress) { this.handleTrackballPress = handleTrackballPress; syncAdapter(); treeAdapter.refresh(); } public Drawable getExpandedDrawable() { return expandedDrawable; } public Drawable getCollapsedDrawable() { return collapsedDrawable; } public Drawable getRowBackgroundDrawable() { return rowBackgroundDrawable; } public Drawable getIndicatorBackgroundDrawable() { return indicatorBackgroundDrawable; } public int getIndentWidth() { return indentWidth; } public int getIndicatorGravity() { return indicatorGravity; } public boolean isCollapsible() { return collapsible; } public boolean isHandleTrackballPress() { return handleTrackballPress; } }
Java
package pl.polidea.treeview; import android.app.Activity; import android.content.Context; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.ListAdapter; /** * Adapter used to feed the table view. * * @param <T> * class for ID of the tree */ public abstract class AbstractTreeViewAdapter<T> extends BaseAdapter implements ListAdapter { private static final String TAG = AbstractTreeViewAdapter.class .getSimpleName(); private final TreeStateManager<T> treeStateManager; private final int numberOfLevels; private final LayoutInflater layoutInflater; private int indentWidth = 0; private int indicatorGravity = 0; private Drawable collapsedDrawable; private Drawable expandedDrawable; private Drawable indicatorBackgroundDrawable; private Drawable rowBackgroundDrawable; private final OnClickListener indicatorClickListener = new OnClickListener() { @Override public void onClick(final View v) { @SuppressWarnings("unchecked") final T id = (T) v.getTag(); expandCollapse(id); } }; private boolean collapsible; private final Activity activity; public Activity getActivity() { return activity; } protected TreeStateManager<T> getManager() { return treeStateManager; } protected void expandCollapse(final T id) { final TreeNodeInfo<T> info = treeStateManager.getNodeInfo(id); if (!info.isWithChildren()) { // ignore - no default action return; } if (info.isExpanded()) { treeStateManager.collapseChildren(id); } else { treeStateManager.expandDirectChildren(id); } } private void calculateIndentWidth() { if (expandedDrawable != null) { indentWidth = Math.max(getIndentWidth(), expandedDrawable.getIntrinsicWidth()); } if (collapsedDrawable != null) { indentWidth = Math.max(getIndentWidth(), collapsedDrawable.getIntrinsicWidth()); } } public AbstractTreeViewAdapter(final Activity activity, final TreeStateManager<T> treeStateManager, final int numberOfLevels) { this.activity = activity; this.treeStateManager = treeStateManager; this.layoutInflater = (LayoutInflater) activity .getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.numberOfLevels = numberOfLevels; this.collapsedDrawable = null; this.expandedDrawable = null; this.rowBackgroundDrawable = null; this.indicatorBackgroundDrawable = null; } @Override public void registerDataSetObserver(final DataSetObserver observer) { treeStateManager.registerDataSetObserver(observer); } @Override public void unregisterDataSetObserver(final DataSetObserver observer) { treeStateManager.unregisterDataSetObserver(observer); } @Override public int getCount() { return treeStateManager.getVisibleCount(); } @Override public Object getItem(final int position) { return getTreeId(position); } public T getTreeId(final int position) { return treeStateManager.getVisibleList().get(position); } public TreeNodeInfo<T> getTreeNodeInfo(final int position) { return treeStateManager.getNodeInfo(getTreeId(position)); } @Override public boolean hasStableIds() { // NOPMD return true; } @Override public int getItemViewType(final int position) { return getTreeNodeInfo(position).getLevel(); } @Override public int getViewTypeCount() { return numberOfLevels; } @Override public boolean isEmpty() { return getCount() == 0; } @Override public boolean areAllItemsEnabled() { // NOPMD return true; } @Override public boolean isEnabled(final int position) { // NOPMD return true; } protected int getTreeListItemWrapperId() { return R.layout.tree_list_item_wrapper; } @Override public final View getView(final int position, final View convertView, final ViewGroup parent) { Log.d(TAG, "Creating a view based on " + convertView + " with position " + position); final TreeNodeInfo<T> nodeInfo = getTreeNodeInfo(position); if (convertView == null) { Log.d(TAG, "Creating the view a new"); final LinearLayout layout = (LinearLayout) layoutInflater.inflate( getTreeListItemWrapperId(), null); return populateTreeItem(layout, getNewChildView(nodeInfo), nodeInfo, true); } else { Log.d(TAG, "Reusing the view"); final LinearLayout linear = (LinearLayout) convertView; final FrameLayout frameLayout = (FrameLayout) linear .findViewById(R.id.treeview_list_item_frame); final View childView = frameLayout.getChildAt(0); updateView(childView, nodeInfo); return populateTreeItem(linear, childView, nodeInfo, false); } } /** * Called when new view is to be created. * * @param treeNodeInfo * node info * @return view that should be displayed as tree content */ public abstract View getNewChildView(TreeNodeInfo<T> treeNodeInfo); /** * Called when new view is going to be reused. You should update the view * and fill it in with the data required to display the new information. You * can also create a new view, which will mean that the old view will not be * reused. * * @param view * view that should be updated with the new values * @param treeNodeInfo * node info used to populate the view * @return view to used as row indented content */ public abstract View updateView(View view, TreeNodeInfo<T> treeNodeInfo); /** * Retrieves background drawable for the node. * * @param treeNodeInfo * node info * @return drawable returned as background for the whole row. Might be null, * then default background is used */ public Drawable getBackgroundDrawable(final TreeNodeInfo<T> treeNodeInfo) { // NOPMD return null; } private Drawable getDrawableOrDefaultBackground(final Drawable r) { if (r == null) { return activity.getResources() .getDrawable(R.drawable.list_selector_background).mutate(); } else { return r; } } public final LinearLayout populateTreeItem(final LinearLayout layout, final View childView, final TreeNodeInfo<T> nodeInfo, final boolean newChildView) { final Drawable individualRowDrawable = getBackgroundDrawable(nodeInfo); layout.setBackgroundDrawable(individualRowDrawable == null ? getDrawableOrDefaultBackground(rowBackgroundDrawable) : individualRowDrawable); final LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( calculateIndentation(nodeInfo), LayoutParams.FILL_PARENT); final LinearLayout indicatorLayout = (LinearLayout) layout .findViewById(R.id.treeview_list_item_image_layout); indicatorLayout.setGravity(indicatorGravity); indicatorLayout.setLayoutParams(indicatorLayoutParams); final ImageView image = (ImageView) layout .findViewById(R.id.treeview_list_item_image); image.setImageDrawable(getDrawable(nodeInfo)); image.setBackgroundDrawable(getDrawableOrDefaultBackground(indicatorBackgroundDrawable)); image.setScaleType(ScaleType.CENTER); image.setTag(nodeInfo.getId()); if (nodeInfo.isWithChildren() && collapsible) { image.setOnClickListener(indicatorClickListener); } else { image.setOnClickListener(null); } layout.setTag(nodeInfo.getId()); final FrameLayout frameLayout = (FrameLayout) layout .findViewById(R.id.treeview_list_item_frame); final FrameLayout.LayoutParams childParams = new FrameLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); if (newChildView) { frameLayout.addView(childView, childParams); } frameLayout.setTag(nodeInfo.getId()); return layout; } protected int calculateIndentation(final TreeNodeInfo<T> nodeInfo) { return getIndentWidth() * (nodeInfo.getLevel() + (collapsible ? 1 : 0)); } protected Drawable getDrawable(final TreeNodeInfo<T> nodeInfo) { if (!nodeInfo.isWithChildren() || !collapsible) { return getDrawableOrDefaultBackground(indicatorBackgroundDrawable); } if (nodeInfo.isExpanded()) { return expandedDrawable; } else { return collapsedDrawable; } } public void setIndicatorGravity(final int indicatorGravity) { this.indicatorGravity = indicatorGravity; } public void setCollapsedDrawable(final Drawable collapsedDrawable) { this.collapsedDrawable = collapsedDrawable; calculateIndentWidth(); } public void setExpandedDrawable(final Drawable expandedDrawable) { this.expandedDrawable = expandedDrawable; calculateIndentWidth(); } public void setIndentWidth(final int indentWidth) { this.indentWidth = indentWidth; calculateIndentWidth(); } public void setRowBackgroundDrawable(final Drawable rowBackgroundDrawable) { this.rowBackgroundDrawable = rowBackgroundDrawable; } public void setIndicatorBackgroundDrawable( final Drawable indicatorBackgroundDrawable) { this.indicatorBackgroundDrawable = indicatorBackgroundDrawable; } public void setCollapsible(final boolean collapsible) { this.collapsible = collapsible; } public void refresh() { treeStateManager.refresh(); } private int getIndentWidth() { return indentWidth; } @SuppressWarnings("unchecked") public void handleItemClick(final View view, final Object id) { expandCollapse((T) id); } }
Java
package pl.polidea.treeview; /** * This exception is thrown when the tree does not contain node requested. * */ public class NodeNotInTreeException extends RuntimeException { private static final long serialVersionUID = 1L; public NodeNotInTreeException(final String id) { super("The tree does not contain the node specified: " + id); } }
Java
/** * Provides expandable Tree View implementation. */ package pl.polidea.treeview;
Java
package pl.polidea.treeview; import android.util.Log; /** * Allows to build tree easily in sequential mode (you have to know levels of * all the tree elements upfront). You should rather use this class rather than * manager if you build initial tree from some external data source. * <p> * Note, that all ids must be unique. IDs are used to find nodes in the whole * tree, so they cannot repeat even if they are in different * sub-trees. * * @param <T> */ public class TreeBuilder<T> { private static final String TAG = TreeBuilder.class.getSimpleName(); private final TreeStateManager<T> manager; private T lastAddedId = null; private int lastLevel = -1; public TreeBuilder(final TreeStateManager<T> manager) { this.manager = manager; } public void clear() { manager.clear(); lastAddedId = null; lastLevel = -1; } /** * Adds new relation to existing tree. Child is set as the last child of the * parent node. Parent has to already exist in the tree, child cannot yet * exist. This method is mostly useful in case you add entries layer by * layer - i.e. first top level entries, then children for all parents, then * grand-children and so on. * * @param parent * parent id * @param child * child id */ public synchronized void addRelation(final T parent, final T child) { Log.d(TAG, "Adding relation parent:" + parent + " -> child: " + child); manager.addAfterChild(parent, child, null); lastAddedId = child; lastLevel = manager.getLevel(child); } /** * Adds sequentially new node. Using this method is the simplest way of * building tree - if you have all the elements in the sequence as they * should be displayed in fully-expanded tree. You can combine it with add * relation - for example you can add information about few levels using * {@link addRelation} and then after the right level is added as parent, * you can continue adding them using sequential operation. * * @param id * id of the node * @param level * its level */ public synchronized void sequentiallyAddNextNode(final T id, final int level) { Log.d(TAG, "Adding sequentiall node " + id + " at level " + level); if (lastAddedId == null) { addNodeToParentOneLevelDown(null, id, level); } else { if (level <= lastLevel) { final T parent = findParentAtLevel(lastAddedId, level - 1); addNodeToParentOneLevelDown(parent, id, level); } else { addNodeToParentOneLevelDown(lastAddedId, id, level); } } } /** * Find parent of the node at the level specified. * * @param node * node from which we start * @param levelToFind * level which we are looking for * @return the node found (null if it is topmost node). */ private T findParentAtLevel(final T node, final int levelToFind) { T parent = manager.getParent(node); while (parent != null) { if (manager.getLevel(parent) == levelToFind) { break; } parent = manager.getParent(parent); } return parent; } /** * Adds note to parent at the level specified. But it verifies that the * level is one level down than the parent! * * @param parent * parent parent * @param id * new node id * @param level * should always be parent's level + 1 */ private void addNodeToParentOneLevelDown(final T parent, final T id, final int level) { if (parent == null && level != 0) { throw new TreeConfigurationException("Trying to add new id " + id + " to top level with level != 0 (" + level + ")"); } if (parent != null && manager.getLevel(parent) != level - 1) { throw new TreeConfigurationException("Trying to add new id " + id + " <" + level + "> to " + parent + " <" + manager.getLevel(parent) + ">. The difference in levels up is bigger than 1."); } manager.addAfterChild(parent, id, null); setLastAdded(id, level); } private void setLastAdded(final T id, final int level) { lastAddedId = id; lastLevel = level; } }
Java
package pl.polidea.treeview; /** * Exception thrown when there is a problem with configuring tree. * */ public class TreeConfigurationException extends RuntimeException { private static final long serialVersionUID = 1L; public TreeConfigurationException(final String detailMessage) { super(detailMessage); } }
Java
package pl.polidea.treeview; /** * The node being added is already in the tree. * */ public class NodeAlreadyInTreeException extends RuntimeException { private static final long serialVersionUID = 1L; public NodeAlreadyInTreeException(final String id, final String oldNode) { super("The node has already been added to the tree: " + id + ". Old node is:" + oldNode); } }
Java
package pl.polidea.treeview; /** * Information about the node. * * @param <T> * type of the id for the tree */ public class TreeNodeInfo<T> { private final T id; private final int level; private final boolean withChildren; private final boolean visible; private final boolean expanded; /** * Creates the node information. * * @param id * id of the node * @param level * level of the node * @param withChildren * whether the node has children. * @param visible * whether the tree node is visible. * @param expanded * whether the tree node is expanded * */ public TreeNodeInfo(final T id, final int level, final boolean withChildren, final boolean visible, final boolean expanded) { super(); this.id = id; this.level = level; this.withChildren = withChildren; this.visible = visible; this.expanded = expanded; } public T getId() { return id; } public boolean isWithChildren() { return withChildren; } public boolean isVisible() { return visible; } public boolean isExpanded() { return expanded; } public int getLevel() { return level; } @Override public String toString() { return "TreeNodeInfo [id=" + id + ", level=" + level + ", withChildren=" + withChildren + ", visible=" + visible + ", expanded=" + expanded + "]"; } }
Java
package pl.polidea.treeview; import java.io.Serializable; import java.util.List; import android.database.DataSetObserver; /** * Manages information about state of the tree. It only keeps information about * tree elements, not the elements themselves. * * @param <T> * type of the identifier for nodes in the tree */ public interface TreeStateManager<T> extends Serializable { /** * Returns array of integers showing the location of the node in hierarchy. * It corresponds to heading numbering. {0,0,0} in 3 level node is the first * node {0,0,1} is second leaf (assuming that there are two leaves in first * subnode of the first node). * * @param id * id of the node * @return textual description of the hierarchy in tree for the node. */ Integer[] getHierarchyDescription(T id); /** * Returns level of the node. * * @param id * id of the node * @return level in the tree */ int getLevel(T id); /** * Returns information about the node. * * @param id * node id * @return node info */ TreeNodeInfo<T> getNodeInfo(T id); /** * Returns children of the node. * * @param id * id of the node or null if asking for top nodes * @return children of the node */ List<T> getChildren(T id); /** * Returns parent of the node. * * @param id * id of the node * @return parent id or null if no parent */ T getParent(T id); /** * Adds the node before child or at the beginning. * * @param parent * id of the parent node. If null - adds at the top level * @param newChild * new child to add if null - adds at the beginning. * @param beforeChild * child before which to add the new child */ void addBeforeChild(T parent, T newChild, T beforeChild); /** * Adds the node after child or at the end. * * @param parent * id of the parent node. If null - adds at the top level. * @param newChild * new child to add. If null - adds at the end. * @param afterChild * child after which to add the new child */ void addAfterChild(T parent, T newChild, T afterChild); /** * Removes the node and all children from the tree. * * @param id * id of the node to remove or null if all nodes are to be * removed. */ void removeNodeRecursively(T id); /** * Expands all children of the node. * * @param id * node which children should be expanded. cannot be null (top * nodes are always expanded!). */ void expandDirectChildren(T id); /** * Expands everything below the node specified. Might be null - then expands * all. * * @param id * node which children should be expanded or null if all nodes * are to be expanded. */ void expandEverythingBelow(T id); /** * Collapse children. * * @param id * id collapses everything below node specified. If null, * collapses everything but top-level nodes. */ void collapseChildren(T id); /** * Returns next sibling of the node (or null if no further sibling). * * @param id * node id * @return the sibling (or null if no next) */ T getNextSibling(T id); /** * Returns previous sibling of the node (or null if no previous sibling). * * @param id * node id * @return the sibling (or null if no previous) */ T getPreviousSibling(T id); /** * Checks if given node is already in tree. * * @param id * id of the node * @return true if node is already in tree. */ boolean isInTree(T id); /** * Count visible elements. * * @return number of currently visible elements. */ int getVisibleCount(); /** * Returns visible node list. * * @return return the list of all visible nodes in the right sequence */ List<T> getVisibleList(); /** * Registers observers with the manager. * * @param observer * observer */ void registerDataSetObserver(final DataSetObserver observer); /** * Unregisters observers with the manager. * * @param observer * observer */ void unregisterDataSetObserver(final DataSetObserver observer); /** * Cleans tree stored in manager. After this operation the tree is empty. * */ void clear(); /** * Refreshes views connected to the manager. */ void refresh(); }
Java
package pl.polidea.treeview; import java.io.Serializable; import java.util.LinkedList; import java.util.List; /** * Node. It is package protected so that it cannot be used outside. * * @param <T> * type of the identifier used by the tree */ class InMemoryTreeNode<T> implements Serializable { private static final long serialVersionUID = 1L; private final T id; private final T parent; private final int level; private boolean visible = true; private final List<InMemoryTreeNode<T>> children = new LinkedList<InMemoryTreeNode<T>>(); private List<T> childIdListCache = null; public InMemoryTreeNode(final T id, final T parent, final int level, final boolean visible) { super(); this.id = id; this.parent = parent; this.level = level; this.visible = visible; } public int indexOf(final T id) { return getChildIdList().indexOf(id); } /** * Cache is built lasily only if needed. The cache is cleaned on any * structure change for that node!). * * @return list of ids of children */ public synchronized List<T> getChildIdList() { if (childIdListCache == null) { childIdListCache = new LinkedList<T>(); for (final InMemoryTreeNode<T> n : children) { childIdListCache.add(n.getId()); } } return childIdListCache; } public boolean isVisible() { return visible; } public void setVisible(final boolean visible) { this.visible = visible; } public int getChildrenListSize() { return children.size(); } public synchronized InMemoryTreeNode<T> add(final int index, final T child, final boolean visible) { childIdListCache = null; // Note! top levell children are always visible (!) final InMemoryTreeNode<T> newNode = new InMemoryTreeNode<T>(child, getId(), getLevel() + 1, getId() == null ? true : visible); children.add(index, newNode); return newNode; } /** * Note. This method should technically return unmodifiable collection, but * for performance reason on small devices we do not do it. * * @return children list */ public List<InMemoryTreeNode<T>> getChildren() { return children; } public synchronized void clearChildren() { children.clear(); childIdListCache = null; } public synchronized void removeChild(final T child) { final int childIndex = indexOf(child); if (childIndex != -1) { children.remove(childIndex); childIdListCache = null; } } @Override public String toString() { return "InMemoryTreeNode [id=" + getId() + ", parent=" + getParent() + ", level=" + getLevel() + ", visible=" + visible + ", children=" + children + ", childIdListCache=" + childIdListCache + "]"; } T getId() { return id; } T getParent() { return parent; } int getLevel() { return level; } }
Java
package pl.polidea.treeview; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import android.database.DataSetObserver; import android.util.Log; /** * In-memory manager of tree state. * * @param <T> * type of identifier */ public class InMemoryTreeStateManager<T> implements TreeStateManager<T> { private static final String TAG = InMemoryTreeStateManager.class .getSimpleName(); private static final long serialVersionUID = 1L; private final Map<T, InMemoryTreeNode<T>> allNodes = new HashMap<T, InMemoryTreeNode<T>>(); private final InMemoryTreeNode<T> topSentinel = new InMemoryTreeNode<T>( null, null, -1, true); private transient List<T> visibleListCache = null; // lasy initialised private transient List<T> unmodifiableVisibleList = null; private boolean visibleByDefault = true; private final transient Set<DataSetObserver> observers = new HashSet<DataSetObserver>(); private synchronized void internalDataSetChanged() { visibleListCache = null; unmodifiableVisibleList = null; for (final DataSetObserver observer : observers) { observer.onChanged(); } } /** * If true new nodes are visible by default. * * @param visibleByDefault * if true, then newly added nodes are expanded by default */ public void setVisibleByDefault(final boolean visibleByDefault) { this.visibleByDefault = visibleByDefault; } private InMemoryTreeNode<T> getNodeFromTreeOrThrow(final T id) { if (id == null) { throw new NodeNotInTreeException("(null)"); } final InMemoryTreeNode<T> node = allNodes.get(id); if (node == null) { throw new NodeNotInTreeException(id.toString()); } return node; } private InMemoryTreeNode<T> getNodeFromTreeOrThrowAllowRoot(final T id) { if (id == null) { return topSentinel; } return getNodeFromTreeOrThrow(id); } private void expectNodeNotInTreeYet(final T id) { final InMemoryTreeNode<T> node = allNodes.get(id); if (node != null) { throw new NodeAlreadyInTreeException(id.toString(), node.toString()); } } @Override public synchronized TreeNodeInfo<T> getNodeInfo(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrow(id); final List<InMemoryTreeNode<T>> children = node.getChildren(); boolean expanded = false; if (!children.isEmpty() && children.get(0).isVisible()) { expanded = true; } return new TreeNodeInfo<T>(id, node.getLevel(), !children.isEmpty(), node.isVisible(), expanded); } @Override public synchronized List<T> getChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); return node.getChildIdList(); } @Override public synchronized T getParent(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); return node.getParent(); } private boolean getChildrenVisibility(final InMemoryTreeNode<T> node) { boolean visibility; final List<InMemoryTreeNode<T>> children = node.getChildren(); if (children.isEmpty()) { visibility = visibleByDefault; } else { visibility = children.get(0).isVisible(); } return visibility; } @Override public synchronized void addBeforeChild(final T parent, final T newChild, final T beforeChild) { expectNodeNotInTreeYet(newChild); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent); final boolean visibility = getChildrenVisibility(node); // top nodes are always expanded. if (beforeChild == null) { final InMemoryTreeNode<T> added = node.add(0, newChild, visibility); allNodes.put(newChild, added); } else { final int index = node.indexOf(beforeChild); final InMemoryTreeNode<T> added = node.add(index == -1 ? 0 : index, newChild, visibility); allNodes.put(newChild, added); } if (visibility) { internalDataSetChanged(); } } @Override public synchronized void addAfterChild(final T parent, final T newChild, final T afterChild) { expectNodeNotInTreeYet(newChild); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent); final boolean visibility = getChildrenVisibility(node); if (afterChild == null) { final InMemoryTreeNode<T> added = node.add( node.getChildrenListSize(), newChild, visibility); allNodes.put(newChild, added); } else { final int index = node.indexOf(afterChild); final InMemoryTreeNode<T> added = node.add( index == -1 ? node.getChildrenListSize() : index + 1, newChild, visibility); allNodes.put(newChild, added); } if (visibility) { internalDataSetChanged(); } } @Override public synchronized void removeNodeRecursively(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); final boolean visibleNodeChanged = removeNodeRecursively(node); final T parent = node.getParent(); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); parentNode.removeChild(id); if (visibleNodeChanged) { internalDataSetChanged(); } } private boolean removeNodeRecursively(final InMemoryTreeNode<T> node) { boolean visibleNodeChanged = false; for (final InMemoryTreeNode<T> child : node.getChildren()) { if (removeNodeRecursively(child)) { visibleNodeChanged = true; } } node.clearChildren(); if (node.getId() != null) { allNodes.remove(node.getId()); if (node.isVisible()) { visibleNodeChanged = true; } } return visibleNodeChanged; } private void setChildrenVisibility(final InMemoryTreeNode<T> node, final boolean visible, final boolean recursive) { for (final InMemoryTreeNode<T> child : node.getChildren()) { child.setVisible(visible); if (recursive) { setChildrenVisibility(child, visible, true); } } } @Override public synchronized void expandDirectChildren(final T id) { Log.d(TAG, "Expanding direct children of " + id); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); setChildrenVisibility(node, true, false); internalDataSetChanged(); } @Override public synchronized void expandEverythingBelow(final T id) { Log.d(TAG, "Expanding all children below " + id); final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); setChildrenVisibility(node, true, true); internalDataSetChanged(); } @Override public synchronized void collapseChildren(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); if (node == topSentinel) { for (final InMemoryTreeNode<T> n : topSentinel.getChildren()) { setChildrenVisibility(n, false, true); } } else { setChildrenVisibility(node, false, true); } internalDataSetChanged(); } @Override public synchronized T getNextSibling(final T id) { final T parent = getParent(id); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); boolean returnNext = false; for (final InMemoryTreeNode<T> child : parentNode.getChildren()) { if (returnNext) { return child.getId(); } if (child.getId().equals(id)) { returnNext = true; } } return null; } @Override public synchronized T getPreviousSibling(final T id) { final T parent = getParent(id); final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent); T previousSibling = null; for (final InMemoryTreeNode<T> child : parentNode.getChildren()) { if (child.getId().equals(id)) { return previousSibling; } previousSibling = child.getId(); } return null; } @Override public synchronized boolean isInTree(final T id) { return allNodes.containsKey(id); } @Override public synchronized int getVisibleCount() { return getVisibleList().size(); } @Override public synchronized List<T> getVisibleList() { T currentId = null; if (visibleListCache == null) { visibleListCache = new ArrayList<T>(allNodes.size()); do { currentId = getNextVisible(currentId); if (currentId == null) { break; } else { visibleListCache.add(currentId); } } while (true); } if (unmodifiableVisibleList == null) { unmodifiableVisibleList = Collections .unmodifiableList(visibleListCache); } return unmodifiableVisibleList; } public synchronized T getNextVisible(final T id) { final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id); if (!node.isVisible()) { return null; } final List<InMemoryTreeNode<T>> children = node.getChildren(); if (!children.isEmpty()) { final InMemoryTreeNode<T> firstChild = children.get(0); if (firstChild.isVisible()) { return firstChild.getId(); } } final T sibl = getNextSibling(id); if (sibl != null) { return sibl; } T parent = node.getParent(); do { if (parent == null) { return null; } final T parentSibling = getNextSibling(parent); if (parentSibling != null) { return parentSibling; } parent = getNodeFromTreeOrThrow(parent).getParent(); } while (true); } @Override public synchronized void registerDataSetObserver( final DataSetObserver observer) { observers.add(observer); } @Override public synchronized void unregisterDataSetObserver( final DataSetObserver observer) { observers.remove(observer); } @Override public int getLevel(final T id) { return getNodeFromTreeOrThrow(id).getLevel(); } @Override public Integer[] getHierarchyDescription(final T id) { final int level = getLevel(id); final Integer[] hierarchy = new Integer[level + 1]; int currentLevel = level; T currentId = id; T parent = getParent(currentId); while (currentLevel >= 0) { hierarchy[currentLevel--] = getChildren(parent).indexOf(currentId); currentId = parent; parent = getParent(parent); } return hierarchy; } private void appendToSb(final StringBuilder sb, final T id) { if (id != null) { final TreeNodeInfo<T> node = getNodeInfo(id); final int indent = node.getLevel() * 4; final char[] indentString = new char[indent]; Arrays.fill(indentString, ' '); sb.append(indentString); sb.append(node.toString()); sb.append(Arrays.asList(getHierarchyDescription(id)).toString()); sb.append("\n"); } final List<T> children = getChildren(id); for (final T child : children) { appendToSb(sb, child); } } @Override public synchronized String toString() { final StringBuilder sb = new StringBuilder(); appendToSb(sb, null); return sb.toString(); } @Override public synchronized void clear() { allNodes.clear(); topSentinel.clearChildren(); internalDataSetChanged(); } @Override public void refresh() { internalDataSetChanged(); } }
Java
package pl.polidea.treeview.demo; import java.util.Arrays; import java.util.Set; import pl.polidea.treeview.AbstractTreeViewAdapter; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.TextView; /** * This is a very simple adapter that provides very basic tree view with a * checkboxes and simple item description. * */ class SimpleStandardAdapter extends AbstractTreeViewAdapter<Long> { private final Set<Long> selected; private final OnCheckedChangeListener onCheckedChange = new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { final Long id = (Long) buttonView.getTag(); changeSelected(isChecked, id); } }; private void changeSelected(final boolean isChecked, final Long id) { if (isChecked) { selected.add(id); } else { selected.remove(id); } } public SimpleStandardAdapter(final TreeViewListDemo treeViewListDemo, final Set<Long> selected, final TreeStateManager<Long> treeStateManager, final int numberOfLevels) { super(treeViewListDemo, treeStateManager, numberOfLevels); this.selected = selected; } private String getDescription(final long id) { final Integer[] hierarchy = getManager().getHierarchyDescription(id); return "Node " + id + Arrays.asList(hierarchy); } @Override public View getNewChildView(final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = (LinearLayout) getActivity() .getLayoutInflater().inflate(R.layout.demo_list_item, null); return updateView(viewLayout, treeNodeInfo); } @Override public LinearLayout updateView(final View view, final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = (LinearLayout) view; final TextView descriptionView = (TextView) viewLayout .findViewById(R.id.demo_list_item_description); final TextView levelView = (TextView) viewLayout .findViewById(R.id.demo_list_item_level); descriptionView.setText(getDescription(treeNodeInfo.getId())); levelView.setText(Integer.toString(treeNodeInfo.getLevel())); final CheckBox box = (CheckBox) viewLayout .findViewById(R.id.demo_list_checkbox); box.setTag(treeNodeInfo.getId()); if (treeNodeInfo.isWithChildren()) { box.setVisibility(View.GONE); } else { box.setVisibility(View.VISIBLE); box.setChecked(selected.contains(treeNodeInfo.getId())); } box.setOnCheckedChangeListener(onCheckedChange); return viewLayout; } @Override public void handleItemClick(final View view, final Object id) { final Long longId = (Long) id; final TreeNodeInfo<Long> info = getManager().getNodeInfo(longId); if (info.isWithChildren()) { super.handleItemClick(view, id); } else { final ViewGroup vg = (ViewGroup) view; final CheckBox cb = (CheckBox) vg .findViewById(R.id.demo_list_checkbox); cb.performClick(); } } @Override public long getItemId(final int position) { return getTreeId(position); } }
Java
package pl.polidea.treeview.demo; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import pl.polidea.treeview.InMemoryTreeStateManager; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeBuilder; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import pl.polidea.treeview.TreeViewList; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; /** * Demo activity showing how the tree view can be used. * */ public class TreeViewListDemo extends Activity { private enum TreeType implements Serializable { SIMPLE, FANCY } private final Set<Long> selected = new HashSet<Long>(); private static final String TAG = TreeViewListDemo.class.getSimpleName(); private TreeViewList treeView; private static final int[] DEMO_NODES = new int[] { 0, 0, 1, 1, 1, 2, 2, 1, 1, 2, 1, 0, 0, 0, 1, 2, 3, 2, 0, 0, 1, 2, 0, 1, 2, 0, 1 }; private static final int LEVEL_NUMBER = 4; private TreeStateManager<Long> manager = null; private FancyColouredVariousSizesAdapter fancyAdapter; private SimpleStandardAdapter simpleAdapter; private TreeType treeType; private boolean collapsible; @SuppressWarnings("unchecked") @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); TreeType newTreeType = null; boolean newCollapsible; if (savedInstanceState == null) { manager = new InMemoryTreeStateManager<Long>(); final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager); for (int i = 0; i < DEMO_NODES.length; i++) { treeBuilder.sequentiallyAddNextNode((long) i, DEMO_NODES[i]); } Log.d(TAG, manager.toString()); newTreeType = TreeType.SIMPLE; newCollapsible = true; } else { manager = (TreeStateManager<Long>) savedInstanceState .getSerializable("treeManager"); if (manager == null) { manager = new InMemoryTreeStateManager<Long>(); } newTreeType = (TreeType) savedInstanceState .getSerializable("treeType"); if (newTreeType == null) { newTreeType = TreeType.SIMPLE; } newCollapsible = savedInstanceState.getBoolean("collapsible"); } setContentView(R.layout.main_demo); treeView = (TreeViewList) findViewById(R.id.mainTreeView); fancyAdapter = new FancyColouredVariousSizesAdapter(this, selected, manager, LEVEL_NUMBER); simpleAdapter = new SimpleStandardAdapter(this, selected, manager, LEVEL_NUMBER); setTreeAdapter(newTreeType); setCollapsible(newCollapsible); registerForContextMenu(treeView); } @Override protected void onSaveInstanceState(final Bundle outState) { outState.putSerializable("treeManager", manager); outState.putSerializable("treeType", treeType); outState.putBoolean("collapsible", this.collapsible); super.onSaveInstanceState(outState); } protected final void setTreeAdapter(final TreeType newTreeType) { this.treeType = newTreeType; switch (newTreeType) { case SIMPLE: treeView.setAdapter(simpleAdapter); break; case FANCY: treeView.setAdapter(fancyAdapter); break; default: treeView.setAdapter(simpleAdapter); } } protected final void setCollapsible(final boolean newCollapsible) { this.collapsible = newCollapsible; treeView.setCollapsible(this.collapsible); } @Override public boolean onCreateOptionsMenu(final Menu menu) { final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(final Menu menu) { final MenuItem collapsibleMenu = menu .findItem(R.id.collapsible_menu_item); if (collapsible) { collapsibleMenu.setTitle(R.string.collapsible_menu_disable); collapsibleMenu.setTitleCondensed(getResources().getString( R.string.collapsible_condensed_disable)); } else { collapsibleMenu.setTitle(R.string.collapsible_menu_enable); collapsibleMenu.setTitleCondensed(getResources().getString( R.string.collapsible_condensed_enable)); } return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(final MenuItem item) { if (item.getItemId() == R.id.simple_menu_item) { setTreeAdapter(TreeType.SIMPLE); } else if (item.getItemId() == R.id.fancy_menu_item) { setTreeAdapter(TreeType.FANCY); } else if (item.getItemId() == R.id.collapsible_menu_item) { setCollapsible(!this.collapsible); } else if (item.getItemId() == R.id.expand_all_menu_item) { manager.expandEverythingBelow(null); } else if (item.getItemId() == R.id.collapse_all_menu_item) { manager.collapseChildren(null); } else { return false; } return true; } @Override public void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) { final AdapterContextMenuInfo adapterInfo = (AdapterContextMenuInfo) menuInfo; final long id = adapterInfo.id; final TreeNodeInfo<Long> info = manager.getNodeInfo(id); final MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.context_menu, menu); if (info.isWithChildren()) { if (info.isExpanded()) { menu.findItem(R.id.context_menu_expand_item).setVisible(false); menu.findItem(R.id.context_menu_expand_all).setVisible(false); } else { menu.findItem(R.id.context_menu_collapse).setVisible(false); } } else { menu.findItem(R.id.context_menu_expand_item).setVisible(false); menu.findItem(R.id.context_menu_expand_all).setVisible(false); menu.findItem(R.id.context_menu_collapse).setVisible(false); } super.onCreateContextMenu(menu, v, menuInfo); } @Override public boolean onContextItemSelected(final MenuItem item) { final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); final long id = info.id; if (item.getItemId() == R.id.context_menu_collapse) { manager.collapseChildren(id); return true; } else if (item.getItemId() == R.id.context_menu_expand_all) { manager.expandEverythingBelow(id); return true; } else if (item.getItemId() == R.id.context_menu_expand_item) { manager.expandDirectChildren(id); return true; } else if (item.getItemId() == R.id.context_menu_delete) { manager.removeNodeRecursively(id); return true; } else { return super.onContextItemSelected(item); } } }
Java
/** * Provides just demo of the TreeView widget. */ package pl.polidea.treeview.demo;
Java
package pl.polidea.treeview.demo; import java.util.Set; import pl.polidea.treeview.R; import pl.polidea.treeview.TreeNodeInfo; import pl.polidea.treeview.TreeStateManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; final class FancyColouredVariousSizesAdapter extends SimpleStandardAdapter { public FancyColouredVariousSizesAdapter(final TreeViewListDemo activity, final Set<Long> selected, final TreeStateManager<Long> treeStateManager, final int numberOfLevels) { super(activity, selected, treeStateManager, numberOfLevels); } @Override public LinearLayout updateView(final View view, final TreeNodeInfo<Long> treeNodeInfo) { final LinearLayout viewLayout = super.updateView(view, treeNodeInfo); final TextView descriptionView = (TextView) viewLayout .findViewById(R.id.demo_list_item_description); final TextView levelView = (TextView) viewLayout .findViewById(R.id.demo_list_item_level); descriptionView.setTextSize(20 - 2 * treeNodeInfo.getLevel()); levelView.setTextSize(20 - 2 * treeNodeInfo.getLevel()); return viewLayout; } @Override public Drawable getBackgroundDrawable(final TreeNodeInfo<Long> treeNodeInfo) { switch (treeNodeInfo.getLevel()) { case 0: return new ColorDrawable(Color.WHITE); case 1: return new ColorDrawable(Color.GRAY); case 2: return new ColorDrawable(Color.YELLOW); default: return null; } } }
Java
package com.hibernate.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Java
package com.anket.poll.bo; import java.util.List; import com.anket.poll.model.Poll; public interface PollBo { List<Poll> getAllPolls(); List<Poll> getAllPollsWithOptionLimit(Integer limit); }
Java
package com.anket.poll.dao; import java.util.List; import com.anket.poll.model.Poll; public interface PollDao { List<Poll> getAllPolls(); List<Poll> getAllPollsWithOptionLimit(Integer limit); }
Java
package com.anket.poll.dao.impl; import java.util.ArrayList; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import com.anket.poll.dao.PollDao; import com.anket.poll.model.Poll; import com.hibernate.util.HibernateUtil; public class PollDaoImpl implements PollDao { public List<Poll> getAllPolls() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Query query = session.createQuery("from Poll"); List<Poll> list = query.list(); return list; } public List<Poll> getAllPollsWithOptionLimit(Integer limit) { List<Poll> newList = new ArrayList<Poll>(); int m = 0; for (Poll poll : getAllPolls()) { m++; if (m < limit) newList.add(poll); else return newList; } return newList; } }
Java
package com.anket.poll; import java.io.Serializable; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import org.primefaces.model.chart.PieChartModel; import com.anket.option.model.Option; import com.anket.poll.bo.PollBo; import com.anket.poll.model.Poll; @ManagedBean(name = "homePageBean") @RequestScoped public class HomePageBean implements Serializable { private PollBo pollBo; private Poll selectedPoll; private PieChartModel chartModel; private String str; public String getStr() { return "anket.xhtml"; } public void setStr(String str) { this.str = str; } private int selectedPollId=-1; public Poll getSelectedPoll() { return selectedPoll; } public void setSelectedPoll(Poll selectedPoll) { this.selectedPoll = selectedPoll; } public PieChartModel getChartModel() { chartModel = new PieChartModel(); if (selectedPoll != null) for (Option option : selectedPoll.getAllOptions()) { chartModel.set(option.content, option.click); } return chartModel; } public PollBo getPollBo() { return pollBo; } public void setPollBo(PollBo pollBo) { this.pollBo = pollBo; } public List<Poll> getAllPolls() { return pollBo.getAllPolls(); } }
Java
package com.anket.poll.model; import java.util.ArrayList; import java.util.List; import com.anket.option.model.Option; import com.anket.person.model.Person; public class Poll { private long pollId; private String title; private Person person; private List<Option> allOptions; public long getPollId() { return pollId; } public void setPollId(long pollId) { this.pollId = pollId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public List<Option> getAllOptions() { return allOptions; } public List<Option> getAllOptionsWithLimit(Integer limit){ List<Option> newList=new ArrayList<Option>(); int m=0; for(Option option:getAllOptions()){ m++; if(m<=limit)newList.add(option); else{ Option opt=new Option(); opt.setContent("..."); newList.add(opt); return newList; } } return newList; } public void setAllOptions(List<Option> allOptions) { this.allOptions = allOptions; } }
Java
package com.anket.address.bo; import java.util.List; import org.springframework.transaction.annotation.Transactional; import com.anket.city.model.City; import com.anket.country.model.Country; import com.anket.district.model.District; public interface AddressBo { List<Country> getAllCountries(); List<City> getAllCities(Integer countryId); List<District> getAllDistricts(Integer cityId); }
Java
package com.anket.address.bo.impl; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.anket.address.bo.AddressBo; import com.anket.address.dao.AddressDao; import com.anket.city.model.City; import com.anket.country.model.Country; import com.anket.district.model.District; public class AddressBoImpl implements AddressBo{ AddressDao addressDao; public AddressDao getAddressDao() { return addressDao; } public void setAddressDao(AddressDao addressDao) { this.addressDao = addressDao; } public List<Country> getAllCountries() { return addressDao.getAllCountries(); } public List<City> getAllCities(Integer countryId) { // TODO Auto-generated method stub return addressDao.getAllCities(countryId); } public List<District> getAllDistricts(Integer cityId) { // TODO Auto-generated method stub return addressDao.getAllDistricts(cityId); } }
Java
package com.anket.address.dao; import java.util.List; import com.anket.city.model.City; import com.anket.country.model.Country; import com.anket.district.model.District; public interface AddressDao { List<Country> getAllCountries(); List<City> getAllCities(Integer countryId); List<District> getAllDistricts(Integer cityId); }
Java
package com.anket.address.dao.impl; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.anket.address.dao.AddressDao; import com.anket.city.model.City; import com.anket.country.model.Country; import com.anket.district.model.District; import com.hibernate.util.HibernateUtil; public class AddressDaoImpl implements AddressDao{ public List<Country> getAllCountries() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Query q=session.createQuery("from Country"); return q.list(); } public List<City> getAllCities(Integer countryId) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Query q=session.createQuery("from City where COUNTRY_ID=:id"); q.setString("id", countryId.toString()); return q.list(); } public List<District> getAllDistricts(Integer cityId) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Query q=session.createQuery("from District where CITY_ID=:id"); q.setString("id", cityId.toString()); return q.list(); } }
Java
package com.anket.address.model; import com.anket.district.model.District; import com.anket.city.model.City; import com.anket.country.model.Country; public class Address { public long addressId; public String shortAddress; public Country country; public City city; public District district; public Address(){ country=new Country(); city=new City(); district=new District(); } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } public District getDistrict() { return district; } public void setDistrict(District district) { this.district = district; } public long getAddressId() { return addressId; } public void setAddressId(long addressId) { this.addressId = addressId; } public String getShortAddress() { return shortAddress; } public void setShortAddress(String shortAddress) { this.shortAddress = shortAddress; } }
Java
package com.anket.option.model; import com.anket.poll.model.Poll; public class Option { public long optionId; public String content; public Poll poll; public Integer click; public Integer getClick() { return click; } public Poll getPoll() { return poll; } public void setPoll(Poll poll) { this.poll = poll; } public long getOptionId() { return optionId; } public void setClick(Integer click) { this.click = click; } public void setOptionId(long optionId) { this.optionId = optionId; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
Java
package com.anket; import java.awt.Font; import java.io.File; import java.io.FileInputStream; import java.util.logging.Logger; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot; import org.jfree.data.general.PieDataset; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; @ManagedBean public class DynamicImageController { private StreamedContent barcode; private StreamedContent chart; private static final Logger logger = Logger.getLogger(DynamicImageController.class.getName()); public DynamicImageController() { //Chart } public StreamedContent getBarcode() { return barcode; } public void setBarcode(StreamedContent barcode) { this.barcode = barcode; } public StreamedContent getChart() { return chart; } public void setChart(StreamedContent chart) { this.chart = chart; } public StreamedContent print(PieDataset dataset){ try { JFreeChart jfreechart = ChartFactory.createPieChart("Turkish Cities", dataset, true, true, false); File chartFile = new File("dynamichart"); final PiePlot plot = (PiePlot) jfreechart.getPlot(); plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12)); plot.setNoDataMessage("No data available"); plot.setCircular(false); plot.setLabelGap(0.02); ChartUtilities.saveChartAsPNG(chartFile, jfreechart, 375, 300); chart = new DefaultStreamedContent(new FileInputStream(chartFile), "image/png"); } catch (Exception e) { logger.severe(e.getMessage()); } return chart; } }
Java
package com.anket.city.model; import com.anket.country.model.Country; public class City { public long cityId; public String name; public Country country; public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public long getCityId() { return cityId; } public void setCityId(long cityId) { this.cityId = cityId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Java
package com.anket.district.model; import com.anket.city.model.City; public class District { public long districtId; public String name; public City city; public City getCity() { return city; } public void setCity(City city) { this.city = city; } public long getDistrictId() { return districtId; } public void setDistrictId(long districtId) { this.districtId = districtId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Java
package com.anket; import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; import org.hibernate.SessionFactory; import com.hibernate.util.HibernateUtil; public class RestoreViewPhaseListener implements PhaseListener { public void afterPhase(PhaseEvent arg0) { // SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); // try { // sessionFactory.getCurrentSession().getTransaction().commit(); // } catch (Throwable ex) { // // // very bad error here, occured... // if (sessionFactory.getCurrentSession().getTransaction().isActive()) { // sessionFactory.getCurrentSession().getTransaction().rollback(); // } // } } public void beforePhase(PhaseEvent arg0) { SessionFactory sessionFactory = null; sessionFactory = HibernateUtil.getSessionFactory(); sessionFactory.getCurrentSession().beginTransaction(); } public PhaseId getPhaseId() { // TODO Auto-generated method stub return PhaseId.RESTORE_VIEW; } }
Java
package com.anket; import java.io.IOException; import javax.faces.FacesException; import javax.faces.application.NavigationHandler; import javax.faces.application.ViewHandler; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; import javax.servlet.http.HttpSession; public class LoggedInCheck implements PhaseListener { public PhaseId getPhaseId() { return PhaseId.RENDER_RESPONSE; } public void beforePhase(PhaseEvent event) { System.out.println("before phase"); FacesContext fc = event.getFacesContext(); if (!loggedIn()) { NavigationHandler nh = fc.getApplication().getNavigationHandler(); nh.handleNavigation(fc, "", "logout"); } //redirect(fc, "/default.xhtml"); } private static void redirect(FacesContext facesContext, String url) { try { facesContext.getExternalContext().redirect(url); } catch (IOException e) { throw new FacesException("Cannot redirect to " + url + " due to IO exception.", e); } } public void afterPhase(PhaseEvent event) { System.out.println("after phase"); } private boolean loggedIn() { HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true); String isLog = (String)session.getAttribute("isLoggedIn"); System.out.println("isLoggedIn: " + isLog); return (isLog != null && isLog.equals("yes")); } }
Java
package com.anket.country.model; public class Country { public long countryId; public String name; public long getCountryId() { return countryId; } public void setCountryId(long countryId) { this.countryId = countryId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Java
package com.anket.person.bo; import java.util.List; import org.springframework.transaction.annotation.Transactional; import com.anket.address.model.Address; import com.anket.option.model.Option; import com.anket.person.model.Person; import com.anket.poll.model.Poll; public interface PersonBo{ void addPerson(Person person); void deletePerson(Person person); void updatePerson(Person person); Person getPersonById(Integer id); boolean isPersonAdmin(Person person); Person isloginTrue(String email,String password); void addPoll(Poll poll); void addOption(Option option); Address prepareAddress(Address address); }
Java
package com.anket.person.bo.impl; import com.anket.address.model.Address; import com.anket.option.model.Option; import com.anket.person.bo.PersonBo; import com.anket.person.dao.PersonDao; import com.anket.person.model.Person; import com.anket.poll.model.Poll; public class PersonBoImpl implements PersonBo{ PersonDao personDao; public void setPersonDao(PersonDao personDao) { this.personDao = personDao; } public void addPerson(Person person) { // TODO Auto-generated method stub personDao.addPerson(person); } public void deletePerson(Person person) { // TODO Auto-generated method stub personDao.deletePerson(person); } public void updatePerson(Person person) { // TODO Auto-generated method stub personDao.updatePerson(person); } public Person getPersonById(Integer id) { return personDao.getPersonById(id); } public boolean isPersonAdmin(Person person) { // TODO Auto-generated method stub return false; } public Person isloginTrue(String email, String password) { return personDao.isloginTrue(email, password); } public void addPoll(Poll poll) { personDao.addPoll(poll); } public void addOption(Option option) { personDao.addOption(option); } public Address prepareAddress(Address address) { return personDao.prepareAddress(address); } }
Java
package com.anket.person.dao; import com.anket.address.model.Address; import com.anket.option.model.Option; import com.anket.person.model.Person; import com.anket.poll.model.Poll; public interface PersonDao{ void addPerson(Person person); void deletePerson(Person person); void updatePerson(Person person); Person getPersonById(Integer id); boolean isPersonAdmin(Person person); Person isloginTrue(String email,String password); Address prepareAddress(Address address); void addPoll(Poll poll); void addOption(Option option); }
Java
package com.anket.person.dao.impl; import java.util.Date; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.anket.address.model.Address; import com.anket.city.model.City; import com.anket.country.model.Country; import com.anket.district.model.District; import com.anket.option.model.Option; import com.anket.person.dao.PersonDao; import com.anket.person.model.Person; import com.anket.poll.model.Poll; import com.hibernate.util.HibernateUtil; public class PersonDaoImpl implements PersonDao{ public Address prepareAddress(Address address){ Session session = HibernateUtil.getSessionFactory().getCurrentSession(); long country= address.getCountry().getCountryId(); long city= address.getCity().getCityId(); long district= address.getDistrict().getDistrictId(); String shortAddress=address.getShortAddress(); Address newAddress=new Address(); newAddress.setShortAddress(shortAddress); Query q=session.createQuery("from Country where countryId=:id"); q.setLong("id", country); newAddress.setCountry((Country) q.list().get(0)); q=session.createQuery("from City where cityId=:id"); q.setLong("id", city); newAddress.setCity((City) q.list().get(0)); q=session.createQuery("from District where districtId=:id"); q.setLong("id", district); newAddress.setDistrict((District) q.list().get(0)); return newAddress; } public void addPerson(Person person) { person.setCreatedDate(new Date()); Session session = HibernateUtil.getSessionFactory().getCurrentSession(); // Address address=person.getAddress(); // long country= address.getCountry().getCountryId(); // long city= address.getCity().getCityId(); // long district= address.getDistrict().getDistrictId(); // String shortAddress=address.getShortAddress(); // // // Address newAddress=new Address(); // // // newAddress.setShortAddress(shortAddress); // Query q=session.createQuery("from Country where countryId=:id"); // q.setLong("id", country); // // newAddress.setCountry((Country) q.list().get(0)); // // q=session.createQuery("from City where cityId=:id"); // q.setLong("id", city); // // newAddress.setCity((City) q.list().get(0)); // // q=session.createQuery("from District where districtId=:id"); // q.setLong("id", district); // // newAddress.setDistrict((District) q.list().get(0)); // // person.setAddress(newAddress); session.save(person); } public void deletePerson(Person person) { // TODO Auto-generated method stub } public void updatePerson(Person person) { // TODO Auto-generated method stub } public Person getPersonById(Integer id) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Query q = session.createQuery("from Person where personId=:id"); q.setLong("id", id.longValue()); List list=q.list(); return (Person) list.get(0); } public boolean isPersonAdmin(Person person) { return false; } public Person isloginTrue(String email, String password) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Query q = session.createQuery("from Person where email=:email and password=:pass"); q.setString("email", email); q.setString("pass", password); List list=q.list(); return (list.size()!=0)?(Person) list.get(0):null; } public void addPoll(Poll poll) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.save(poll); } public void addOption(Option option) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.save(option); } }
Java
package com.anket.person.model; import java.util.Date; import java.util.List; import com.anket.address.model.Address; import com.anket.poll.model.Poll; public class Person{ public long personId; public String name; public String lastname; public String email; public String password; public Address address; public Date createdDate; public Integer isAdmin;//1 admin public Integer status;//0 unaccepted 1 accepted public List <Poll> allPolls; public List<Poll> getAllPolls() { return allPolls; } public void setAllPolls(List<Poll> allPolls) { this.allPolls = allPolls; } public Integer getIsAdmin() { return isAdmin; } public void setIsAdmin(Integer isAdmin) { this.isAdmin = isAdmin; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public long getPersonId() { return personId; } public void setPersonId(long personId) { this.personId = personId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } }
Java
package com.anket.person; public class Car { private String model; private String manufacturer; private String color; private int year; public Car(String model,String color){ this.color=color; this.model=model; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
Java
package com.anket.person; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.servlet.http.HttpSession; import org.jfree.data.general.DefaultPieDataset; import org.jfree.data.general.PieDataset; import org.primefaces.model.StreamedContent; import org.primefaces.model.chart.PieChartModel; import com.anket.DynamicImageController; import com.anket.address.bo.AddressBo; import com.anket.address.model.Address; import com.anket.city.model.City; import com.anket.country.model.Country; import com.anket.district.model.District; import com.anket.option.model.Option; import com.anket.person.bo.PersonBo; import com.anket.person.model.Person; import com.anket.poll.model.Poll; @ManagedBean(name = "personBean") @SessionScoped public class PersonBean implements Serializable { PersonBo personBo; AddressBo addressBo; public Person tempPerson; public Address tempAddress; private Country tempCountry; public Country getTempCountry() { return tempCountry; } public void setTempCountry(Country tempCountry) { this.tempCountry = tempCountry; } public Poll tempPoll; public Option tempOption; public String email = ""; public String password = ""; public String pollTitle = ""; public boolean login = false; public boolean logout = true; private int sizeOfOption; private List<Car> allCars; private String test; private String size; private List<Option> optionList; private Date date1; private Poll selectedPoll; private PieChartModel model; public PieChartModel getModel() { model = new PieChartModel(); if (selectedPoll != null) for (Option option : selectedPoll.getAllOptions()) { model.set(option.content, option.click); } return model; } public StreamedContent printChart(){ DefaultPieDataset dataset = new DefaultPieDataset(); if (selectedPoll != null) for (Option option : selectedPoll.getAllOptions()) { dataset.setValue(option.content.toString(), new Double(45.0)); } dataset.setValue("Istanbul", new Double(45.0)); return (new DynamicImageController()).print((PieDataset)dataset); } public String getGoogleChartData(){ String str=""; if (selectedPoll != null){ int val=0; val=selectedPoll.getAllOptions().size(); int i=0; str+="data.addRows(["; for (Option option : selectedPoll.getAllOptions()) { str+="['"+option.getContent()+"',"+(i+1)*10+"]"; if(i!=val-1)str+=","; // str+="data.setValue("+i+",0,'"+option.getContent()+"');"; // str+="data.setValue("+i+",1,"+i*10+");"; i++; } str+="]);"; } return str; } public Poll getSelectedPoll() { return selectedPoll; } public void setSelectedPoll(Poll selectedPoll) { this.selectedPoll = selectedPoll; } public Date getDate1() { return date1; } public void setDate1(Date date1) { this.date1 = date1; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getTest() { return test; } public void setTest(String test) { this.test = test; } public List<Car> getAllCars() { return allCars; } public void setAllCars(List<Car> allCars) { this.allCars = allCars; } public Option getTempOption() { return tempOption; } public void setTempOption(Option tempOption) { this.tempOption = tempOption; } public String getPollTitle() { return pollTitle; } public void setPollTitle(String pollTitle) { this.pollTitle = pollTitle; } public Poll getTempPoll() { return tempPoll; } public void setTempPoll(Poll tempPoll) { this.tempPoll = tempPoll; } public int getSizeOfOption() { return sizeOfOption; } public void setSizeOfOption(int sizeOfOption) { this.sizeOfOption = sizeOfOption; } public void handleOptionChange(AjaxBehaviorEvent event) { // gridComponent.setColumns(sizeOfOption); try { addFunction(sizeOfOption); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void addFunction(int number) throws IOException { FacesContext context = FacesContext.getCurrentInstance(); optionList.clear(); for (int i = 0; i < number; i++) { tempOption = new Option(); optionList.add(tempOption); } } public List<Option> getOptionList() { return optionList; } public void setOptionList(List<Option> optionList) { this.optionList = optionList; } public boolean isLogin() { return login; } public void setLogin(boolean login) { this.login = login; } public boolean isLogout() { return logout; } public void setLogout(boolean logout) { this.logout = logout; } public List<Country> getAllCountries() { return addressBo.getAllCountries(); } public List<City> getAllCities() { return addressBo.getAllCities((int) tempAddress.getCountry().getCountryId()); } public List<District> getAllDistricts() { return addressBo.getAllDistricts((int) tempAddress.getCity().getCityId()); } public AddressBo getAddressBo() { return addressBo; } public void setAddressBo(AddressBo addressBo) { this.addressBo = addressBo; } public Address getTempAddress() { return tempAddress; } public void setTempAddress(Address tempAddress) { this.tempAddress = tempAddress; } public PersonBean() { tempPerson = new Person(); tempAddress = new Address(); tempPoll = new Poll(); tempOption = new Option(); allCars = new ArrayList<Car>(); optionList = new ArrayList<Option>(); for (int i = 0; i < 5; i++) { Car car = new Car("mercedes", "" + i + 1); allCars.add(car); } } public PersonBo getPersonBo() { return personBo; } public void setPersonBo(PersonBo personBo) { this.personBo = personBo; } public Person getTempPerson() { return tempPerson; } public void setTempPerson(Person tempPerson) { this.tempPerson = tempPerson; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String addPerson() { tempPerson.setAddress(personBo.prepareAddress(tempAddress)); tempPerson.setIsAdmin(0); tempPerson.setStatus(0); personBo.addPerson(tempPerson); //clearForm(); return ""; } public String addPoll() { tempPoll = new Poll(); HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); String id = session.getAttribute("id").toString(); Person person = personBo.getPersonById(Integer.parseInt(id)); tempPoll.setPerson(person); tempPoll.setTitle(pollTitle); // tempOption = new Option(); Iterator ite = optionList.iterator(); while (ite.hasNext()) { tempOption = (Option) ite.next(); tempOption.setPoll(tempPoll); tempOption.setClick(-1); personBo.addOption(tempOption); } return ""; } public Person isLoginTrue() { return personBo.isloginTrue(email, password); } public String doLogin() { System.out.println("login"); Person person = isLoginTrue(); if (person != null) { HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); session.setAttribute("isLoggedIn", "yes"); session.setAttribute("id", person.getPersonId()); login = true; logout = false; } System.out.println("----" + isLoginTrue()); return person != null ? "homepage" : ""; } public String doLogout() { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false); session.invalidate(); login = false; logout = true; return "login"; } public void clearForm() { tempPerson.setName(""); tempPerson.setLastname(""); tempPerson.setPassword(""); tempPerson.setEmail(""); tempAddress.setShortAddress(""); tempAddress.getCountry().setCountryId(0); tempAddress.setShortAddress(""); tempAddress.getDistrict().setDistrictId(0); tempAddress.getCity().setCityId(0); } public void fonk1() { Object sessionName = "name"; Object sessionValue = "value"; FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false); Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String attr = (String) e.nextElement(); System.err.println(" attr = " + attr); Object value = session.getValue(attr); System.err.println(" value = " + value); } // session.setAttribute("name", new String("mustafa")); System.out.println("\n--end of fonk1--\n"); } public void fonk2() { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false); Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String attr = (String) e.nextElement(); System.err.println(" attr = " + attr); Object value = session.getValue(attr); System.err.println(" value = " + value); } System.out.println("\n--end of fonk2--\n"); } public void fonk3() { FacesContext facesContext = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false); Enumeration e = session.getAttributeNames(); session.invalidate(); System.out.println("\n--end of fonk3--\n"); } public void fonk4() { FacesContext fc = FacesContext.getCurrentInstance(); System.out.println("view id=" + fc.getViewRoot().getViewId()); } public boolean loggedIn() { HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); String isLog = (String) session.getAttribute("isLoggedIn"); System.out.println("isLoggedIn: " + isLog); return (isLog != null && isLog.equals("yes")); } public List<Poll> getAllPolls() { HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true); String id = session.getAttribute("id").toString(); Person person = personBo.getPersonById(Integer.parseInt(id)); return person.getAllPolls(); } }
Java
package com.anket; import javax.faces.event.PhaseEvent; import javax.faces.event.PhaseId; import javax.faces.event.PhaseListener; import org.hibernate.SessionFactory; import com.hibernate.util.HibernateUtil; public class RenderResponsePhaseListener implements PhaseListener { public void afterPhase(PhaseEvent arg0) { SessionFactory sessionFactory = null; try { sessionFactory = HibernateUtil.getSessionFactory(); sessionFactory.getCurrentSession().getTransaction().commit(); } catch (Throwable ex) { System.err.println("Very unsuitable error occured ..."); if (sessionFactory.getCurrentSession().getTransaction().isActive()) { sessionFactory.getCurrentSession().getTransaction().rollback(); } } } public void beforePhase(PhaseEvent arg0) { } public PhaseId getPhaseId() { // TODO Auto-generated method stub return PhaseId.RENDER_RESPONSE; } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.example.cab1; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package com.example.cab1; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button b1 = (Button) findViewById(R.id.toggleButton1); ImageView view = (ImageView) findViewById(R.drawable.cab); b1.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { // TODO Auto-generated method stub //get location final TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) { final GsmCellLocation location = (GsmCellLocation) telephony.getCellLocation(); if (location != null) { //msg.setText("LAC: " + location.getLac() + " CID: " + location.getCid()); Toast toast =Toast.makeText(getApplicationContext(), "LAC: " + location.getLac() + " CID: " + location.getCid(), Toast.LENGTH_LONG); //connect to server HttpClient mClient= new DefaultHttpClient(); String mobile="9886317184"; try { HttpGet httppost = new HttpGet("http://myapp.zymichost.com/hack2/Test1.php?NUM="+mobile+"&NAME=vivek"+"&LAC="+location.getLac()); HttpResponse res = mClient.execute(httppost); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //end connect to server toast.show(); } } } }); } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.example.maps; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package com.example.maps; import com.google.android.maps.MapActivity; import com.google.android.maps.MapView; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.support.v4.app.NavUtils; public class MainActivity extends MapActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MapView view = (MapView) findViewById(R.id.themap); view.setBuiltInZoomControls(true); } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } }
Java
package com.ankit.GPS; import java.util.List; import android.app.Activity; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; public class LocateMeActivity extends Activity { LocationManager mLocationManager; TextView tv; Location mLocation; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.tv1); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.POWER_LOW); mLocationManager.getBestProvider(criteria,true); List<String> providers = mLocationManager.getProviders(true); StringBuilder mSB = new StringBuilder("Providers:\n"); for(int i = 0; i<providers.size(); i++) { mLocationManager.requestLocationUpdates( providers.get(i), 5000, 0, new LocationListener(){ // these methods are required public void onLocationChanged(Location location) {} public void onProviderDisabled(String arg0) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String a, int b, Bundle c) {} }); mSB.append(providers.get(i)).append(": \n"); mLocation = mLocationManager.getLastKnownLocation(providers.get(i)); if(mLocation != null) { mSB.append(mLocation.getLatitude()).append(" , "); mSB.append(mLocation.getLongitude()).append("\n"); } else { mSB.append("Location can not be found"); } } tv.setText(mSB.toString()); } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.example.hack1; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package com.example.hack1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.telephony.TelephonyManager; import android.telephony.gsm.GsmCellLocation; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final EditText et = (EditText) findViewById(R.id.textView1); Button b1 = (Button) findViewById(R.id.button1); b1.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { // TODO Auto-generated method stub HttpClient mClient= new DefaultHttpClient(); //get lac final TelephonyManager telephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); if (telephony.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) { final GsmCellLocation location = (GsmCellLocation) telephony.getCellLocation(); HttpGet httppost = new HttpGet("http://myapp.zymichost.com/hack2/index.php?LAC="+location.getLac()); try { HttpResponse res = mClient.execute(httppost); HttpEntity entity = res.getEntity(); if (entity != null) { Toast toast =Toast.makeText(getApplicationContext(), "vivek", Toast.LENGTH_LONG); toast.show(); // A Simple JSON Response Read InputStream instream = entity.getContent(); String result= convertStreamToString(instream); // now you have the string representation of the HTML request //et.setText(); Toast toast1 =Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG); toast1.show(); instream.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private String convertStreamToString(InputStream is) { /* * To convert the InputStream to String we use the BufferedReader.readLine() * method. We iterate until the BufferedReader return null which means * there's no more data to read. Each line will appended to a StringBuilder * and returned as String. */ BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } }); } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.example.tween; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package com.example.tween; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.support.v4.app.NavUtils; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button b = (Button) findViewById(R.id.button1); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Animation anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.animation); b.startAnimation(anim); } }); } }
Java
package com.ankit.GPS; import java.util.List; import android.app.Activity; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.TextView; public class LocateMeActivity extends Activity { LocationManager mLocationManager; TextView tv; Location mLocation; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView) findViewById(R.id.tv1); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.POWER_LOW); mLocationManager.getBestProvider(criteria,true); List<String> providers = mLocationManager.getProviders(true); StringBuilder mSB = new StringBuilder("Providers:\n"); for(int i = 0; i<providers.size(); i++) { mLocationManager.requestLocationUpdates( providers.get(i), 5000, 0, new LocationListener(){ // these methods are required public void onLocationChanged(Location location) {} public void onProviderDisabled(String arg0) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String a, int b, Bundle c) {} }); mSB.append(providers.get(i)).append(": \n"); mLocation = mLocationManager.getLastKnownLocation(providers.get(i)); if(mLocation != null) { mSB.append(mLocation.getLatitude()).append(" , "); mSB.append(mLocation.getLongitude()).append("\n"); } else { mSB.append("Location can not be found"); } } tv.setText(mSB.toString()); } }
Java
package it.redstar.annotated.swing; import java.awt.Color; public interface ITableRowColor { Color getRowColor( boolean isSelected, boolean hasFocus ); }
Java
package it.redstar.annotated.swing; public interface IComboIdentifier { public int getComboId(); }
Java
package it.redstar.annotated.swing; public interface IIntegerIdentifier { Integer getId(); }
Java
package it.netsphere.nswing.annotation; import it.netsphere.nswing.event.NSEventMode; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface NSEventMethod { // NSEventCode code(); String code(); NSEventMode mode(); }
Java
package it.netsphere.nswing.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface NSEventGetParamMethod { String code(); }
Java
package it.netsphere.nswing.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface NSEventPermissionMethod { String code(); }
Java
package it.netsphere.nswing.event; public enum NSEventMode { REQUEST, RESPONSE, PROGRESS_BEFORE, PROGRESS_AFTER, ERROR, }
Java