code
stringlengths
3
1.18M
language
stringclasses
1 value
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Window; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout; /** * @date August 2, 2010. * @author Mark Wyszomierski (markww@gmail.com). * */ public class WebViewActivity extends Activity { private static final String TAG = "WebViewActivity"; public static final String INTENT_EXTRA_URL = Foursquared.PACKAGE_NAME + ".WebViewActivity.INTENT_EXTRA_URL"; private WebView mWebView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); mWebView = new WebView(this); mWebView.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebViewClient(new EmbeddedWebViewClient()); if (getIntent().getStringExtra(INTENT_EXTRA_URL) != null) { mWebView.loadUrl(getIntent().getStringExtra(INTENT_EXTRA_URL)); } else { Log.e(TAG, "Missing url in intent extras."); finish(); return; } setContentView(mWebView); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } private class EmbeddedWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); setProgressBarIndeterminateVisibility(true); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); setProgressBarIndeterminateVisibility(false); } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.Display; import android.view.WindowManager; import android.webkit.WebView; import android.widget.LinearLayout; /** * Renders the result of a checkin using a CheckinResult object. This is called * from CheckinExecuteActivity. It would be nicer to put this in another activity, * but right now the CheckinResult is quite large and would require a good amount * of work to add serializers for all its inner classes. This wouldn't be a huge * problem, but maintaining it as the classes evolve could more trouble than it's * worth. * * The only way the user can dismiss this dialog is by hitting the 'back' key. * CheckingExecuteActivity depends on this so it knows when to finish() itself. * * @date March 3, 2010. * @author Mark Wyszomierski (markww@gmail.com), foursquare. * */ public class WebViewDialog extends Dialog { private WebView mWebView; private String mTitle; private String mContent; public WebViewDialog(Context context, String title, String content) { super(context, R.style.ThemeCustomDlgBase_ThemeCustomDlg); mTitle = title; mContent = content; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview_dialog); setTitle(mTitle); mWebView = (WebView)findViewById(R.id.webView); mWebView.loadDataWithBaseURL("--", mContent, "text/html", "utf-8", ""); LinearLayout llMain = (LinearLayout)findViewById(R.id.llMain); inflateDialog(llMain); } /** * Force-inflates a dialog main linear-layout to take max available screen space even though * contents might not occupy full screen size. */ public static void inflateDialog(LinearLayout layout) { WindowManager wm = (WindowManager) layout.getContext().getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); layout.setMinimumWidth(display.getWidth() - 30); layout.setMinimumHeight(display.getHeight() - 40); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import android.app.Activity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.util.StringFormatters; import com.joelapenna.foursquared.util.TipUtils; /** * Shows actions a user can perform on a tip, which includes marking a tip * as a to-do, marking a tip as done, un-marking a tip. Marking a tip as * a to-do will generate a to-do, which has the tip as a child object. * * The intent will return a Tip object and a Todo object (if the final state * of the tip was marked as a Todo). In the case where a Todo is returned, * the Tip will be the representation as found within the Todo object. * * If the user does not modify the tip, no intent data is returned. If the * final state of the tip was not marked as a to-do, the Todo object is * not returned. * * @date September 2, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class TipActivity extends Activity { private static final String TAG = "TipActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_TIP_PARCEL = Foursquared.PACKAGE_NAME + ".TipActivity.EXTRA_TIP_PARCEL"; public static final String EXTRA_VENUE_CLICKABLE = Foursquared.PACKAGE_NAME + ".TipActivity.EXTRA_VENUE_CLICKABLE"; /** * Always returned if the user modifies the tip in any way. Captures the * new <status> attribute of the tip. It may not have been changed by the * user. */ public static final String EXTRA_TIP_RETURNED = Foursquared.PACKAGE_NAME + ".TipActivity.EXTRA_TIP_RETURNED"; /** * If the user marks the tip as to-do as the final state, then a to-do object * will also be returned here. The to-do object has the same tip object as * returned in EXTRA_TIP_PARCEL_RETURNED as a child member. */ public static final String EXTRA_TODO_RETURNED = Foursquared.PACKAGE_NAME + ".TipActivity.EXTRA_TODO_RETURNED"; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.tip_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTipTask(this); setPreparedResultIntent(); } else { mStateHolder = new StateHolder(); if (getIntent().getExtras() != null) { if (getIntent().hasExtra(EXTRA_TIP_PARCEL)) { Tip tip = getIntent().getExtras().getParcelable(EXTRA_TIP_PARCEL); mStateHolder.setTip(tip); } else { Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras."); finish(); return; } if (getIntent().hasExtra(EXTRA_VENUE_CLICKABLE)) { mStateHolder.setVenueClickable( getIntent().getBooleanExtra(EXTRA_VENUE_CLICKABLE, true)); } } else { Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras."); finish(); return; } } ensureUi(); } @Override public void onResume() { super.onResume(); if (mStateHolder.getIsRunningTipTask()) { startProgressBar(); } } @Override public void onPause() { super.onPause(); if (isFinishing()) { stopProgressBar(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTipTask(null); return mStateHolder; } private void ensureUi() { Tip tip = mStateHolder.getTip(); Venue venue = tip.getVenue(); LinearLayout llHeader = (LinearLayout)findViewById(R.id.tipActivityHeaderView); if (mStateHolder.getVenueClickable()) { llHeader.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showVenueDetailsActivity(mStateHolder.getTip().getVenue()); } }); } ImageView ivVenueChevron = (ImageView)findViewById(R.id.tipActivityVenueChevron); if (mStateHolder.getVenueClickable()) { ivVenueChevron.setVisibility(View.VISIBLE); } else { ivVenueChevron.setVisibility(View.INVISIBLE); } TextView tvTitle = (TextView)findViewById(R.id.tipActivityName); TextView tvAddress = (TextView)findViewById(R.id.tipActivityAddress); if (venue != null) { tvTitle.setText(venue.getName()); tvAddress.setText( venue.getAddress() + (TextUtils.isEmpty(venue.getCrossstreet()) ? "" : " (" + venue.getCrossstreet() + ")")); } else { tvTitle.setText(""); tvAddress.setText(""); } TextView tvBody = (TextView)findViewById(R.id.tipActivityBody); tvBody.setText(tip.getText()); String created = getResources().getString( R.string.tip_activity_created, StringFormatters.getTipAge(getResources(), tip.getCreated())); TextView tvDate = (TextView)findViewById(R.id.tipActivityDate); tvDate.setText(created); TextView tvAuthor = (TextView)findViewById(R.id.tipActivityAuthor); if (tip.getUser() != null) { tvAuthor.setText(tip.getUser().getFirstname()); tvAuthor.setClickable(true); tvAuthor.setFocusable(true); tvAuthor.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showUserDetailsActivity(mStateHolder.getTip().getUser()); } }); tvDate.setText(tvDate.getText() + getResources().getString( R.string.tip_activity_created_by)); } else { tvAuthor.setText(""); } Button btn1 = (Button)findViewById(R.id.tipActivityyAddTodoList); Button btn2 = (Button)findViewById(R.id.tipActivityIveDoneThis); btn1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onBtnTodo(); } }); btn2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onBtnDone(); } }); updateButtonStates(); } private void onBtnTodo() { Tip tip = mStateHolder.getTip(); if (TipUtils.isTodo(tip)) { mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(), TipTask.ACTION_UNMARK_TODO); } else { mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(), TipTask.ACTION_TODO); } } private void onBtnDone() { Tip tip = mStateHolder.getTip(); if (TipUtils.isDone(tip)) { mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(), TipTask.ACTION_UNMARK_DONE); } else { mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(), TipTask.ACTION_DONE); } } private void updateButtonStates() { Button btn1 = (Button)findViewById(R.id.tipActivityyAddTodoList); Button btn2 = (Button)findViewById(R.id.tipActivityIveDoneThis); TextView tv = (TextView)findViewById(R.id.tipActivityCongrats); Tip tip = mStateHolder.getTip(); if (TipUtils.isTodo(tip)) { btn1.setText(getResources().getString(R.string.tip_activity_btn_tip_1)); // "REMOVE FROM MY TO-DO LIST" btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_2)); // "I'VE DONE THIS" btn1.setVisibility(View.VISIBLE); tv.setVisibility(View.GONE); } else if (TipUtils.isDone(tip)) { tv.setText(getResources().getString(R.string.tip_activity_btn_tip_4)); // "CONGRATS! YOU'VE DONE THIS" btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_3)); // "UNDO THIS" btn1.setVisibility(View.GONE); tv.setVisibility(View.VISIBLE); } else { btn1.setText(getResources().getString(R.string.tip_activity_btn_tip_0)); // "ADD TO MY TO-DO LIST" btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_2)); // "I'VE DONE THIS" btn1.setVisibility(View.VISIBLE); tv.setVisibility(View.GONE); } } private void showUserDetailsActivity(User user) { Intent intent = new Intent(this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, user.getId()); startActivity(intent); } private void showVenueDetailsActivity(Venue venue) { Intent intent = new Intent(this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue); startActivity(intent); } private void startProgressBar() { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, "", getResources().getString(R.string.tip_activity_progress_message)); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } private void prepareResultIntent(Tip tip, Todo todo) { Intent intent = new Intent(); intent.putExtra(EXTRA_TIP_RETURNED, tip); if (todo != null) { intent.putExtra(EXTRA_TODO_RETURNED, todo); // tip is also a part of the to-do. } mStateHolder.setPreparedResult(intent); setPreparedResultIntent(); } private void setPreparedResultIntent() { if (mStateHolder.getPreparedResult() != null) { setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult()); } } private void onTipTaskComplete(FoursquareType tipOrTodo, int type, Exception ex) { stopProgressBar(); mStateHolder.setIsRunningTipTask(false); if (tipOrTodo != null) { // When the tip and todo are serialized into the intent result, the // link between them will be lost, they'll appear as two separate // tip object instances (ids etc will all be the same though). if (tipOrTodo instanceof Tip) { Tip tip = (Tip)tipOrTodo; mStateHolder.setTip(tip); prepareResultIntent(tip, null); } else { Todo todo = (Todo)tipOrTodo; Tip tip = todo.getTip(); mStateHolder.setTip(tip); prepareResultIntent(tip, todo); } } else if (ex != null) { Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Error updating tip!", Toast.LENGTH_LONG).show(); } ensureUi(); } private static class TipTask extends AsyncTask<String, Void, FoursquareType> { private TipActivity mActivity; private String mTipId; private int mTask; private Exception mReason; public static final int ACTION_TODO = 0; public static final int ACTION_DONE = 1; public static final int ACTION_UNMARK_TODO = 2; public static final int ACTION_UNMARK_DONE = 3; public TipTask(TipActivity activity, String tipid, int task) { mActivity = activity; mTipId = tipid; mTask = task; } public void setActivity(TipActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(); } @Override protected FoursquareType doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); switch (mTask) { case ACTION_TODO: return foursquare.markTodo(mTipId); // returns a todo. case ACTION_DONE: return foursquare.markDone(mTipId); // returns a tip. case ACTION_UNMARK_TODO: return foursquare.unmarkTodo(mTipId); // returns a tip case ACTION_UNMARK_DONE: return foursquare.unmarkDone(mTipId); // returns a tip default: return null; } } catch (Exception e) { if (DEBUG) Log.d(TAG, "TipTask: Exception performing tip task.", e); mReason = e; } return null; } @Override protected void onPostExecute(FoursquareType tipOrTodo) { if (DEBUG) Log.d(TAG, "TipTask: onPostExecute()"); if (mActivity != null) { mActivity.onTipTaskComplete(tipOrTodo, mTask, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTipTaskComplete(null, mTask, new Exception("Tip task cancelled.")); } } } private static class StateHolder { private Tip mTip; private TipTask mTipTask; private boolean mIsRunningTipTask; private boolean mVenueClickable; private Intent mPreparedResult; public StateHolder() { mTip = null; mPreparedResult = null; mIsRunningTipTask = false; mVenueClickable = true; } public Tip getTip() { return mTip; } public void setTip(Tip tip) { mTip = tip; } public void startTipTask(TipActivity activity, String tipId, int task) { mIsRunningTipTask = true; mTipTask = new TipTask(activity, tipId, task); mTipTask.execute(); } public void setActivityForTipTask(TipActivity activity) { if (mTipTask != null) { mTipTask.setActivity(activity); } } public void setIsRunningTipTask(boolean isRunningTipTask) { mIsRunningTipTask = isRunningTipTask; } public boolean getIsRunningTipTask() { return mIsRunningTipTask; } public boolean getVenueClickable() { return mVenueClickable; } public void setVenueClickable(boolean venueClickable) { mVenueClickable = venueClickable; } public Intent getPreparedResult() { return mPreparedResult; } public void setPreparedResult(Intent intent) { mPreparedResult = intent; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Settings; import com.joelapenna.foursquare.types.User; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * Lets the user set pings on/off for a given friend. * * @date September 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class UserDetailsPingsActivity extends Activity { private static final String TAG = "UserDetailsPingsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME + ".UserDetailsPingsActivity.EXTRA_USER_PARCEL"; public static final String EXTRA_USER_RETURNED = Foursquared.PACKAGE_NAME + ".UserDetailsPingsActivity.EXTRA_USER_RETURNED"; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.user_details_pings_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); setPreparedResultIntent(); } else { mStateHolder = new StateHolder(); if (getIntent().getExtras() != null) { if (getIntent().hasExtra(EXTRA_USER_PARCEL)) { User user = getIntent().getExtras().getParcelable(EXTRA_USER_PARCEL); mStateHolder.setUser(user); } else { Log.e(TAG, TAG + " requires a user pareclable in its intent extras."); finish(); return; } } else { Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras."); finish(); return; } } ensureUi(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { User user = mStateHolder.getUser(); TextView tv = (TextView)findViewById(R.id.userDetailsPingsActivityDescription); Button btn = (Button)findViewById(R.id.userDetailsPingsActivityButton); if (user.getSettings().getGetPings()) { tv.setText(getString(R.string.user_details_pings_activity_description_on, user.getFirstname())); btn.setText(getString(R.string.user_details_pings_activity_pings_off, user.getFirstname())); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); setProgressBarIndeterminateVisibility(true); mStateHolder.startPingsTask(UserDetailsPingsActivity.this, false); } }); } else { tv.setText(getString(R.string.user_details_pings_activity_description_off, user.getFirstname())); btn.setText(getString(R.string.user_details_pings_activity_pings_on, user.getFirstname())); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); setProgressBarIndeterminateVisibility(true); mStateHolder.startPingsTask(UserDetailsPingsActivity.this, true); } }); } if (mStateHolder.getIsRunningTaskPings()) { btn.setEnabled(false); setProgressBarIndeterminateVisibility(true); } else { btn.setEnabled(true); setProgressBarIndeterminateVisibility(false); } } private void setPreparedResultIntent() { if (mStateHolder.getPreparedResult() != null) { setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult()); } } private void prepareResultIntent() { Intent intent = new Intent(); intent.putExtra(EXTRA_USER_RETURNED, mStateHolder.getUser()); mStateHolder.setPreparedResult(intent); setPreparedResultIntent(); } private void onTaskPingsComplete(Settings settings, String userId, boolean on, Exception ex) { mStateHolder.setIsRunningTaskPings(false); // The api is returning pings = false for all cases, so manually overwrite, // assume a non-null settings object is success. if (settings != null) { settings.setGetPings(on); mStateHolder.setSettingsResult(settings); prepareResultIntent(); } else { Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show(); } ensureUi(); } private static class TaskPings extends AsyncTask<Void, Void, Settings> { private UserDetailsPingsActivity mActivity; private String mUserId; private boolean mOn; private Exception mReason; public TaskPings(UserDetailsPingsActivity activity, String userId, boolean on) { mActivity = activity; mUserId = userId; mOn = on; } public void setActivity(UserDetailsPingsActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.ensureUi(); } @Override protected Settings doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.setpings(mUserId, mOn); } catch (Exception e) { if (DEBUG) Log.d(TAG, "TipTask: Exception performing tip task.", e); mReason = e; } return null; } @Override protected void onPostExecute(Settings settings) { if (mActivity != null) { mActivity.onTaskPingsComplete(settings, mUserId, mOn, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskPingsComplete(null, mUserId, mOn, new FoursquareException("Tip task cancelled.")); } } } private static class StateHolder { private User mUser; private boolean mIsRunningTask; private Intent mPreparedResult; private TaskPings mTaskPings; public StateHolder() { mPreparedResult = null; mIsRunningTask = false; } public User getUser() { return mUser; } public void setUser(User user) { mUser = user; } public void setSettingsResult(Settings settings) { mUser.getSettings().setGetPings(settings.getGetPings()); } public void startPingsTask(UserDetailsPingsActivity activity, boolean on) { if (!mIsRunningTask) { mIsRunningTask = true; mTaskPings = new TaskPings(activity, mUser.getId(), on); mTaskPings.execute(); } } public void setActivity(UserDetailsPingsActivity activity) { if (mTaskPings != null) { mTaskPings.setActivity(activity); } } public void setIsRunningTaskPings(boolean isRunning) { mIsRunningTask = isRunning; } public boolean getIsRunningTaskPings() { return mIsRunningTask; } public Intent getPreparedResult() { return mPreparedResult; } public void setPreparedResult(Intent intent) { mPreparedResult = intent; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.app.LoadableListActivity; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.FriendListAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * Shows a list of friends for the user id passed as an intent extra. * * @date March 9, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserDetailsFriendsActivity extends LoadableListActivity { static final String TAG = "UserDetailsFriendsActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER_ID = Foursquared.PACKAGE_NAME + ".UserDetailsFriendsActivity.EXTRA_USER_ID"; public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME + ".UserDetailsFriendsActivity.EXTRA_USER_NAME"; public static final String EXTRA_SHOW_ADD_FRIEND_OPTIONS = Foursquared.PACKAGE_NAME + ".UserDetailsFriendsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS"; private StateHolder mStateHolder; private FriendListAdapter mListAdapter; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTaskFriends(this); } else { if (getIntent().hasExtra(EXTRA_USER_ID) && getIntent().hasExtra(EXTRA_USER_NAME)) { mStateHolder = new StateHolder( getIntent().getStringExtra(EXTRA_USER_ID), getIntent().getStringExtra(EXTRA_USER_NAME)); } else { Log.e(TAG, TAG + " requires a userid and username in its intent extras."); finish(); return; } mStateHolder.startTaskFriends(this); } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mStateHolder.cancelTasks(); mListAdapter.removeObserver(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTaskFriends(null); return mStateHolder; } private void ensureUi() { mListAdapter = new FriendListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); mListAdapter.setGroup(mStateHolder.getFriends()); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(true); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { User user = (User) parent.getAdapter().getItem(position); Intent intent = new Intent(UserDetailsFriendsActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user); intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true); startActivity(intent); } }); if (mStateHolder.getIsRunningFriendsTask()) { setLoadingView(); } else if (mStateHolder.getFetchedFriendsOnce() && mStateHolder.getFriends().size() == 0) { setEmptyView(); } setTitle(getString(R.string.user_details_friends_activity_title, mStateHolder.getUsername())); } private void onFriendsTaskComplete(Group<User> group, Exception ex) { mListAdapter.removeObserver(); mListAdapter = new FriendListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); if (group != null) { mStateHolder.setFriends(group); mListAdapter.setGroup(mStateHolder.getFriends()); getListView().setAdapter(mListAdapter); } else { mStateHolder.setFriends(new Group<User>()); mListAdapter.setGroup(mStateHolder.getFriends()); getListView().setAdapter(mListAdapter); NotificationsUtil.ToastReasonForFailure(this, ex); } mStateHolder.setIsRunningFriendsTask(false); mStateHolder.setFetchedFriendsOnce(true); // TODO: We can probably tighten this up by just calling ensureUI() again. if (mStateHolder.getFriends().size() == 0) { setEmptyView(); } } /** * Gets friends of the current user we're working for. */ private static class FriendsTask extends AsyncTask<String, Void, Group<User>> { private UserDetailsFriendsActivity mActivity; private Exception mReason; public FriendsTask(UserDetailsFriendsActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.setLoadingView(); } @Override protected Group<User> doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.friends( params[0], LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Group<User> users) { if (mActivity != null) { mActivity.onFriendsTaskComplete(users, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onFriendsTaskComplete(null, mReason); } } public void setActivity(UserDetailsFriendsActivity activity) { mActivity = activity; } } private static class StateHolder { private String mUserId; private String mUsername; private Group<User> mFriends; private FriendsTask mTaskFriends; private boolean mIsRunningFriendsTask; private boolean mFetchedFriendsOnce; public StateHolder(String userId, String username) { mUserId = userId; mUsername = username; mIsRunningFriendsTask = false; mFetchedFriendsOnce = false; mFriends = new Group<User>(); } public String getUsername() { return mUsername; } public Group<User> getFriends() { return mFriends; } public void setFriends(Group<User> friends) { mFriends = friends; } public void startTaskFriends(UserDetailsFriendsActivity activity) { mIsRunningFriendsTask = true; mTaskFriends = new FriendsTask(activity); mTaskFriends.execute(mUserId); } public void setActivityForTaskFriends(UserDetailsFriendsActivity activity) { if (mTaskFriends != null) { mTaskFriends.setActivity(activity); } } public void setIsRunningFriendsTask(boolean isRunning) { mIsRunningFriendsTask = isRunning; } public boolean getIsRunningFriendsTask() { return mIsRunningFriendsTask; } public void setFetchedFriendsOnce(boolean fetchedOnce) { mFetchedFriendsOnce = fetchedOnce; } public boolean getFetchedFriendsOnce() { return mFetchedFriendsOnce; } public void cancelTasks() { if (mTaskFriends != null) { mTaskFriends.setActivity(null); mTaskFriends.cancel(true); } } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.app.LoadableListActivity; import com.joelapenna.foursquared.location.BestLocationListener; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.MenuUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.VenueUtils; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import com.joelapenna.foursquared.widget.VenueListAdapter; import android.app.Activity; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Observable; import java.util.Observer; import java.util.Set; /** * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -Refactored to allow NearbyVenuesMapActivity to list to search results. */ public class NearbyVenuesActivity extends LoadableListActivity { static final String TAG = "NearbyVenuesActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_STARTUP_GEOLOC_DELAY = Foursquared.PACKAGE_NAME + ".NearbyVenuesActivity.INTENT_EXTRA_STARTUP_GEOLOC_DELAY"; private static final int MENU_REFRESH = 0; private static final int MENU_ADD_VENUE = 1; private static final int MENU_SEARCH = 2; private static final int MENU_MAP = 3; private static final int RESULT_CODE_ACTIVITY_VENUE = 1; private StateHolder mStateHolder = new StateHolder(); private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver(); private ListView mListView; private SeparatedListAdapter mListAdapter; private LinearLayout mFooterView; private TextView mTextViewFooter; private Handler mHandler; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mHandler = new Handler(); mListView = getListView(); mListAdapter = new SeparatedListAdapter(this); mListView.setAdapter(mListAdapter); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Venue venue = (Venue) parent.getAdapter().getItem(position); startItemActivity(venue); } }); // We can dynamically add a footer to our loadable listview. LayoutInflater inflater = LayoutInflater.from(this); mFooterView = (LinearLayout)inflater.inflate(R.layout.geo_loc_address_view, null); mTextViewFooter = (TextView)mFooterView.findViewById(R.id.footerTextView); LinearLayout llMain = (LinearLayout)findViewById(R.id.main); llMain.addView(mFooterView); // Check if we're returning from a configuration change. if (getLastNonConfigurationInstance() != null) { if (DEBUG) Log.d(TAG, "Restoring state."); mStateHolder = (StateHolder) getLastNonConfigurationInstance(); mStateHolder.setActivity(this); } else { mStateHolder = new StateHolder(); mStateHolder.setQuery(""); } // Start a new search if one is not running or we have no results. if (mStateHolder.getIsRunningTask()) { setProgressBarIndeterminateVisibility(true); putSearchResultsInAdapter(mStateHolder.getResults()); ensureTitle(false); } else if (mStateHolder.getResults().size() == 0) { long firstLocDelay = 0L; if (getIntent().getExtras() != null) { firstLocDelay = getIntent().getLongExtra(INTENT_EXTRA_STARTUP_GEOLOC_DELAY, 0L); } startTask(firstLocDelay); } else { onTaskComplete(mStateHolder.getResults(), mStateHolder.getReverseGeoLoc(), null); } populateFooter(mStateHolder.getReverseGeoLoc()); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public void onResume() { super.onResume(); if (DEBUG) Log.d(TAG, "onResume"); ((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver); } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver); if (isFinishing()) { mStateHolder.cancelAllTasks(); mListAdapter.removeObserver(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) // .setIcon(R.drawable.ic_menu_refresh); menu.add(Menu.NONE, MENU_SEARCH, Menu.NONE, R.string.search_label) // .setIcon(R.drawable.ic_menu_search) // .setAlphabeticShortcut(SearchManager.MENU_KEY); menu.add(Menu.NONE, MENU_ADD_VENUE, Menu.NONE, R.string.nearby_menu_add_venue) // .setIcon(R.drawable.ic_menu_add); // Shows a map of all nearby venues, works but not going into this version. //menu.add(Menu.NONE, MENU_MAP, Menu.NONE, "Map") // .setIcon(R.drawable.ic_menu_places); MenuUtils.addPreferencesToMenu(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: if (mStateHolder.getIsRunningTask() == false) { startTask(); } return true; case MENU_SEARCH: Intent intent = new Intent(NearbyVenuesActivity.this, SearchVenuesActivity.class); intent.setAction(Intent.ACTION_SEARCH); startActivity(intent); return true; case MENU_ADD_VENUE: startActivity(new Intent(NearbyVenuesActivity.this, AddVenueActivity.class)); return true; case MENU_MAP: startActivity(new Intent(NearbyVenuesActivity.this, NearbyVenuesMapActivity.class)); return true; } return super.onOptionsItemSelected(item); } @Override public int getNoSearchResultsStringId() { return R.string.no_nearby_venues; } public void putSearchResultsInAdapter(Group<Group<Venue>> searchResults) { if (DEBUG) Log.d(TAG, "putSearchResultsInAdapter"); mListAdapter.removeObserver(); mListAdapter = new SeparatedListAdapter(this); if (searchResults != null && searchResults.size() > 0) { int groupCount = searchResults.size(); for (int groupsIndex = 0; groupsIndex < groupCount; groupsIndex++) { Group<Venue> group = searchResults.get(groupsIndex); if (group.size() > 0) { VenueListAdapter groupAdapter = new VenueListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); groupAdapter.setGroup(group); if (DEBUG) Log.d(TAG, "Adding Section: " + group.getType()); mListAdapter.addSection(group.getType(), groupAdapter); } } } else { setEmptyView(); } mListView.setAdapter(mListAdapter); } private void startItemActivity(Venue venue) { Intent intent = new Intent(NearbyVenuesActivity.this, VenueActivity.class); if (mStateHolder.isFullyLoadedVenue(venue.getId())) { intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE, venue); } else { intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue); } startActivityForResult(intent, RESULT_CODE_ACTIVITY_VENUE); } private void ensureTitle(boolean finished) { if (finished) { setTitle(getString(R.string.title_search_finished_noquery)); } else { setTitle(getString(R.string.title_search_inprogress_noquery)); } } private void populateFooter(String reverseGeoLoc) { mFooterView.setVisibility(View.VISIBLE); mTextViewFooter.setText(reverseGeoLoc); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case RESULT_CODE_ACTIVITY_VENUE: if (resultCode == Activity.RESULT_OK && data.hasExtra(VenueActivity.EXTRA_VENUE_RETURNED)) { Venue venue = (Venue)data.getParcelableExtra(VenueActivity.EXTRA_VENUE_RETURNED); mStateHolder.updateVenue(venue); mListAdapter.notifyDataSetInvalidated(); } break; } } private long getClearGeolocationOnSearch() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); boolean cacheGeolocation = settings.getBoolean(Preferences.PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES, true); if (cacheGeolocation) { return 0L; } else { Foursquared foursquared = ((Foursquared) getApplication()); foursquared.clearLastKnownLocation(); foursquared.removeLocationUpdates(mSearchLocationObserver); foursquared.requestLocationUpdates(mSearchLocationObserver); return 2000L; } } /** If location changes, auto-start a nearby venues search. */ private class SearchLocationObserver implements Observer { private boolean mRequestedFirstSearch = false; @Override public void update(Observable observable, Object data) { Location location = (Location) data; // Fire a search if we haven't done so yet. if (!mRequestedFirstSearch && ((BestLocationListener) observable).isAccurateEnough(location)) { mRequestedFirstSearch = true; if (mStateHolder.getIsRunningTask() == false) { // Since we were told by the system that location has changed, no need to make the // task wait before grabbing the current location. mHandler.post(new Runnable() { public void run() { startTask(0L); } }); } } } } private void startTask() { startTask(getClearGeolocationOnSearch()); } private void startTask(long geoLocDelayTimeInMs) { if (mStateHolder.getIsRunningTask() == false) { setProgressBarIndeterminateVisibility(true); ensureTitle(false); if (mStateHolder.getResults().size() == 0) { setLoadingView(""); } mStateHolder.startTask(this, mStateHolder.getQuery(), geoLocDelayTimeInMs); } } private void onTaskComplete(Group<Group<Venue>> result, String reverseGeoLoc, Exception ex) { if (result != null) { mStateHolder.setResults(result); mStateHolder.setReverseGeoLoc(reverseGeoLoc); } else { mStateHolder.setResults(new Group<Group<Venue>>()); NotificationsUtil.ToastReasonForFailure(NearbyVenuesActivity.this, ex); } populateFooter(mStateHolder.getReverseGeoLoc()); putSearchResultsInAdapter(mStateHolder.getResults()); setProgressBarIndeterminateVisibility(false); ensureTitle(true); mStateHolder.cancelAllTasks(); } /** Handles the work of finding nearby venues. */ private static class SearchTask extends AsyncTask<Void, Void, Group<Group<Venue>>> { private NearbyVenuesActivity mActivity; private Exception mReason = null; private String mQuery; private long mSleepTimeInMs; private Foursquare mFoursquare; private String mReverseGeoLoc; // Filled in after execution. private String mNoLocException; private String mLabelNearby; public SearchTask(NearbyVenuesActivity activity, String query, long sleepTimeInMs) { super(); mActivity = activity; mQuery = query; mSleepTimeInMs = sleepTimeInMs; mFoursquare = ((Foursquared)activity.getApplication()).getFoursquare(); mNoLocException = activity.getResources().getString(R.string.nearby_venues_no_location); mLabelNearby = activity.getResources().getString(R.string.nearby_venues_label_nearby); } @Override public void onPreExecute() { } @Override public Group<Group<Venue>> doInBackground(Void... params) { try { // If the user has chosen to clear their geolocation on each search, wait briefly // for a new fix to come in. The two-second wait time is arbitrary and can be // changed to something more intelligent. if (mSleepTimeInMs > 0L) { Thread.sleep(mSleepTimeInMs); } // Get last known location. Location location = ((Foursquared) mActivity.getApplication()).getLastKnownLocation(); if (location == null) { throw new FoursquareException(mNoLocException); } // Get the venues. Group<Group<Venue>> results = mFoursquare.venues(LocationUtils .createFoursquareLocation(location), mQuery, 30); // Try to get our reverse geolocation. mReverseGeoLoc = getGeocode(mActivity, location); return results; } catch (Exception e) { mReason = e; } return null; } @Override public void onPostExecute(Group<Group<Venue>> groups) { if (mActivity != null) { mActivity.onTaskComplete(groups, mReverseGeoLoc, mReason); } } private String getGeocode(Context context, Location location) { Geocoder geocoded = new Geocoder(context, Locale.getDefault()); try { List<Address> addresses = geocoded.getFromLocation( location.getLatitude(), location.getLongitude(), 1); if (addresses.size() > 0) { Address address = addresses.get(0); StringBuilder sb = new StringBuilder(128); sb.append(mLabelNearby); sb.append(" "); sb.append(address.getAddressLine(0)); if (addresses.size() > 1) { sb.append(", "); sb.append(address.getAddressLine(1)); } if (addresses.size() > 2) { sb.append(", "); sb.append(address.getAddressLine(2)); } if (!TextUtils.isEmpty(address.getLocality())) { if (sb.length() > 0) { sb.append(", "); } sb.append(address.getLocality()); } return sb.toString(); } } catch (Exception ex) { if (DEBUG) Log.d(TAG, "SearchTask: error geocoding current location.", ex); } return null; } public void setActivity(NearbyVenuesActivity activity) { mActivity = activity; } } private static class StateHolder { private Group<Group<Venue>> mResults; private String mQuery; private String mReverseGeoLoc; private SearchTask mSearchTask; private Set<String> mFullyLoadedVenueIds; public StateHolder() { mResults = new Group<Group<Venue>>(); mSearchTask = null; mFullyLoadedVenueIds = new HashSet<String>(); } public String getQuery() { return mQuery; } public void setQuery(String query) { mQuery = query; } public String getReverseGeoLoc() { return mReverseGeoLoc; } public void setReverseGeoLoc(String reverseGeoLoc) { mReverseGeoLoc = reverseGeoLoc; } public Group<Group<Venue>> getResults() { return mResults; } public void setResults(Group<Group<Venue>> results) { mResults = results; } public void startTask(NearbyVenuesActivity activity, String query, long sleepTimeInMs) { mSearchTask = new SearchTask(activity, query, sleepTimeInMs); mSearchTask.execute(); } public boolean getIsRunningTask() { return mSearchTask != null; } public void cancelAllTasks() { if (mSearchTask != null) { mSearchTask.cancel(true); mSearchTask = null; } } public void setActivity(NearbyVenuesActivity activity) { if (mSearchTask != null) { mSearchTask.setActivity(activity); } } public void updateVenue(Venue venue) { for (Group<Venue> it : mResults) { for (int j = 0; j < it.size(); j++) { if (it.get(j).getId().equals(venue.getId())) { // The /venue api call does not supply the venue's distance value, // so replace it manually here. Venue replaced = it.get(j); Venue replacer = VenueUtils.cloneVenue(venue); replacer.setDistance(replaced.getDistance()); it.set(j, replacer); mFullyLoadedVenueIds.add(replacer.getId()); } } } } public boolean isFullyLoadedVenue(String vid) { return mFullyLoadedVenueIds.contains(vid); } } }
Java
package com.joelapenna.foursquared.location; import com.joelapenna.foursquared.FoursquaredSettings; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import java.util.Date; import java.util.List; import java.util.Observable; public class BestLocationListener extends Observable implements LocationListener { private static final String TAG = "BestLocationListener"; private static final boolean DEBUG = FoursquaredSettings.LOCATION_DEBUG; public static final long LOCATION_UPDATE_MIN_TIME = 0; public static final long LOCATION_UPDATE_MIN_DISTANCE = 0; public static final long SLOW_LOCATION_UPDATE_MIN_TIME = 1000 * 60 * 5; public static final long SLOW_LOCATION_UPDATE_MIN_DISTANCE = 50; public static final float REQUESTED_FIRST_SEARCH_ACCURACY_IN_METERS = 100.0f; public static final int REQUESTED_FIRST_SEARCH_MAX_DELTA_THRESHOLD = 1000 * 60 * 5; public static final long LOCATION_UPDATE_MAX_DELTA_THRESHOLD = 1000 * 60 * 5; private Location mLastLocation; public BestLocationListener() { super(); } @Override public void onLocationChanged(Location location) { if (DEBUG) Log.d(TAG, "onLocationChanged: " + location); updateLocation(location); } @Override public void onProviderDisabled(String provider) { // do nothing. } @Override public void onProviderEnabled(String provider) { // do nothing. } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // do nothing. } synchronized public void onBestLocationChanged(Location location) { if (DEBUG) Log.d(TAG, "onBestLocationChanged: " + location); mLastLocation = location; setChanged(); notifyObservers(location); } synchronized public Location getLastKnownLocation() { return mLastLocation; } synchronized public void clearLastKnownLocation() { mLastLocation = null; } public void updateLocation(Location location) { if (DEBUG) { Log.d(TAG, "updateLocation: Old: " + mLastLocation); Log.d(TAG, "updateLocation: New: " + location); } // Cases where we only have one or the other. if (location != null && mLastLocation == null) { if (DEBUG) Log.d(TAG, "updateLocation: Null last location"); onBestLocationChanged(location); return; } else if (location == null) { if (DEBUG) Log.d(TAG, "updated location is null, doing nothing"); return; } long now = new Date().getTime(); long locationUpdateDelta = now - location.getTime(); long lastLocationUpdateDelta = now - mLastLocation.getTime(); boolean locationIsInTimeThreshold = locationUpdateDelta <= LOCATION_UPDATE_MAX_DELTA_THRESHOLD; boolean lastLocationIsInTimeThreshold = lastLocationUpdateDelta <= LOCATION_UPDATE_MAX_DELTA_THRESHOLD; boolean locationIsMostRecent = locationUpdateDelta <= lastLocationUpdateDelta; boolean accuracyComparable = location.hasAccuracy() || mLastLocation.hasAccuracy(); boolean locationIsMostAccurate = false; if (accuracyComparable) { // If we have only one side of the accuracy, that one is more // accurate. if (location.hasAccuracy() && !mLastLocation.hasAccuracy()) { locationIsMostAccurate = true; } else if (!location.hasAccuracy() && mLastLocation.hasAccuracy()) { locationIsMostAccurate = false; } else { // If we have both accuracies, do a real comparison. locationIsMostAccurate = location.getAccuracy() <= mLastLocation.getAccuracy(); } } if (DEBUG) { Log.d(TAG, "locationIsMostRecent:\t\t\t" + locationIsMostRecent); Log.d(TAG, "locationUpdateDelta:\t\t\t" + locationUpdateDelta); Log.d(TAG, "lastLocationUpdateDelta:\t\t" + lastLocationUpdateDelta); Log.d(TAG, "locationIsInTimeThreshold:\t\t" + locationIsInTimeThreshold); Log.d(TAG, "lastLocationIsInTimeThreshold:\t" + lastLocationIsInTimeThreshold); Log.d(TAG, "accuracyComparable:\t\t\t" + accuracyComparable); Log.d(TAG, "locationIsMostAccurate:\t\t" + locationIsMostAccurate); } // Update location if its more accurate and w/in time threshold or if // the old location is // too old and this update is newer. if (accuracyComparable && locationIsMostAccurate && locationIsInTimeThreshold) { onBestLocationChanged(location); } else if (locationIsInTimeThreshold && !lastLocationIsInTimeThreshold) { onBestLocationChanged(location); } } public boolean isAccurateEnough(Location location) { if (location != null && location.hasAccuracy() && location.getAccuracy() <= REQUESTED_FIRST_SEARCH_ACCURACY_IN_METERS) { long locationUpdateDelta = new Date().getTime() - location.getTime(); if (locationUpdateDelta < REQUESTED_FIRST_SEARCH_MAX_DELTA_THRESHOLD) { if (DEBUG) Log.d(TAG, "Location is accurate: " + location.toString()); return true; } } if (DEBUG) Log.d(TAG, "Location is not accurate: " + String.valueOf(location)); return false; } public void register(LocationManager locationManager, boolean gps) { if (DEBUG) Log.d(TAG, "Registering this location listener: " + this.toString()); long updateMinTime = SLOW_LOCATION_UPDATE_MIN_TIME; long updateMinDistance = SLOW_LOCATION_UPDATE_MIN_DISTANCE; if (gps) { updateMinTime = LOCATION_UPDATE_MIN_TIME; updateMinDistance = LOCATION_UPDATE_MIN_DISTANCE; } List<String> providers = locationManager.getProviders(true); int providersCount = providers.size(); for (int i = 0; i < providersCount; i++) { String providerName = providers.get(i); if (locationManager.isProviderEnabled(providerName)) { updateLocation(locationManager.getLastKnownLocation(providerName)); } // Only register with GPS if we've explicitly allowed it. if (gps || !LocationManager.GPS_PROVIDER.equals(providerName)) { locationManager.requestLocationUpdates(providerName, updateMinTime, updateMinDistance, this); } } } public void unregister(LocationManager locationManager) { if (DEBUG) Log.d(TAG, "Unregistering this location listener: " + this.toString()); locationManager.removeUpdates(this); } /** * Updates the current location with the last known location without * registering any location listeners. * * @param locationManager the LocationManager instance from which to * retrieve the latest known location */ synchronized public void updateLastKnownLocation(LocationManager locationManager) { List<String> providers = locationManager.getProviders(true); for (int i = 0, providersCount = providers.size(); i < providersCount; i++) { String providerName = providers.get(i); if (locationManager.isProviderEnabled(providerName)) { updateLocation(locationManager.getLastKnownLocation(providerName)); } } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.location; import com.joelapenna.foursquare.Foursquare.Location; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class LocationUtils { public static final Location createFoursquareLocation(android.location.Location location) { if (location == null) { return new Location(null, null, null, null, null); } String geolat = null; if (location.getLatitude() != 0.0) { geolat = String.valueOf(location.getLatitude()); } String geolong = null; if (location.getLongitude() != 0.0) { geolong = String.valueOf(location.getLongitude()); } String geohacc = null; if (location.hasAccuracy()) { geohacc = String.valueOf(location.getAccuracy()); } String geoalt = null; if (location.hasAccuracy()) { geoalt = String.valueOf(location.hasAltitude()); } return new Location(geolat, geolong, geohacc, null, geoalt); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.StringFormatters; /** * Lets the user add a tip to a venue. * * @date September 16, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class AddTipActivity extends Activity { private static final String TAG = "AddTipActivity"; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".AddTipActivity.INTENT_EXTRA_VENUE"; public static final String EXTRA_TIP_RETURNED = Foursquared.PACKAGE_NAME + ".AddTipActivity.EXTRA_TIP_RETURNED"; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_tip_activity); StateHolder holder = (StateHolder) getLastNonConfigurationInstance(); if (holder != null) { mStateHolder = holder; mStateHolder.setActivityForTasks(this); } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE)); } else { Log.e(TAG, "AddTipActivity must be given a venue parcel as intent extras."); finish(); return; } } ensureUi(); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTasks(null); return mStateHolder; } private void ensureUi() { TextView tvVenueName = (TextView)findViewById(R.id.addTipActivityVenueName); tvVenueName.setText(mStateHolder.getVenue().getName()); TextView tvVenueAddress = (TextView)findViewById(R.id.addTipActivityVenueAddress); tvVenueAddress.setText(StringFormatters.getVenueLocationCrossStreetOrCity( mStateHolder.getVenue())); Button btn = (Button) findViewById(R.id.addTipActivityButton); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { EditText et = (EditText)findViewById(R.id.addTipActivityText); String text = et.getText().toString(); if (!TextUtils.isEmpty(text)) { mStateHolder.startTaskAddTip(AddTipActivity.this, mStateHolder.getVenue().getId(), text); } else { Toast.makeText(AddTipActivity.this, text, Toast.LENGTH_SHORT).show(); } } }); if (mStateHolder.getIsRunningTaskVenue()) { startProgressBar(); } } private void startProgressBar() { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, "", getResources().getString(R.string.add_tip_todo_activity_progress_message)); mDlgProgress.setCancelable(true); mDlgProgress.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { Log.e(TAG, "User cancelled add tip."); mStateHolder.cancelTasks(); } }); } mDlgProgress.show(); setProgressBarIndeterminateVisibility(true); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } setProgressBarIndeterminateVisibility(false); } private static class TaskAddTip extends AsyncTask<Void, Void, Tip> { private AddTipActivity mActivity; private String mVenueId; private String mTipText; private Exception mReason; public TaskAddTip(AddTipActivity activity, String venueId, String tipText) { mActivity = activity; mVenueId = venueId; mTipText = tipText; } @Override protected void onPreExecute() { mActivity.startProgressBar(); } @Override protected Tip doInBackground(Void... params) { try { // The returned tip won't have the user object or venue attached to it // as part of the response. The venue is the parent venue and the user // is the logged-in user. Foursquared foursquared = (Foursquared)mActivity.getApplication(); Tip tip = foursquared.getFoursquare().addTip( mVenueId, mTipText, "tip", LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); // So fetch the full tip for convenience. Tip tipFull = foursquared.getFoursquare().tipDetail(tip.getId()); return tipFull; } catch (Exception e) { Log.e(TAG, "Error adding tip.", e); mReason = e; } return null; } @Override protected void onPostExecute(Tip tip) { mActivity.stopProgressBar(); mActivity.mStateHolder.setIsRunningTaskAddTip(false); if (tip != null) { Intent intent = new Intent(); intent.putExtra(EXTRA_TIP_RETURNED, tip); mActivity.setResult(Activity.RESULT_OK, intent); mActivity.finish(); } else { NotificationsUtil.ToastReasonForFailure(mActivity, mReason); mActivity.setResult(Activity.RESULT_CANCELED); mActivity.finish(); } } @Override protected void onCancelled() { mActivity.stopProgressBar(); mActivity.setResult(Activity.RESULT_CANCELED); mActivity.finish(); } public void setActivity(AddTipActivity activity) { mActivity = activity; } } private static final class StateHolder { private Venue mVenue; private TaskAddTip mTaskAddTip; private boolean mIsRunningTaskAddTip; public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; } public boolean getIsRunningTaskVenue() { return mIsRunningTaskAddTip; } public void setIsRunningTaskAddTip(boolean isRunningTaskAddTip) { mIsRunningTaskAddTip = isRunningTaskAddTip; } public void startTaskAddTip(AddTipActivity activity, String venueId, String text) { mIsRunningTaskAddTip = true; mTaskAddTip = new TaskAddTip(activity, venueId, text); mTaskAddTip.execute(); } public void setActivityForTasks(AddTipActivity activity) { if (mTaskAddTip != null) { mTaskAddTip.setActivity(activity); } } public void cancelTasks() { if (mTaskAddTip != null) { mTaskAddTip.cancel(true); } } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.UserUtils; import com.joelapenna.foursquared.widget.FriendActionableListAdapter; import com.joelapenna.foursquared.widget.SegmentedButton; import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import java.util.ArrayList; import java.util.List; /** * Shows the logged-in user's followers and friends. If the user has no followers, then * they should just be shown UserDetailsFriendsActivity directly. * * @date September 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserDetailsFriendsFollowersActivity extends LoadableListActivityWithViewAndHeader { static final String TAG = "UserDetailsFriendsFollowersActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME + ".UserDetailsFriendsFollowersActivity.EXTRA_USER_NAME"; private StateHolder mStateHolder; private FriendActionableListAdapter mListAdapter; private ScrollView mLayoutEmpty; private static final int MENU_REFRESH = 0; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { if (getIntent().hasExtra(EXTRA_USER_NAME)) { mStateHolder = new StateHolder(getIntent().getStringExtra(EXTRA_USER_NAME)); mStateHolder.setFollowersOnly(true); } else { Log.e(TAG, TAG + " requires user name in intent extras."); finish(); return; } } ensureUi(); // Friend tips is shown first by default so auto-fetch it if necessary. if (!mStateHolder.getRanOnceFollowers()) { mStateHolder.startTask(this, true); } } @Override public void onPause() { super.onPause(); if (isFinishing()) { mStateHolder.cancelTasks(); mListAdapter.removeObserver(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { LayoutInflater inflater = LayoutInflater.from(this); mLayoutEmpty = (ScrollView)inflater.inflate(R.layout.user_details_friends_activity_empty, null); mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); mListAdapter = new FriendActionableListAdapter( this, mButtonRowClickHandler, ((Foursquared) getApplication()).getRemoteResourceManager()); if (mStateHolder.getFollowersOnly()) { mListAdapter.setGroup(mStateHolder.getFollowers()); if (mStateHolder.getFollowers().size() == 0) { if (mStateHolder.getRanOnceFollowers()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } else { mListAdapter.setGroup(mStateHolder.getFriends()); if (mStateHolder.getFriends().size() == 0) { if (mStateHolder.getRanOnceFriends()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } SegmentedButton buttons = getHeaderButton(); buttons.clearButtons(); buttons.addButtons( getString(R.string.user_details_friends_followers_activity_followers), getString(R.string.user_details_friends_followers_activity_friends)); if (mStateHolder.mFollowersOnly) { buttons.setPushedButtonIndex(0); } else { buttons.setPushedButtonIndex(1); } buttons.setOnClickListener(new OnClickListenerSegmentedButton() { @Override public void onClick(int index) { if (index == 0) { mStateHolder.setFollowersOnly(true); mListAdapter.setGroup(mStateHolder.getFollowers()); if (mStateHolder.getFollowers().size() < 1) { if (mStateHolder.getRanOnceFollowers()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTask(UserDetailsFriendsFollowersActivity.this, true); } } } else { mStateHolder.setFollowersOnly(false); mListAdapter.setGroup(mStateHolder.getFriends()); if (mStateHolder.getFriends().size() < 1) { if (mStateHolder.getRanOnceFriends()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTask(UserDetailsFriendsFollowersActivity.this, false); } } } mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } }); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(false); listView.setItemsCanFocus(false); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { User user = (User) parent.getAdapter().getItem(position); Intent intent = new Intent(UserDetailsFriendsFollowersActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user); startActivity(intent); } }); if (mStateHolder.getIsRunningTaskFollowers() || mStateHolder.getIsRunningTaskFriends()) { setProgressBarIndeterminateVisibility(true); } else { setProgressBarIndeterminateVisibility(false); } setTitle(getString(R.string.user_details_friends_followers_activity_title, mStateHolder.getUsername())); } private FriendActionableListAdapter.ButtonRowClickHandler mButtonRowClickHandler = new FriendActionableListAdapter.ButtonRowClickHandler() { @Override public void onBtnClickBtn1(User user) { if (mStateHolder.getFollowersOnly()) { updateFollowerStatus(user, true); } } @Override public void onBtnClickBtn2(User user) { if (mStateHolder.getFollowersOnly()) { updateFollowerStatus(user, false); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: mStateHolder.startTask(this, mStateHolder.getFollowersOnly()); return true; } return super.onOptionsItemSelected(item); } /* * Leaving this out for now as it may be very costly for users with very large * friend networks. private void prepareResultIntent() { Group<User> followers = mStateHolder.getFollowers(); Group<User> friends = mStateHolder.getFollowers(); User[] followersArr = (User[])followers.toArray(new User[followers.size()]); User[] friendsArr = (User[])friends.toArray(new User[friends.size()]); Intent intent = new Intent(); intent.putExtra(EXTRA_FOLLOWERS_RETURNED, followersArr); intent.putExtra(EXTRA_FRIENDS_RETURNED, friendsArr); setResult(CODE, intent); } */ private void updateFollowerStatus(User user, boolean approve) { mStateHolder.startTaskUpdateFollower(this, user, approve); if (mStateHolder.getFollowersOnly()) { mListAdapter.notifyDataSetChanged(); if (mStateHolder.getFollowers().size() == 0) { setEmptyView(mLayoutEmpty); } } } private void onStartTaskUsers() { if (mListAdapter != null) { if (mStateHolder.getFollowersOnly()) { mStateHolder.setIsRunningTaskFollowers(true); mListAdapter.setGroup(mStateHolder.getFollowers()); } else { mStateHolder.setIsRunningTaskFriends(true); mListAdapter.setGroup(mStateHolder.getFriends()); } mListAdapter.notifyDataSetChanged(); } setProgressBarIndeterminateVisibility(true); setLoadingView(); } private void onStartUpdateFollower() { setProgressBarIndeterminateVisibility(true); } private void onTaskUsersComplete(Group<User> group, boolean friendsOnly, Exception ex) { SegmentedButton buttons = getHeaderButton(); boolean update = false; if (group != null) { if (friendsOnly) { mStateHolder.setFollowers(group); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getFollowers()); update = true; } } else { mStateHolder.setFriends(group); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getFriends()); update = true; } } } else { if (friendsOnly) { mStateHolder.setFollowers(new Group<User>()); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getFollowers()); update = true; } } else { mStateHolder.setFriends(new Group<User>()); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getFriends()); update = true; } } NotificationsUtil.ToastReasonForFailure(this, ex); } if (friendsOnly) { mStateHolder.setIsRunningTaskFollowers(false); mStateHolder.setRanOnceFollowers(true); if (mStateHolder.getFollowers().size() == 0 && buttons.getSelectedButtonIndex() == 0) { setEmptyView(mLayoutEmpty); } } else { mStateHolder.setIsRunningTaskFriends(false); mStateHolder.setRanOnceFriends(true); if (mStateHolder.getFriends().size() == 0 && buttons.getSelectedButtonIndex() == 1) { setEmptyView(mLayoutEmpty); } } if (update) { mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } if (!mStateHolder.areAnyTasksRunning()) { setProgressBarIndeterminateVisibility(false); } } private void onTaskUpdateFollowerComplete(TaskUpdateFollower task, User user, boolean approve, Exception ex) { if (user != null) { if (UserUtils.isFriend(user)) { if (mStateHolder.addFriend(user)) { mListAdapter.notifyDataSetChanged(); } } } mStateHolder.removeTaskUpdateFollower(task); if (!mStateHolder.areAnyTasksRunning()) { setProgressBarIndeterminateVisibility(false); } } private static class TaskUsers extends AsyncTask<Void, Void, Group<User>> { private UserDetailsFriendsFollowersActivity mActivity; private boolean mFollowersOnly; private Exception mReason; public TaskUsers(UserDetailsFriendsFollowersActivity activity, boolean followersOnly) { mActivity = activity; mFollowersOnly = followersOnly; } @Override protected void onPreExecute() { mActivity.onStartTaskUsers(); } @Override protected Group<User> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); Location loc = foursquared.getLastKnownLocation(); if (mFollowersOnly) { return foursquare.friendRequests(); } else { return foursquare.friends(null, LocationUtils.createFoursquareLocation(loc)); } } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Group<User> users) { if (mActivity != null) { mActivity.onTaskUsersComplete(users, mFollowersOnly, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskUsersComplete(null, mFollowersOnly, mReason); } } public void setActivity(UserDetailsFriendsFollowersActivity activity) { mActivity = activity; } } private static class TaskUpdateFollower extends AsyncTask<Void, Void, User> { private UserDetailsFriendsFollowersActivity mActivity; private String mUserId; private boolean mApprove; private Exception mReason; private boolean mDone; public TaskUpdateFollower(UserDetailsFriendsFollowersActivity activity, String userId, boolean approve) { mActivity = activity; mUserId = userId; mApprove = approve; mDone = false; } @Override protected void onPreExecute() { mActivity.onStartUpdateFollower(); } @Override protected User doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); if (mApprove) { return foursquare.friendApprove(mUserId); } else { return foursquare.friendDeny(mUserId); } } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (mActivity != null) { mActivity.onTaskUpdateFollowerComplete(this, user, mApprove, mReason); } mDone = true; } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskUpdateFollowerComplete(this, null, mApprove, mReason); } mDone = true; } public void setActivity(UserDetailsFriendsFollowersActivity activity) { mActivity = activity; } public boolean getIsDone() { return mDone; } } private static class StateHolder { private String mUsername; private Group<User> mFollowers; private Group<User> mFriends; private TaskUsers mTaskFollowers; private TaskUsers mTaskFriends; private boolean mIsRunningTaskFollowers; private boolean mIsRunningTaskFriends; private boolean mFollowersOnly; private boolean mRanOnceFollowers; private boolean mRanOnceFriends; private List<TaskUpdateFollower> mTasksUpdateFollowers; public StateHolder(String username) { mUsername = username; mIsRunningTaskFollowers = false; mIsRunningTaskFriends = false; mRanOnceFriends = false; mRanOnceFollowers = false; mFollowers = new Group<User>(); mFriends = new Group<User>(); mFollowersOnly = true; mTasksUpdateFollowers = new ArrayList<TaskUpdateFollower>(); } public String getUsername() { return mUsername; } public Group<User> getFollowers() { return mFollowers; } public void setFollowers(Group<User> followers) { mFollowers = followers; } public Group<User> getFriends() { return mFriends; } public void setFriends(Group<User> friends) { mFriends = friends; } public void startTask(UserDetailsFriendsFollowersActivity activity, boolean followersOnly) { if (followersOnly) { if (mIsRunningTaskFollowers) { return; } mIsRunningTaskFollowers = true; mTaskFollowers = new TaskUsers(activity, followersOnly); mTaskFollowers.execute(); } else { if (mIsRunningTaskFriends) { return; } mIsRunningTaskFriends = true; mTaskFriends = new TaskUsers(activity, followersOnly); mTaskFriends.execute(); } } public void startTaskUpdateFollower(UserDetailsFriendsFollowersActivity activity, User user, boolean approve) { for (User it : mFollowers) { if (it.getId().equals(user.getId())) { mFollowers.remove(it); break; } } TaskUpdateFollower task = new TaskUpdateFollower(activity, user.getId(), approve); task.execute(); mTasksUpdateFollowers.add(task); } public void setActivity(UserDetailsFriendsFollowersActivity activity) { if (mTaskFollowers != null) { mTaskFollowers.setActivity(activity); } if (mTaskFriends != null) { mTaskFriends.setActivity(activity); } for (TaskUpdateFollower it : mTasksUpdateFollowers) { it.setActivity(activity); } } public boolean getIsRunningTaskFollowers() { return mIsRunningTaskFollowers; } public void setIsRunningTaskFollowers(boolean isRunning) { mIsRunningTaskFollowers = isRunning; } public boolean getIsRunningTaskFriends() { return mIsRunningTaskFriends; } public void setIsRunningTaskFriends(boolean isRunning) { mIsRunningTaskFriends = isRunning; } public void cancelTasks() { if (mTaskFollowers != null) { mTaskFollowers.setActivity(null); mTaskFollowers.cancel(true); } if (mTaskFriends != null) { mTaskFriends.setActivity(null); mTaskFriends.cancel(true); } for (TaskUpdateFollower it : mTasksUpdateFollowers) { it.setActivity(null); it.cancel(true); } } public boolean getFollowersOnly() { return mFollowersOnly; } public void setFollowersOnly(boolean followersOnly) { mFollowersOnly = followersOnly; } public boolean getRanOnceFollowers() { return mRanOnceFollowers; } public void setRanOnceFollowers(boolean ranOnce) { mRanOnceFollowers = ranOnce; } public boolean getRanOnceFriends() { return mRanOnceFriends; } public void setRanOnceFriends(boolean ranOnce) { mRanOnceFriends = ranOnce; } public boolean areAnyTasksRunning() { return mIsRunningTaskFollowers || mIsRunningTaskFriends || mTasksUpdateFollowers.size() > 0; } public boolean addFriend(User user) { for (User it : mFriends) { if (it.getId().equals(user.getId())) { return false; } } mFriends.add(user); return true; } public void removeTaskUpdateFollower(TaskUpdateFollower task) { mTasksUpdateFollowers.remove(task); // Try to cleanup anyone we missed, this could happen for a brief period // during rotation. for (int i = mTasksUpdateFollowers.size()-1; i > -1; i--) { if (mTasksUpdateFollowers.get(i).getIsDone()) { mTasksUpdateFollowers.remove(i); } } } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay; import com.joelapenna.foursquared.maps.VenueItemizedOverlay; import com.joelapenna.foursquared.util.UiUtil; import android.os.Bundle; import android.util.Log; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueMapActivity extends MapActivity { public static final String TAG = "VenueMapActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".VenueMapActivity.INTENT_EXTRA_VENUE"; private MapView mMapView; private MapController mMapController; private VenueItemizedOverlay mOverlay = null; private MyLocationOverlay mMyLocationOverlay = null; private StateHolder mStateHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.venue_map_activity); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE)); } else { Log.e(TAG, "VenueMapActivity requires a venue parcel its intent extras."); finish(); return; } } ensureUi(); } private void ensureUi() { /* Button mapsButton = (Button) findViewById(R.id.mapsButton); mapsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse( // "geo:0,0?q=" + mStateHolder.getVenue().getName() + " near " + mStateHolder.getVenue().getCity())); startActivity(intent); } }); if (FoursquaredSettings.SHOW_VENUE_MAP_BUTTON_MORE == false) { mapsButton.setVisibility(View.GONE); } */ setTitle(getString(R.string.venue_map_activity_title, mStateHolder.getVenue().getName())); mMapView = (MapView) findViewById(R.id.mapView); mMapView.setBuiltInZoomControls(true); mMapController = mMapView.getController(); mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mMyLocationOverlay); mOverlay = new VenueItemizedOverlay(this.getResources().getDrawable( R.drawable.map_marker_blue)); if (VenueUtils.hasValidLocation(mStateHolder.getVenue())) { Group<Venue> venueGroup = new Group<Venue>(); venueGroup.setType("Current Venue"); venueGroup.add(mStateHolder.getVenue()); mOverlay.setGroup(venueGroup); mMapView.getOverlays().add(mOverlay); } updateMap(); } @Override public void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); if (UiUtil.sdkVersion() > 3) { mMyLocationOverlay.enableCompass(); } } @Override public void onPause() { super.onPause(); mMyLocationOverlay.disableMyLocation(); mMyLocationOverlay.disableCompass(); } @Override protected boolean isRouteDisplayed() { return false; } private void updateMap() { if (mOverlay != null && mOverlay.size() > 0) { GeoPoint center = mOverlay.getCenter(); mMapController.animateTo(center); mMapController.setZoom(17); } } private static class StateHolder { private Venue mVenue; public StateHolder() { } public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import android.app.Activity; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.UriMatcher; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import java.net.URLDecoder; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class BrowsableActivity extends Activity { private static final String TAG = "BrowsableActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int URI_PATH_CHECKIN = 1; private static final int URI_PATH_CHECKINS = 2; private static final int URI_PATH_SEARCH = 3; private static final int URI_PATH_SHOUT = 4; private static final int URI_PATH_USER = 5; private static final int URI_PATH_VENUE = 6; public static String PARAM_SHOUT_TEXT = "shout"; public static String PARAM_SEARCH_QUERY = "q"; public static String PARAM_SEARCH_IMMEDIATE= "immediate"; public static String PARAM_USER_ID= "uid"; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI("m.foursquare.com", "checkin", URI_PATH_CHECKIN); sUriMatcher.addURI("m.foursquare.com", "checkins", URI_PATH_CHECKINS); sUriMatcher.addURI("m.foursquare.com", "search", URI_PATH_SEARCH); sUriMatcher.addURI("m.foursquare.com", "shout", URI_PATH_SHOUT); sUriMatcher.addURI("m.foursquare.com", "user", URI_PATH_USER); sUriMatcher.addURI("m.foursquare.com", "venue/#", URI_PATH_VENUE); } private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Uri uri = getIntent().getData(); if (DEBUG) Log.d(TAG, "Intent Data: " + uri); Intent intent; switch (sUriMatcher.match(uri)) { case URI_PATH_CHECKIN: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_CHECKIN"); intent = new Intent(this, VenueActivity.class); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, uri.getQueryParameter("vid")); startActivity(intent); break; case URI_PATH_CHECKINS: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_CHECKINS"); intent = new Intent(this, FriendsActivity.class); startActivity(intent); break; case URI_PATH_SEARCH: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_SEARCH"); intent = new Intent(this, SearchVenuesActivity.class); if (!TextUtils.isEmpty(uri.getQueryParameter(PARAM_SEARCH_QUERY))) { intent.putExtra(SearchManager.QUERY, URLDecoder.decode(uri.getQueryParameter(PARAM_SEARCH_QUERY))); if (uri.getQueryParameter(PARAM_SEARCH_IMMEDIATE) != null && uri.getQueryParameter(PARAM_SEARCH_IMMEDIATE).equals("1")) { intent.setAction(Intent.ACTION_SEARCH); // interpret action as search immediately. } else { intent.setAction(Intent.ACTION_VIEW); // interpret as prepopulate search field only. } } startActivity(intent); break; case URI_PATH_SHOUT: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_SHOUT"); intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_SHOUT, true); if (!TextUtils.isEmpty(uri.getQueryParameter(PARAM_SHOUT_TEXT))) { intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_TEXT_PREPOPULATE, URLDecoder.decode(uri.getQueryParameter(PARAM_SHOUT_TEXT))); } startActivity(intent); break; case URI_PATH_USER: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_USER"); intent = new Intent(this, UserDetailsActivity.class); if (!TextUtils.isEmpty(uri.getQueryParameter(PARAM_USER_ID))) { intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, uri.getQueryParameter(PARAM_USER_ID)); } startActivity(intent); break; case URI_PATH_VENUE: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_VENUE"); intent = new Intent(this, VenueActivity.class); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, uri.getLastPathSegment()); startActivity(intent); break; default: if (DEBUG) Log.d(TAG, "Matched: None"); } finish(); } }
Java
/** * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 CommonsWare, LLC */ package com.joelapenna.foursquared.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * This is based off the chapter 13 sample in Advanced Android Development, by Mark Murphy. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class OnBootReceiver extends BroadcastReceiver { public static final String TAG = "OnBootReceiver"; @Override public void onReceive(Context context, Intent intent) { // If the user has notifications on, set an alarm every N minutes, where N is their // requested refresh rate. PingsService.setupPings(context); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquared.R; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.LinearLayout; /** * This is pretty much a direct copy of LoadableListActivity. It just gives the caller * a chance to set their own view for the empty state. This is used by FriendsActivity * to show a button like 'Find some friends!' when the list is empty (in the case that * they are a new user and have no friends initially). * * By default, loadable_list_activity_with_view is used as the intial empty view with * a progress bar and textview description. The owner can then call setEmptyView() * with their own view to show if there are no results. * * @date April 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class LoadableListActivityWithView extends ListActivity { private LinearLayout mLayoutHeader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.loadable_list_activity_with_view); mLayoutHeader = (LinearLayout)findViewById(R.id.header); getListView().setDividerHeight(0); } public void setEmptyView(View view) { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); parent.getChildAt(0).setVisibility(View.GONE); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.addView(view); } public void setLoadingView() { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.getChildAt(0).setVisibility(View.VISIBLE); } public int getNoSearchResultsStringId() { return R.string.no_search_results; } public LinearLayout getHeaderLayout() { return mLayoutHeader; } }
Java
/** * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 CommonsWare, LLC */ package com.joelapenna.foursquared.app; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.os.PowerManager; /** * This is based off the chapter 13 sample in Advanced Android Development, by Mark Murphy. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public abstract class WakefulIntentService extends IntentService { public static final String TAG = "WakefulIntentService"; public static final String LOCK_NAME_STATIC = "com.joelapenna.foursquared.app.WakefulintentService.Static"; private static PowerManager.WakeLock lockStatic = null; abstract void doWakefulWork(Intent intent); public static void acquireStaticLock(Context context) { getLock(context).acquire(); } private synchronized static PowerManager.WakeLock getLock(Context context) { if (lockStatic == null) { PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE); lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME_STATIC); lockStatic.setReferenceCounted(true); } return(lockStatic); } public WakefulIntentService(String name) { super(name); } @Override final protected void onHandleIntent(Intent intent) { doWakefulWork(intent); getLock(this).release(); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.appwidget.FriendsAppWidgetProvider; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.Comparators; import android.app.IntentService; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import java.util.Collections; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquaredService extends IntentService { private static final String TAG = "FoursquaredService"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public FoursquaredService() { super("FoursquaredService"); } /** * Handles various intents, appwidget state changes for starters. * * {@inheritDoc} */ @Override public void onHandleIntent(Intent intent) { if (DEBUG) Log.d(TAG, "onHandleIntent: " + intent.toString()); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(intent.getAction())) { updateWidgets(); } } private void updateWidgets() { if (DEBUG) Log.d(TAG, "updateWidgets"); Group<Checkin> checkins = null; Foursquared foursquared = ((Foursquared) getApplication()); if (foursquared.isReady()) { if (DEBUG) Log.d(TAG, "User settings are ready, starting normal widget update."); try { checkins = foursquared.getFoursquare().checkins( LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); } catch (Exception e) { if (DEBUG) Log.d(TAG, "Exception: Skipping widget update.", e); return; } Collections.sort(checkins, Comparators.getCheckinRecencyComparator()); // Request the user photos for the checkins... At the moment, this // is async. It is likely this means that the first update of the widget will never // show user photos as the photos will still be downloading when the getInputStream // call is made in SpecialDealsAppWidgetProvider. for (int i = 0; i < checkins.size(); i++) { Uri photoUri = Uri.parse((checkins.get(i)).getUser().getPhoto()); if (!foursquared.getRemoteResourceManager().exists(photoUri)) { foursquared.getRemoteResourceManager().request(photoUri); } } } AppWidgetManager am = AppWidgetManager.getInstance(this); int[] appWidgetIds = am.getAppWidgetIds(new ComponentName(this, FriendsAppWidgetProvider.class)); for (int i = 0; i < appWidgetIds.length; i++) { FriendsAppWidgetProvider.updateAppWidget((Context) this, foursquared .getRemoteResourceManager(), am, appWidgetIds[i], checkins); } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FriendsActivity; import com.joelapenna.foursquared.MainActivity; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.StringFormatters; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.widget.RemoteViews; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This service will run every N minutes (specified by the user in settings). An alarm * handles running the service. * * When the service runs, we call /checkins. From the list of checkins, we cut down the * list of relevant checkins as follows: * <ul> * <li>Not one of our own checkins.</li> * <li>We haven't turned pings off for the user. This can be toggled on/off in the * UserDetailsActivity activity, per user.</li> * <li>The checkin is younger than the last time we ran this service.</li> * </ul> * * Note that the server might override the pings attribute to 'off' for certain checkins, * usually if the checkin is far away from our current location. * * Pings will not be cleared from the notification bar until a subsequent run can * generate at least one new ping. A new batch of pings will clear all * previous pings so as to not clutter the notification bar. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsService extends WakefulIntentService { public static final String TAG = "PingsService"; private static final boolean DEBUG = false; public static final int NOTIFICATION_ID_CHECKINS = 15; public PingsService() { super("PingsService"); } @Override public void onCreate() { super.onCreate(); } @Override protected void doWakefulWork(Intent intent) { Log.i(TAG, "Foursquare pings service running..."); // The user must have logged in once previously for this to work, // and not leave the app in a logged-out state. Foursquared foursquared = (Foursquared) getApplication(); Foursquare foursquare = foursquared.getFoursquare(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (!foursquared.isReady()) { Log.i(TAG, "User not logged in, cannot proceed."); return; } // Before running, make sure the user still wants pings on. // For example, the user could have turned pings on from // this device, but then turned it off on a second device. This // service would continue running then, continuing to notify the // user. if (!checkUserStillWantsPings(foursquared.getUserId(), foursquare)) { // Turn off locally. Log.i(TAG, "Pings have been turned off for user, cancelling service."); prefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit(); cancelPings(this); return; } // Get the users current location and then request nearby checkins. Group<Checkin> checkins = null; Location location = getLastGeolocation(); if (location != null) { try { checkins = foursquare.checkins( LocationUtils.createFoursquareLocation(location)); } catch (Exception ex) { Log.e(TAG, "Error getting checkins in pings service.", ex); } } else { Log.e(TAG, "Could not find location in pings service, cannot proceed."); } if (checkins != null) { Log.i(TAG, "Checking " + checkins.size() + " checkins for pings."); // Don't accept any checkins that are older than the last time we ran. long lastRunTime = prefs.getLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()); Date dateLast = new Date(lastRunTime); Log.i(TAG, "Last service run time: " + dateLast.toLocaleString() + " (" + lastRunTime + ")."); // Now build the list of 'new' checkins. List<Checkin> newCheckins = new ArrayList<Checkin>(); for (Checkin it : checkins) { if (DEBUG) Log.d(TAG, "Checking checkin of " + it.getUser().getFirstname()); // Ignore ourselves. The server should handle this by setting the pings flag off but.. if (it.getUser() != null && it.getUser().getId().equals(foursquared.getUserId())) { if (DEBUG) Log.d(TAG, " Ignoring checkin of ourselves."); continue; } // Check that our user wanted to see pings from this user. if (!it.getPing()) { if (DEBUG) Log.d(TAG, " Pings are off for this user."); continue; } // If it's an 'off the grid' checkin, ignore. if (it.getVenue() == null && it.getShout() == null) { if (DEBUG) Log.d(TAG, " Checkin is off the grid, ignoring."); continue; } // Check against date times. try { Date dateCheckin = StringFormatters.DATE_FORMAT.parse(it.getCreated()); if (DEBUG) { Log.d(TAG, " Comaring date times for checkin."); Log.d(TAG, " Last run time: " + dateLast.toLocaleString()); Log.d(TAG, " Checkin time: " + dateCheckin.toLocaleString()); } if (dateCheckin.after(dateLast)) { if (DEBUG) Log.d(TAG, " Checkin is younger than our last run time, passes all tests!!"); newCheckins.add(it); } else { if (DEBUG) Log.d(TAG, " Checkin is older than last run time."); } } catch (ParseException ex) { if (DEBUG) Log.e(TAG, " Error parsing checkin timestamp: " + it.getCreated(), ex); } } Log.i(TAG, "Found " + newCheckins.size() + " new checkins."); notifyUser(newCheckins); } else { // Checkins were null, so don't record this as the last run time in order to try // fetching checkins we may have missed on the next run. // Thanks to logan.johnson@gmail.com for the fix. Log.i(TAG, "Checkins were null, won't update last run timestamp."); return; } // Record this as the last time we ran. prefs.edit().putLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()).commit(); } private Location getLastGeolocation() { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); List<String> providers = manager.getAllProviders(); Location bestLocation = null; for (String it : providers) { Location location = manager.getLastKnownLocation(it); if (location != null) { if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { bestLocation = location; } } } return bestLocation; } private void notifyUser(List<Checkin> newCheckins) { // If we have no new checkins to show, nothing to do. We would also be leaving the // previous batch of pings alive (if any) which is ok. if (newCheckins.size() < 1) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // Clear all previous pings notifications before showing new ones. NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); mgr.cancelAll(); // We'll only ever show a single entry, so we collapse data depending on how many // new checkins we received on this refresh. RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.pings_list_item); if (newCheckins.size() == 1) { // A single checkin, show full checkin preview. Checkin checkin = newCheckins.get(0); String checkinMsgLine1 = StringFormatters.getCheckinMessageLine1(checkin, true); String checkinMsgLine2 = StringFormatters.getCheckinMessageLine2(checkin); String checkinMsgLine3 = StringFormatters.getCheckinMessageLine3(checkin); contentView.setTextViewText(R.id.text1, checkinMsgLine1); if (!TextUtils.isEmpty(checkinMsgLine2)) { contentView.setTextViewText(R.id.text2, checkinMsgLine2); contentView.setTextViewText(R.id.text3, checkinMsgLine3); } else { contentView.setTextViewText(R.id.text2, checkinMsgLine3); } } else { // More than one new checkin, collapse them. String checkinMsgLine1 = newCheckins.size() + " new Foursquare checkins!"; StringBuilder sbCheckinMsgLine2 = new StringBuilder(1024); for (Checkin it : newCheckins) { sbCheckinMsgLine2.append(StringFormatters.getUserAbbreviatedName(it.getUser())); sbCheckinMsgLine2.append(", "); } if (sbCheckinMsgLine2.length() > 0) { sbCheckinMsgLine2.delete(sbCheckinMsgLine2.length()-2, sbCheckinMsgLine2.length()); } String checkinMsgLine3 = "at " + StringFormatters.DATE_FORMAT_TODAY.format(new Date()); contentView.setTextViewText(R.id.text1, checkinMsgLine1); contentView.setTextViewText(R.id.text2, sbCheckinMsgLine2.toString()); contentView.setTextViewText(R.id.text3, checkinMsgLine3); } PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, FriendsActivity.class), 0); Notification notification = new Notification( R.drawable.notification_icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.flags |= Notification.FLAG_AUTO_CANCEL; if (prefs.getBoolean(Preferences.PREFERENCE_PINGS_VIBRATE, false)) { notification.defaults |= Notification.DEFAULT_VIBRATE; } if (newCheckins.size() > 1) { notification.number = newCheckins.size(); } mgr.notify(NOTIFICATION_ID_CHECKINS, notification); } private boolean checkUserStillWantsPings(String userId, Foursquare foursquare) { try { User user = foursquare.user(userId, false, false, false, null); if (user != null) { return user.getSettings().getPings().equals("on"); } } catch (Exception ex) { // Assume they still want it on. } return true; } public static void setupPings(Context context) { // If the user has pings on, set an alarm every N minutes, where N is their // requested refresh rate. We default to 30 if some problem reading set interval. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean(Preferences.PREFERENCE_PINGS, false)) { int refreshRateInMinutes = getRefreshIntervalInMinutes(prefs); if (DEBUG) { Log.d(TAG, "User has pings on, attempting to setup alarm with interval: " + refreshRateInMinutes + ".."); } // We want to mark this as the last run time so we don't get any notifications // before the service is started. prefs.edit().putLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()).commit(); // Schedule the alarm. AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + (refreshRateInMinutes * 60 * 1000), refreshRateInMinutes * 60 * 1000, makePendingIntentAlarm(context)); } } public static void cancelPings(Context context) { AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.cancel(makePendingIntentAlarm(context)); } private static PendingIntent makePendingIntentAlarm(Context context) { return PendingIntent.getBroadcast(context, 0, new Intent(context, PingsOnAlarmReceiver.class), 0); } public static void clearAllNotifications(Context context) { NotificationManager mgr = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); mgr.cancelAll(); } public static void generatePingsTest(Context context) { Intent intent = new Intent(context, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); NotificationManager mgr = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.pings_list_item); contentView.setTextViewText(R.id.text1, "Ping title line"); contentView.setTextViewText(R.id.text2, "Ping message line 2"); contentView.setTextViewText(R.id.text3, "Ping message line 3"); Notification notification = new Notification( R.drawable.notification_icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.defaults |= Notification.DEFAULT_VIBRATE; mgr.notify(-1, notification); } private static int getRefreshIntervalInMinutes(SharedPreferences prefs) { int refreshRateInMinutes = 30; try { refreshRateInMinutes = Integer.parseInt(prefs.getString( Preferences.PREFERENCE_PINGS_INTERVAL, String.valueOf(refreshRateInMinutes))); } catch (NumberFormatException ex) { Log.e(TAG, "Error parsing pings interval time, defaulting to: " + refreshRateInMinutes); } return refreshRateInMinutes; } }
Java
/** * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 CommonsWare, LLC */ package com.joelapenna.foursquared.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * This is based off the chapter 13 sample in Advanced Android Development, by Mark Murphy. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsOnAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { WakefulIntentService.acquireStaticLock(context); context.startService(new Intent(context, PingsService.class)); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquared.R; import android.app.ListActivity; import android.os.Bundle; import android.view.ViewGroup; import android.view.Window; import android.widget.ProgressBar; import android.widget.TextView; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class LoadableListActivity extends ListActivity { private int mNoSearchResultsString = getNoSearchResultsStringId(); private ProgressBar mEmptyProgress; private TextView mEmptyText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.loadable_list_activity); mEmptyProgress = (ProgressBar)findViewById(R.id.emptyProgress); mEmptyText = (TextView)findViewById(R.id.emptyText); setLoadingView(); getListView().setDividerHeight(0); } public void setEmptyView() { mEmptyProgress.setVisibility(ViewGroup.GONE); mEmptyText.setText(mNoSearchResultsString); } public void setLoadingView() { mEmptyProgress.setVisibility(ViewGroup.VISIBLE); mEmptyText.setText("");//R.string.loading); } public void setLoadingView(String loadingText) { setLoadingView(); mEmptyText.setText(loadingText); } public int getNoSearchResultsStringId() { return R.string.no_search_results; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.widget.SegmentedButton; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.LinearLayout; /** * This is pretty much a direct copy of LoadableListActivity. It just gives the caller * a chance to set their own view for the empty state. This is used by FriendsActivity * to show a button like 'Find some friends!' when the list is empty (in the case that * they are a new user and have no friends initially). * * By default, loadable_list_activity_with_view is used as the intial empty view with * a progress bar and textview description. The owner can then call setEmptyView() * with their own view to show if there are no results. * * @date April 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class LoadableListActivityWithViewAndHeader extends ListActivity { private LinearLayout mLayoutHeader; private SegmentedButton mHeaderButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.loadable_list_activity_with_view_and_header); mLayoutHeader = (LinearLayout)findViewById(R.id.header); mHeaderButton = (SegmentedButton)findViewById(R.id.segmented); getListView().setDividerHeight(0); } public void setEmptyView(View view) { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); parent.getChildAt(0).setVisibility(View.GONE); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.addView(view); } public void setLoadingView() { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.getChildAt(0).setVisibility(View.VISIBLE); } public int getNoSearchResultsStringId() { return R.string.no_search_results; } public LinearLayout getHeaderLayout() { return mLayoutHeader; } public SegmentedButton getHeaderButton() { return mHeaderButton; } }
Java
package com.joelapenna.foursquared; import com.joelapenna.foursquared.providers.GlobalSearchProvider; import android.app.Activity; import android.app.SearchManager; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; /** * Activity that gets intents from the Quick Search Box and starts the correct * Activity depending on the type of the data. * * @author Tauno Talimaa (tauntz@gmail.com) */ public class GlobalSearchActivity extends Activity { private static final String TAG = GlobalSearchProvider.class.getSimpleName(); private static final boolean DEBUG = FoursquaredSettings.DEBUG; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); handleIntent(intent); } private void handleIntent(Intent intent) { String dataString = intent.getDataString(); if (!TextUtils.isEmpty(dataString)) { Uri uri = Uri.parse(intent.getDataString()); String directory = uri.getPathSegments().get(0); if (directory.equals(GlobalSearchProvider.VENUE_DIRECTORY)) { if (DEBUG) { Log.d(TAG, "Viewing venue details for venue id:" + uri.getLastPathSegment()); } Intent i = new Intent(this, VenueActivity.class); i.setAction(Intent.ACTION_VIEW); i.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, uri.getLastPathSegment()); startActivity(i); finish(); } else if (directory.equals(GlobalSearchProvider.FRIEND_DIRECTORY)) { if (DEBUG) { Log.d(TAG, "Viewing friend details for friend id:" + uri.getLastPathSegment()); // TODO: Implement } } } else { // For now just launch search activity and assume a venue search. Intent intentSearch = new Intent(this, SearchVenuesActivity.class); intentSearch.setAction(Intent.ACTION_SEARCH); if (intent.hasExtra(SearchManager.QUERY)) { intentSearch.putExtra(SearchManager.QUERY, intent.getStringExtra(SearchManager.QUERY)); } startActivity(intentSearch); finish(); } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.CheckinTimestampSort; import com.joelapenna.foursquared.util.Comparators; import com.joelapenna.foursquared.util.MenuUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.widget.CheckinListAdapter; import com.joelapenna.foursquared.widget.SegmentedButton; import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import java.io.IOException; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -Added dummy location observer, new menu icon logic, * links to new user activity (3/10/2010). * -Sorting checkins by distance/time. (3/18/2010). * -Added option to sort by server response, or by distance. (6/10/2010). * -Reformatted/refactored. (9/22/2010). */ public class FriendsActivity extends LoadableListActivityWithViewAndHeader { static final String TAG = "FriendsActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final int CITY_RADIUS_IN_METERS = 20 * 1000; // 20km private static final long SLEEP_TIME_IF_NO_LOCATION = 3000L; private static final int MENU_GROUP_SEARCH = 0; private static final int MENU_REFRESH = 1; private static final int MENU_SHOUT = 2; private static final int MENU_MORE = 3; private static final int MENU_MORE_MAP = 20; private static final int MENU_MORE_LEADERBOARD = 21; private static final int SORT_METHOD_RECENT = 0; private static final int SORT_METHOD_NEARBY = 1; private StateHolder mStateHolder; private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver(); private LinkedHashMap<Integer, String> mMenuMoreSubitems; private SeparatedListAdapter mListAdapter; private ViewGroup mLayoutEmpty; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); if (getLastNonConfigurationInstance() != null) { mStateHolder = (StateHolder) getLastNonConfigurationInstance(); mStateHolder.setActivity(this); } else { mStateHolder = new StateHolder(); mStateHolder.setSortMethod(SORT_METHOD_RECENT); } ensureUi(); Foursquared foursquared = (Foursquared)getApplication(); if (foursquared.isReady()) { if (!mStateHolder.getRanOnce()) { mStateHolder.startTask(this); } } } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver); } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver); if (isFinishing()) { mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); mStateHolder.cancel(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(MENU_GROUP_SEARCH, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); menu.add(Menu.NONE, MENU_SHOUT, Menu.NONE, R.string.shout_action_label) .setIcon(R.drawable.ic_menu_shout); SubMenu menuMore = menu.addSubMenu(Menu.NONE, MENU_MORE, Menu.NONE, "More"); menuMore.setIcon(android.R.drawable.ic_menu_more); for (Map.Entry<Integer, String> it : mMenuMoreSubitems.entrySet()) { menuMore.add(it.getValue()); } MenuUtils.addPreferencesToMenu(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: mStateHolder.startTask(this); return true; case MENU_SHOUT: Intent intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_SHOUT, true); startActivity(intent); return true; case MENU_MORE: // Submenu items generate id zero, but we check on item title below. return true; default: if (item.getTitle().equals("Map")) { Checkin[] checkins = (Checkin[])mStateHolder.getCheckins().toArray( new Checkin[mStateHolder.getCheckins().size()]); Intent intentMap = new Intent(FriendsActivity.this, FriendsMapActivity.class); intentMap.putExtra(FriendsMapActivity.EXTRA_CHECKIN_PARCELS, checkins); startActivity(intentMap); return true; } else if (item.getTitle().equals(mMenuMoreSubitems.get(MENU_MORE_LEADERBOARD))) { startActivity(new Intent(FriendsActivity.this, StatsActivity.class)); return true; } break; } return super.onOptionsItemSelected(item); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } @Override public int getNoSearchResultsStringId() { return R.string.no_friend_checkins; } private void ensureUi() { SegmentedButton buttons = getHeaderButton(); buttons.clearButtons(); buttons.addButtons( getString(R.string.friendsactivity_btn_recent), getString(R.string.friendsactivity_btn_nearby)); if (mStateHolder.getSortMethod() == SORT_METHOD_RECENT) { buttons.setPushedButtonIndex(0); } else { buttons.setPushedButtonIndex(1); } buttons.setOnClickListener(new OnClickListenerSegmentedButton() { @Override public void onClick(int index) { if (index == 0) { mStateHolder.setSortMethod(SORT_METHOD_RECENT); } else { mStateHolder.setSortMethod(SORT_METHOD_NEARBY); } ensureUiListView(); } }); mMenuMoreSubitems = new LinkedHashMap<Integer, String>(); mMenuMoreSubitems.put(MENU_MORE_MAP, getResources().getString( R.string.friendsactivity_menu_map)); mMenuMoreSubitems.put(MENU_MORE_LEADERBOARD, getResources().getString( R.string.friendsactivity_menu_leaderboard)); ensureUiListView(); } private void ensureUiListView() { mListAdapter = new SeparatedListAdapter(this); if (mStateHolder.getSortMethod() == SORT_METHOD_RECENT) { sortCheckinsRecent(mStateHolder.getCheckins(), mListAdapter); } else { sortCheckinsDistance(mStateHolder.getCheckins(), mListAdapter); } ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setDividerHeight(0); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Checkin checkin = (Checkin) parent.getAdapter().getItem(position); if (checkin.getUser() != null) { Intent intent = new Intent(FriendsActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, checkin.getUser()); intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true); startActivity(intent); } } }); // Prepare our no-results view. Something odd is going on with the layout parameters though. // If we don't explicitly set the layout to be fill/fill after inflating, the layout jumps // to a wrap/wrap layout. Furthermore, sdk 3 crashes with the original layout using two // buttons in a horizontal LinearLayout. LayoutInflater inflater = LayoutInflater.from(this); if (UiUtil.sdkVersion() > 3) { mLayoutEmpty = (ScrollView)inflater.inflate( R.layout.friends_activity_empty, null); Button btnAddFriends = (Button)mLayoutEmpty.findViewById( R.id.friendsActivityEmptyBtnAddFriends); btnAddFriends.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FriendsActivity.this, AddFriendsActivity.class); startActivity(intent); } }); Button btnFriendRequests = (Button)mLayoutEmpty.findViewById( R.id.friendsActivityEmptyBtnFriendRequests); btnFriendRequests.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FriendsActivity.this, FriendRequestsActivity.class); startActivity(intent); } }); } else { // Inflation on 1.5 is causing a lot of issues, dropping full layout. mLayoutEmpty = (ScrollView)inflater.inflate( R.layout.friends_activity_empty_sdk3, null); } mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); if (mListAdapter.getCount() == 0) { setEmptyView(mLayoutEmpty); } if (mStateHolder.getIsRunningTask()) { setProgressBarIndeterminateVisibility(true); if (!mStateHolder.getRanOnce()) { setLoadingView(); } } else { setProgressBarIndeterminateVisibility(false); } } private void sortCheckinsRecent(Group<Checkin> checkins, SeparatedListAdapter listAdapter) { // Sort all by timestamp first. Collections.sort(checkins, Comparators.getCheckinRecencyComparator()); // We'll group in different section adapters based on some time thresholds. Group<Checkin> recent = new Group<Checkin>(); Group<Checkin> today = new Group<Checkin>(); Group<Checkin> yesterday = new Group<Checkin>(); Group<Checkin> older = new Group<Checkin>(); Group<Checkin> other = new Group<Checkin>(); CheckinTimestampSort timestamps = new CheckinTimestampSort(); for (Checkin it : checkins) { // If we can't parse the distance value, it's possible that we // did not have a geolocation for the device at the time the // search was run. In this case just assume this friend is nearby // to sort them in the time buckets. int meters = 0; try { meters = Integer.parseInt(it.getDistance()); } catch (NumberFormatException ex) { if (DEBUG) Log.d(TAG, "Couldn't parse distance for checkin during friend search."); meters = 0; } if (meters > CITY_RADIUS_IN_METERS) { other.add(it); } else { try { Date date = new Date(it.getCreated()); if (date.after(timestamps.getBoundaryRecent())) { recent.add(it); } else if (date.after(timestamps.getBoundaryToday())) { today.add(it); } else if (date.after(timestamps.getBoundaryYesterday())) { yesterday.add(it); } else { older.add(it); } } catch (Exception ex) { older.add(it); } } } if (recent.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(recent); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_recent), adapter); } if (today.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(today); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_today), adapter); } if (yesterday.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(yesterday); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_yesterday), adapter); } if (older.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(older); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_older), adapter); } if (other.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(other); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_other_city), adapter); } } private void sortCheckinsDistance(Group<Checkin> checkins, SeparatedListAdapter listAdapter) { Collections.sort(checkins, Comparators.getCheckinDistanceComparator()); Group<Checkin> nearby = new Group<Checkin>(); CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); for (Checkin it : checkins) { int meters = 0; try { meters = Integer.parseInt(it.getDistance()); } catch (NumberFormatException ex) { if (DEBUG) Log.d(TAG, "Couldn't parse distance for checkin during friend search."); meters = 0; } if (meters < CITY_RADIUS_IN_METERS) { nearby.add(it); } } if (nearby.size() > 0) { adapter.setGroup(nearby); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_distance), adapter); } } private void onTaskStart() { setProgressBarIndeterminateVisibility(true); setLoadingView(); } private void onTaskComplete(Group<Checkin> checkins, Exception ex) { mStateHolder.setRanOnce(true); mStateHolder.setIsRunningTask(false); setProgressBarIndeterminateVisibility(false); // Clear list for new batch. mListAdapter.removeObserver(); mListAdapter.clear(); mListAdapter = new SeparatedListAdapter(this); // User can sort by default (which is by checkin time), or just by distance. if (checkins != null) { mStateHolder.setCheckins(checkins); if (mStateHolder.getSortMethod() == SORT_METHOD_RECENT) { sortCheckinsRecent(checkins, mListAdapter); } else { sortCheckinsDistance(checkins, mListAdapter); } } else if (ex != null) { mStateHolder.setCheckins(new Group<Checkin>()); NotificationsUtil.ToastReasonForFailure(this, ex); } if (mStateHolder.getCheckins().size() == 0) { setEmptyView(mLayoutEmpty); } getListView().setAdapter(mListAdapter); } private static class TaskCheckins extends AsyncTask<Void, Void, Group<Checkin>> { private Foursquared mFoursquared; private FriendsActivity mActivity; private Exception mException; public TaskCheckins(FriendsActivity activity) { mFoursquared = ((Foursquared) activity.getApplication()); mActivity = activity; } public void setActivity(FriendsActivity activity) { mActivity = activity; } @Override public Group<Checkin> doInBackground(Void... params) { Group<Checkin> checkins = null; try { checkins = checkins(); } catch (Exception ex) { mException = ex; } return checkins; } @Override protected void onPreExecute() { mActivity.onTaskStart(); } @Override public void onPostExecute(Group<Checkin> checkins) { if (mActivity != null) { mActivity.onTaskComplete(checkins, mException); } } private Group<Checkin> checkins() throws FoursquareException, IOException { // If we're the startup tab, it's likely that we won't have a geo location // immediately. For now we can use this ugly method of sleeping for N // seconds to at least let network location get a lock. We're only trying // to discern between same-city, so we can even use LocationManager's // getLastKnownLocation() method because we don't care if we're even a few // miles off. The api endpoint doesn't require location, so still go ahead // even if we can't find a location. Location loc = mFoursquared.getLastKnownLocation(); if (loc == null) { try { Thread.sleep(SLEEP_TIME_IF_NO_LOCATION); } catch (InterruptedException ex) {} loc = mFoursquared.getLastKnownLocation(); } Group<Checkin> checkins = mFoursquared.getFoursquare().checkins(LocationUtils .createFoursquareLocation(loc)); Collections.sort(checkins, Comparators.getCheckinRecencyComparator()); return checkins; } } private static class StateHolder { private Group<Checkin> mCheckins; private int mSortMethod; private boolean mRanOnce; private boolean mIsRunningTask; private TaskCheckins mTaskCheckins; public StateHolder() { mRanOnce = false; mIsRunningTask = false; mCheckins = new Group<Checkin>(); } public int getSortMethod() { return mSortMethod; } public void setSortMethod(int sortMethod) { mSortMethod = sortMethod; } public Group<Checkin> getCheckins() { return mCheckins; } public void setCheckins(Group<Checkin> checkins) { mCheckins = checkins; } public boolean getRanOnce() { return mRanOnce; } public void setRanOnce(boolean ranOnce) { mRanOnce = ranOnce; } public boolean getIsRunningTask() { return mIsRunningTask; } public void setIsRunningTask(boolean isRunning) { mIsRunningTask = isRunning; } public void setActivity(FriendsActivity activity) { if (mIsRunningTask) { mTaskCheckins.setActivity(activity); } } public void startTask(FriendsActivity activity) { if (!mIsRunningTask) { mTaskCheckins = new TaskCheckins(activity); mTaskCheckins.execute(); mIsRunningTask = true; } } public void cancel() { if (mIsRunningTask) { mTaskCheckins.cancel(true); mIsRunningTask = false; } } } /** * This is really just a dummy observer to get the GPS running * since this is the new splash page. After getting a fix, we * might want to stop registering this observer thereafter so * it doesn't annoy the user too much. */ private class SearchLocationObserver implements Observer { @Override public void update(Observable observable, Object data) { } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Display; import android.view.WindowManager; import android.webkit.WebView; import android.widget.LinearLayout; /** * Shows a listing of what's changed between * * @date March 17, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ChangelogActivity extends Activity { private static final String CHANGELOG_HTML_FILE = "file:///android_asset/changelog-en.html"; private WebView mWebViewChanges; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.changelog_activity); ensureUi(); } private void ensureUi() { WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); LinearLayout llMain = (LinearLayout)findViewById(R.id.layoutMain); // We'll force the dialog to be a certain percentage height of the screen. mWebViewChanges = new WebView(this); mWebViewChanges.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, (int)Math.floor(display.getHeight() * 0.5))); mWebViewChanges.loadUrl(CHANGELOG_HTML_FILE); llMain.addView(mWebViewChanges); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.appwidget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.MainActivity; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.UserDetailsActivity; import com.joelapenna.foursquared.app.FoursquaredService; import com.joelapenna.foursquared.util.DumpcatcherHelper; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.text.format.DateUtils; import android.util.Log; import android.view.View; import android.widget.RemoteViews; import java.io.IOException; import java.util.Date; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FriendsAppWidgetProvider extends AppWidgetProvider { private static final String TAG = "FriendsAppWidgetProvider"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int[][] WIDGET_VIEW_IDS = { { R.id.widgetItem0, R.id.photo0, R.id.user0, R.id.time0, R.id.location0 }, { R.id.widgetItem1, R.id.photo1, R.id.user1, R.id.time1, R.id.location1 }, { R.id.widgetItem2, R.id.photo2, R.id.user2, R.id.time2, R.id.location2 }, { R.id.widgetItem3, R.id.photo3, R.id.user3, R.id.time3, R.id.location3 }, { R.id.widgetItem4, R.id.photo4, R.id.user4, R.id.time4, R.id.location4 } }; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { if (DEBUG) Log.d(TAG, "onUpdate()"); Intent intent = new Intent(context, FoursquaredService.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); context.startService(intent); } public static void updateAppWidget(Context context, RemoteResourceManager rrm, AppWidgetManager appWidgetManager, Integer appWidgetId, Group<Checkin> checkins) { if (DEBUG) Log.d(TAG, "updateAppWidget: " + String.valueOf(appWidgetId)); // Get the layout for the App Widget and attach an on-click listener to the button RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.friends_appwidget); if (DEBUG) Log.d(TAG, "adding header intent: " + String.valueOf(appWidgetId)); Intent baseIntent = new Intent(context, MainActivity.class); views.setOnClickPendingIntent(R.id.widgetHeader, PendingIntent.getActivity(context, 0, baseIntent, 0)); if (DEBUG) Log.d(TAG, "adding footer intent: " + String.valueOf(appWidgetId)); baseIntent = new Intent(context, FoursquaredService.class); baseIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); views.setOnClickPendingIntent(R.id.widgetFooter, PendingIntent.getService(context, 0, baseIntent, 0)); // Now hide all views if checkins is null (a sign of not being logged in), or populate the // checkins. if (checkins == null) { if (DEBUG) Log.d(TAG, "checkins is null, hiding UI."); views.setViewVisibility(R.id.widgetNotLoggedInTextView, View.VISIBLE); for (int i = 0; i < WIDGET_VIEW_IDS.length; i++) { hideCheckinView(views, WIDGET_VIEW_IDS[i]); } } else { if (DEBUG) Log.d(TAG, "Displaying checkins"); views.setViewVisibility(R.id.widgetNotLoggedInTextView, View.GONE); int numCheckins = checkins.size(); for (int i = 0; i < WIDGET_VIEW_IDS.length; i++) { if (i < numCheckins) { updateCheckinView(context, rrm, views, checkins.get(i), WIDGET_VIEW_IDS[i]); } else { hideCheckinView(views, WIDGET_VIEW_IDS[i]); } } } // Lastly, update the refresh timestamp CharSequence timestamp = DateUtils.formatDateTime(context, new Date().getTime(), DateUtils.FORMAT_SHOW_TIME); views.setTextViewText(R.id.widgetFooter, context.getResources().getString( R.string.friends_appwidget_footer_text, timestamp)); // Tell the AppWidgetManager to perform an update on the current App Widget try { appWidgetManager.updateAppWidget(appWidgetId, views); } catch (Exception e) { if (DEBUG) Log.d(TAG, "updateAppWidget crashed: ", e); DumpcatcherHelper.sendException(e); } } private static void updateCheckinView(Context context, RemoteResourceManager rrm, RemoteViews views, Checkin checkin, int[] viewIds) { int viewId = viewIds[0]; int photoViewId = viewIds[1]; int userViewId = viewIds[2]; int timeViewId = viewIds[3]; int locationViewId = viewIds[4]; final User user = checkin.getUser(); final Uri photoUri = Uri.parse(user.getPhoto()); views.setViewVisibility(viewId, View.VISIBLE); Intent baseIntent; baseIntent = new Intent(context, UserDetailsActivity.class); baseIntent.putExtra(UserDetailsActivity.EXTRA_USER_ID, checkin.getUser().getId()); baseIntent.setData(Uri.parse("https://foursquare.com/user/" + checkin.getUser().getId())); views.setOnClickPendingIntent(viewId, PendingIntent.getActivity(context, 0, baseIntent, 0)); try { Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(photoUri)); views.setImageViewBitmap(photoViewId, bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(checkin.getUser().getGender())) { views.setImageViewResource(photoViewId, R.drawable.blank_boy); } else { views.setImageViewResource(photoViewId, R.drawable.blank_girl); } } views.setTextViewText(userViewId, StringFormatters.getUserAbbreviatedName(user)); views.setTextViewText(timeViewId, StringFormatters.getRelativeTimeSpanString(checkin .getCreated())); if (VenueUtils.isValid(checkin.getVenue())) { views.setTextViewText(locationViewId, checkin.getVenue().getName()); } else { views.setTextViewText(locationViewId, ""); } } private static void hideCheckinView(RemoteViews views, int[] viewIds) { views.setViewVisibility(viewIds[0], View.GONE); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.Badge; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.widget.BadgeWithIconListAdapter; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.DialogInterface.OnDismissListener; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.AdapterView.OnItemClickListener; import java.util.ArrayList; /** * Shows a listing of all the badges the user has earned. Right not it shows only * the earned badges, we can add an additional display flag to also display badges * the user has yet to unlock as well. This will show them what they're missing * which would be fun to see. * * @date March 10, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class BadgesActivity extends Activity { private static final String TAG = "BadgesActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_BADGE_ARRAY_LIST_PARCEL = Foursquared.PACKAGE_NAME + ".BadgesActivity.EXTRA_BADGE_ARRAY_LIST_PARCEL"; public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME + ".BadgesActivity.EXTRA_USER_NAME"; private static final int DIALOG_ID_INFO = 1; private GridView mBadgesGrid; private BadgeWithIconListAdapter mListAdapter; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.badges_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { if (getIntent().hasExtra(EXTRA_BADGE_ARRAY_LIST_PARCEL) && getIntent().hasExtra(EXTRA_USER_NAME)) { mStateHolder = new StateHolder(getIntent().getStringExtra(EXTRA_USER_NAME)); // Can't jump from ArrayList to Group, argh. ArrayList<Badge> badges = getIntent().getExtras().getParcelableArrayList( EXTRA_BADGE_ARRAY_LIST_PARCEL); Group<Badge> group = new Group<Badge>(); for (Badge it : badges) { group.add(it); } mStateHolder.setBadges(group); } else { Log.e(TAG, "BadgesActivity requires a badge ArrayList pareclable in its intent extras."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } private void ensureUi() { mBadgesGrid = (GridView)findViewById(R.id.badgesGrid); mListAdapter = new BadgeWithIconListAdapter(this, ((Foursquared)getApplication()).getRemoteResourceManager()); mListAdapter.setGroup(mStateHolder.getBadges()); mBadgesGrid.setAdapter(mListAdapter); mBadgesGrid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) { Badge badge = (Badge)mListAdapter.getItem(position); showDialogInfo(badge.getName(), badge.getDescription(), badge.getIcon()); } }); setTitle(getString(R.string.badges_activity_title, mStateHolder.getUsername())); } private void showDialogInfo(String title, String message, String badgeIconUrl) { mStateHolder.setDlgInfoTitle(title); mStateHolder.setDlgInfoMessage(message); mStateHolder.setDlgInfoBadgeIconUrl(badgeIconUrl); showDialog(DIALOG_ID_INFO); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ID_INFO: AlertDialog dlgInfo = new AlertDialog.Builder(this) .setTitle(mStateHolder.getDlgInfoTitle()) .setIcon(0) .setMessage(mStateHolder.getDlgInfoMessage()).create(); dlgInfo.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(DIALOG_ID_INFO); } }); try { Uri icon = Uri.parse(mStateHolder.getDlgInfoBadgeIconUrl()); dlgInfo.setIcon(new BitmapDrawable(((Foursquared) getApplication()) .getRemoteResourceManager().getInputStream(icon))); } catch (Exception e) { Log.e(TAG, "Error loading badge dialog!", e); dlgInfo.setIcon(R.drawable.default_on); } return dlgInfo; } return null; } private static class StateHolder { private String mUsername; private Group<Badge> mBadges; private String mDlgInfoTitle; private String mDlgInfoMessage; private String mDlgInfoBadgeIconUrl; public StateHolder(String username) { mUsername = username; mBadges = new Group<Badge>(); } public String getUsername() { return mUsername; } public Group<Badge> getBadges() { return mBadges; } public void setBadges(Group<Badge> badges) { mBadges = badges; } public String getDlgInfoTitle() { return mDlgInfoTitle; } public void setDlgInfoTitle(String text) { mDlgInfoTitle = text; } public String getDlgInfoMessage() { return mDlgInfoMessage; } public void setDlgInfoMessage(String text) { mDlgInfoMessage = text; } public String getDlgInfoBadgeIconUrl() { return mDlgInfoBadgeIconUrl; } public void setDlgInfoBadgeIconUrl(String url) { mDlgInfoBadgeIconUrl = url; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquared.preferences.Preferences; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; /** * Used to show a prompt to the user before the app runs. Some new marketplace vendors have * been asking this so they can prompt the user and tell them that the app uses internet * connections, which is not unlimited usage under many plans. This really should be handled * by the install screen which shows other permissions used. * * To enable this activity, just set it as the LAUNCHER in the manifest file. If the tag is * not added in the manifest file, this activity is never used. * * You can modify these text items in strings.xml to modify the appearance of the activity: * <ul> * <li>prelaunch_text</li> * <li>prelaunch_button</li> * <li>prelaunch_checkbox_dont_show_again</li> * </ul> * * @date May 15, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PrelaunchActivity extends Activity { public static final String TAG = "PrelaunchActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); setContentView(R.layout.prelaunch_activity); // If user doesn't want to be reminded anymore, just go to main activity. if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean( Preferences.PREFERENCE_SHOW_PRELAUNCH_ACTIVITY, false) == false) { startMainActivity(); } else { ensureUi(); } } private void ensureUi() { Button buttonOk = (Button) findViewById(R.id.btnOk); buttonOk.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { goToMain(false); } }); } private void goToMain(boolean dontRemind) { // Don't show this startup screen anymore. CheckBox checkboxDontShowAgain = (CheckBox)findViewById(R.id.checkboxDontShowAgain); if (checkboxDontShowAgain.isChecked()) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.edit().putBoolean(Preferences.PREFERENCE_SHOW_PRELAUNCH_ACTIVITY, false).commit(); } startMainActivity(); } private void startMainActivity() { Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.facebook.android.Facebook; import com.facebook.android.FacebookUtil; import com.facebook.android.FacebookWebViewActivity; import com.facebook.android.Facebook.PreparedUrl; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.FriendInvitesResult; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.util.AddressBookEmailBuilder; import com.joelapenna.foursquared.util.AddressBookUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.AddressBookEmailBuilder.ContactSimple; import com.joelapenna.foursquared.widget.FriendSearchAddFriendAdapter; import com.joelapenna.foursquared.widget.FriendSearchInviteNonFoursquareUserAdapter; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.DialogInterface.OnDismissListener; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView.OnEditorActionListener; import java.util.ArrayList; import java.util.List; /** * Lets the user search for friends via first+last name, phone number, or * twitter names. Once a list of matching users is found, the user can click on * elements in the list to send a friend request to them. When the request is * successfully sent, that user is removed from the list. You can add the * INPUT_TYPE key to the intent while launching the activity to control what * type of friend search the activity will perform. Pass in one of the following * values: * <ul> * <li>INPUT_TYPE_NAME_OR_PHONE</li> * <li>INPUT_TYPE_TWITTERNAME</li> * <li>INPUT_TYPE_ADDRESSBOOK</li> * <li>INPUT_TYPE_ADDRESSBOOK_INVITE</li> * </ul> * * @date February 11, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class AddFriendsByUserInputActivity extends Activity { private static final String TAG = "AddFriendsByUserInputActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int DIALOG_ID_CONFIRM_INVITE_ALL = 1; public static final String INPUT_TYPE = "com.joelapenna.foursquared.AddFriendsByUserInputActivity.INPUT_TYPE"; public static final int INPUT_TYPE_NAME_OR_PHONE = 0; public static final int INPUT_TYPE_TWITTERNAME = 1; public static final int INPUT_TYPE_ADDRESSBOOK = 2; public static final int INPUT_TYPE_ADDRESSBOOK_INVITE = 3; public static final int INPUT_TYPE_FACEBOOK = 4; private static final int ACTIVITY_RESULT_FACEBOOK_WEBVIEW_ACTIVITY = 5; private TextView mTextViewInstructions; private TextView mTextViewAdditionalInstructions; private EditText mEditInput; private Button mBtnSearch; private ListView mListView; private ProgressDialog mDlgProgress; private int mInputType; private SeparatedListAdapter mListAdapter; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.add_friends_by_user_input_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mTextViewInstructions = (TextView) findViewById(R.id.addFriendInstructionsTextView); mTextViewAdditionalInstructions = (TextView) findViewById(R.id.addFriendInstructionsAdditionalTextView); mEditInput = (EditText) findViewById(R.id.addFriendInputEditText); mBtnSearch = (Button) findViewById(R.id.addFriendSearchButton); mListView = (ListView) findViewById(R.id.addFriendResultsListView); mListAdapter = new SeparatedListAdapter(this); mListView.setAdapter(mListAdapter); mListView.setItemsCanFocus(true); mListView.setDividerHeight(0); mBtnSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startSearch(mEditInput.getText().toString()); } }); mEditInput.addTextChangedListener(mNamesFieldWatcher); mEditInput.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_NULL) { startSearch(mEditInput.getText().toString()); } return false; } }); mBtnSearch.setEnabled(false); mInputType = getIntent().getIntExtra(INPUT_TYPE, INPUT_TYPE_NAME_OR_PHONE); switch (mInputType) { case INPUT_TYPE_TWITTERNAME: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_twitter_instructions)); mEditInput.setHint(getResources().getString(R.string.add_friends_by_twitter_hint)); mEditInput.setInputType(InputType.TYPE_CLASS_TEXT); break; case INPUT_TYPE_ADDRESSBOOK: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_addressbook_instructions)); mTextViewAdditionalInstructions.setText(getResources().getString( R.string.add_friends_by_addressbook_additional_instructions)); mEditInput.setVisibility(View.GONE); mBtnSearch.setVisibility(View.GONE); break; case INPUT_TYPE_ADDRESSBOOK_INVITE: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_addressbook_instructions)); mTextViewAdditionalInstructions.setText(getResources().getString( R.string.add_friends_by_addressbook_additional_instructions)); mEditInput.setVisibility(View.GONE); mBtnSearch.setVisibility(View.GONE); break; case INPUT_TYPE_FACEBOOK: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_facebook_instructions)); mTextViewAdditionalInstructions.setText(getResources().getString( R.string.add_friends_by_facebook_additional_instructions)); mEditInput.setVisibility(View.GONE); mBtnSearch.setVisibility(View.GONE); break; default: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_name_or_phone_instructions)); mEditInput.setHint(getResources().getString(R.string.add_friends_by_name_or_phone_hint)); mEditInput.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); break; } Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTaskFindFriends(this); mStateHolder.setActivityForTaskFriendRequest(this); mStateHolder.setActivityForTaskSendInvite(this); // If we have run before, restore matches divider. if (mStateHolder.getRanOnce()) { populateListFromStateHolder(); } } else { mStateHolder = new StateHolder(); // If we are scanning the address book, or a facebook search, we should // kick off immediately. switch (mInputType) { case INPUT_TYPE_ADDRESSBOOK: case INPUT_TYPE_ADDRESSBOOK_INVITE: startSearch(""); break; case INPUT_TYPE_FACEBOOK: startFacebookWebViewActivity(); break; } } } @Override public void onResume() { super.onResume(); if (mStateHolder.getIsRunningTaskFindFriends()) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_find)); } else if (mStateHolder.getIsRunningTaskSendFriendRequest()) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources() .getString(R.string.add_friends_progress_bar_message_send_request)); } else if (mStateHolder.getIsRunningTaskSendInvite()) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources() .getString(R.string.add_friends_progress_bar_message_send_invite)); } } @Override public void onPause() { super.onPause(); stopProgressBar(); if (isFinishing()) { mListAdapter.removeObserver(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTaskFindFriends(null); mStateHolder.setActivityForTaskFriendRequest(null); mStateHolder.setActivityForTaskSendInvite(null); return mStateHolder; } private void userAdd(User user) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_send_request)); mStateHolder.startTaskSendFriendRequest(AddFriendsByUserInputActivity.this, user.getId()); } private void userInfo(User user) { Intent intent = new Intent(AddFriendsByUserInputActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user); startActivity(intent); } private void userInvite(ContactSimple contact) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_send_invite)); mStateHolder.startTaskSendInvite(AddFriendsByUserInputActivity.this, contact.mEmail, false); } private void inviteAll() { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_send_invite)); mStateHolder.startTaskSendInvite( AddFriendsByUserInputActivity.this, mStateHolder.getUsersNotOnFoursquareAsCommaSepString(), true); } private void startSearch(String input) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEditInput.getWindowToken(), 0); mEditInput.setEnabled(false); mBtnSearch.setEnabled(false); startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_find)); mStateHolder.startTaskFindFriends(AddFriendsByUserInputActivity.this, input); } private void startFacebookWebViewActivity() { Intent intent = new Intent(this, FacebookWebViewActivity.class); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_ACTION, Facebook.LOGIN); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_APP_ID, getResources().getString(R.string.facebook_api_key)); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_PERMISSIONS, new String[] {}); //{"publish_stream", "read_stream", "offline_access"}); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_DEBUG, false); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_CLEAR_COOKIES, true); startActivityForResult(intent, ACTIVITY_RESULT_FACEBOOK_WEBVIEW_ACTIVITY); } private void startProgressBar(String title, String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, title, message); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ID_CONFIRM_INVITE_ALL: AlertDialog dlgInfo = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.add_friends_contacts_title_invite_all)) .setIcon(0) .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { inviteAll(); } }) .setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setMessage(getResources().getString(R.string.add_friends_contacts_message_invite_all, String.valueOf(mStateHolder.getUsersNotOnFoursquare().size()))) .create(); dlgInfo.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(DIALOG_ID_CONFIRM_INVITE_ALL); } }); return dlgInfo; } return null; } /** * Listen for FacebookWebViewActivity finishing, inspect success/failure and returned * request parameters. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTIVITY_RESULT_FACEBOOK_WEBVIEW_ACTIVITY) { // If RESULT_OK, means the request was attempted, but we still have to check the return status. if (resultCode == RESULT_OK) { // Check return status. if (data.getBooleanExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_RESULT_STATUS, false)) { // If ok, the result bundle will contain all data from the webview. Bundle bundle = data.getBundleExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_RESULT_BUNDLE); // We can switch on the action here, the activity echoes it back to us for convenience. String suppliedAction = data.getStringExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_SUPPLIED_ACTION); if (suppliedAction.equals(Facebook.LOGIN)) { // We can now start a task to fetch foursquare friends using their facebook id. mStateHolder.startTaskFindFriends( AddFriendsByUserInputActivity.this, bundle.getString(Facebook.TOKEN)); } } else { // Error running the operation, report to user perhaps. String error = data.getStringExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_ERROR); Log.e(TAG, error); Toast.makeText(this, error, Toast.LENGTH_LONG).show(); finish(); } } else { // If the user cancelled enterting their facebook credentials, exit here too. finish(); } } } private void populateListFromStateHolder() { mListAdapter.removeObserver(); mListAdapter = new SeparatedListAdapter(this); if (mStateHolder.getUsersOnFoursquare().size() + mStateHolder.getUsersNotOnFoursquare().size() > 0) { if (mStateHolder.getUsersOnFoursquare().size() > 0) { FriendSearchAddFriendAdapter adapter = new FriendSearchAddFriendAdapter( this, mButtonRowClickHandler, ((Foursquared)getApplication()).getRemoteResourceManager()); adapter.setGroup(mStateHolder.getUsersOnFoursquare()); mListAdapter.addSection( getResources().getString(R.string.add_friends_contacts_found_on_foursqare), adapter); } if (mStateHolder.getUsersNotOnFoursquare().size() > 0) { FriendSearchInviteNonFoursquareUserAdapter adapter = new FriendSearchInviteNonFoursquareUserAdapter( this, mAdapterListenerInvites); adapter.setContacts(mStateHolder.getUsersNotOnFoursquare()); mListAdapter.addSection( getResources().getString(R.string.add_friends_contacts_not_found_on_foursqare), adapter); } } else { Toast.makeText(this, getResources().getString(R.string.add_friends_no_matches), Toast.LENGTH_SHORT).show(); } mListView.setAdapter(mListAdapter); } private void onFindFriendsTaskComplete(FindFriendsResult result, Exception ex) { if (result != null) { mStateHolder.setUsersOnFoursquare(result.getUsersOnFoursquare()); mStateHolder.setUsersNotOnFoursquare(result.getUsersNotOnFoursquare()); if (result.getUsersOnFoursquare().size() + result.getUsersNotOnFoursquare().size() < 1) { Toast.makeText(this, getResources().getString(R.string.add_friends_no_matches), Toast.LENGTH_SHORT).show(); } } else { NotificationsUtil.ToastReasonForFailure(AddFriendsByUserInputActivity.this, ex); } populateListFromStateHolder(); mEditInput.setEnabled(true); mBtnSearch.setEnabled(true); mStateHolder.setIsRunningTaskFindFriends(false); stopProgressBar(); } private void onSendFriendRequestTaskComplete(User friendRequestRecipient, Exception ex) { if (friendRequestRecipient != null) { // We do a linear search to find the row to remove, ouch. int position = 0; for (User it : mStateHolder.getUsersOnFoursquare()) { if (it.getId().equals(friendRequestRecipient.getId())) { mStateHolder.getUsersOnFoursquare().remove(position); break; } position++; } mListAdapter.notifyDataSetChanged(); Toast.makeText(AddFriendsByUserInputActivity.this, getResources().getString(R.string.add_friends_request_sent_ok), Toast.LENGTH_SHORT).show(); } else { NotificationsUtil.ToastReasonForFailure(AddFriendsByUserInputActivity.this, ex); } mEditInput.setEnabled(true); mBtnSearch.setEnabled(true); mStateHolder.setIsRunningTaskSendFriendRequest(false); stopProgressBar(); } private void onSendInviteTaskComplete(String email, boolean isAllEmails, Exception ex) { if (email != null) { if (isAllEmails) { mStateHolder.getUsersNotOnFoursquare().clear(); Toast.makeText(AddFriendsByUserInputActivity.this, getResources().getString(R.string.add_friends_invites_sent_ok), Toast.LENGTH_SHORT).show(); } else { // We do a linear search to find the row to remove, ouch. int position = 0; for (ContactSimple it : mStateHolder.getUsersNotOnFoursquare()) { if (it.mEmail.equals(email)) { mStateHolder.getUsersNotOnFoursquare().remove(position); break; } position++; } Toast.makeText(AddFriendsByUserInputActivity.this, getResources().getString(R.string.add_friends_invite_sent_ok), Toast.LENGTH_SHORT).show(); } mListAdapter.notifyDataSetChanged(); } else { NotificationsUtil.ToastReasonForFailure(AddFriendsByUserInputActivity.this, ex); } mEditInput.setEnabled(true); mBtnSearch.setEnabled(true); mStateHolder.setIsRunningTaskSendInvite(false); stopProgressBar(); } private static class FindFriendsTask extends AsyncTask<String, Void, FindFriendsResult> { private AddFriendsByUserInputActivity mActivity; private Exception mReason; public FindFriendsTask(AddFriendsByUserInputActivity activity) { mActivity = activity; } public void setActivity(AddFriendsByUserInputActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(mActivity.getResources().getString( R.string.add_friends_activity_label), mActivity.getResources().getString( R.string.add_friends_progress_bar_message_find)); } @Override protected FindFriendsResult doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); FindFriendsResult result = new FindFriendsResult(); switch (mActivity.mInputType) { case INPUT_TYPE_TWITTERNAME: result.setUsersOnFoursquare(foursquare.findFriendsByTwitter(params[0])); break; case INPUT_TYPE_ADDRESSBOOK: scanAddressBook(result, foursquare, foursquared, false); break; case INPUT_TYPE_ADDRESSBOOK_INVITE: scanAddressBook(result, foursquare, foursquared, true); break; case INPUT_TYPE_FACEBOOK: // For facebook, we need to first get all friend uids, then use that with the foursquare api. String facebookFriendIds = getFacebookFriendIds(params[0]); if (!TextUtils.isEmpty(facebookFriendIds)) { result.setUsersOnFoursquare(foursquare.findFriendsByFacebook(facebookFriendIds)); } else { result.setUsersOnFoursquare(new Group<User>()); } break; default: // Combine searches for name/phone, results returned in one list. Group<User> users = new Group<User>(); users.addAll(foursquare.findFriendsByPhone(params[0])); users.addAll(foursquare.findFriendsByName(params[0])); result.setUsersOnFoursquare(users); break; } return result; } catch (Exception e) { if (DEBUG) Log.d(TAG, "FindFriendsTask: Exception doing add friends by name", e); mReason = e; } return null; } private String getFacebookFriendIds(String facebookToken) { Facebook facebook = new Facebook(); facebook.setAccessToken(facebookToken); String friendsAsJson = ""; try { PreparedUrl purl = facebook.requestUrl("me/friends"); friendsAsJson = FacebookUtil.openUrl(purl.getUrl(), purl.getHttpMethod(), purl.getParameters()); } catch (Exception ex) { Log.e(TAG, "Error getting facebook friends as json.", ex); return friendsAsJson; } // {"data":[{"name":"Friends Name","id":"12345"}]} StringBuilder sb = new StringBuilder(2048); try { JSONObject json = new JSONObject(friendsAsJson); JSONArray friends = json.getJSONArray("data"); for (int i = 0, m = friends.length(); i < m; i++) { JSONObject friend = friends.getJSONObject(i); sb.append(friend.get("id")); sb.append(","); } if (sb.length() > 0 && sb.charAt(sb.length()-1) == ',') { sb.deleteCharAt(sb.length()-1); } } catch (Exception ex) { Log.e(TAG, "Error deserializing facebook friends json object.", ex); } return sb.toString(); } private void scanAddressBook(FindFriendsResult result, Foursquare foursquare, Foursquared foursquared, boolean invites) throws Exception { AddressBookUtils addr = AddressBookUtils.addressBookUtils(); AddressBookEmailBuilder bld = addr.getAllContactsEmailAddressesInfo(mActivity); String phones = addr.getAllContactsPhoneNumbers(mActivity); String emails = bld.getEmailsCommaSeparated(); if (!TextUtils.isEmpty(phones) || !TextUtils.isEmpty(emails)) { FriendInvitesResult xml = foursquare.findFriendsByPhoneOrEmail(phones, emails); result.setUsersOnFoursquare(xml.getContactsOnFoursquare()); if (invites) { // Get a contact name for each email address we can send an invite to. List<ContactSimple> contactsNotOnFoursquare = new ArrayList<ContactSimple>(); for (String it : xml.getContactEmailsNotOnFoursquare()) { ContactSimple contact = new ContactSimple(); contact.mEmail = it; contact.mName = bld.getNameForEmail(it); contactsNotOnFoursquare.add(contact); } result.setUsersNotOnFoursquare(contactsNotOnFoursquare); } } } @Override protected void onPostExecute(FindFriendsResult result) { if (DEBUG) Log.d(TAG, "FindFriendsTask: onPostExecute()"); if (mActivity != null) { mActivity.onFindFriendsTaskComplete(result, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onFindFriendsTaskComplete( null, new Exception("Friend search cancelled.")); } } } private static class SendFriendRequestTask extends AsyncTask<String, Void, User> { private AddFriendsByUserInputActivity mActivity; private Exception mReason; public SendFriendRequestTask(AddFriendsByUserInputActivity activity) { mActivity = activity; } public void setActivity(AddFriendsByUserInputActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(mActivity.getResources().getString( R.string.add_friends_activity_label), mActivity.getResources().getString( R.string.add_friends_progress_bar_message_send_request)); } @Override protected User doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); User user = foursquare.friendSendrequest(params[0]); return user; } catch (Exception e) { if (DEBUG) Log.d(TAG, "SendFriendRequestTask: Exception doing send friend request.", e); mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (DEBUG) Log.d(TAG, "SendFriendRequestTask: onPostExecute()"); if (mActivity != null) { mActivity.onSendFriendRequestTaskComplete(user, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onSendFriendRequestTaskComplete(null, new Exception( "Friend invitation cancelled.")); } } } private static class SendInviteTask extends AsyncTask<String, Void, String> { private AddFriendsByUserInputActivity mActivity; private boolean mIsAllEmails; private Exception mReason; public SendInviteTask(AddFriendsByUserInputActivity activity, boolean isAllEmails) { mActivity = activity; mIsAllEmails = isAllEmails; } public void setActivity(AddFriendsByUserInputActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(mActivity.getResources().getString( R.string.add_friends_activity_label), mActivity.getResources().getString( R.string.add_friends_progress_bar_message_send_invite)); } @Override protected String doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); foursquare.inviteByEmail(params[0]); return params[0]; } catch (Exception e) { Log.e(TAG, "SendInviteTask: Exception sending invite.", e); mReason = e; } return null; } @Override protected void onPostExecute(String email) { if (DEBUG) Log.d(TAG, "SendInviteTask: onPostExecute()"); if (mActivity != null) { mActivity.onSendInviteTaskComplete(email, mIsAllEmails, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onSendInviteTaskComplete(null, mIsAllEmails, new Exception("Invite send cancelled.")); } } } private static class StateHolder { FindFriendsTask mTaskFindFriends; SendFriendRequestTask mTaskSendFriendRequest; SendInviteTask mTaskSendInvite; Group<User> mUsersOnFoursquare; List<ContactSimple> mUsersNotOnFoursquare; boolean mIsRunningTaskFindFriends; boolean mIsRunningTaskSendFriendRequest; boolean mIsRunningTaskSendInvite; boolean mRanOnce; public StateHolder() { mUsersOnFoursquare = new Group<User>(); mUsersNotOnFoursquare = new ArrayList<ContactSimple>(); mIsRunningTaskFindFriends = false; mIsRunningTaskSendFriendRequest = false; mIsRunningTaskSendInvite = false; mRanOnce = false; } public Group<User> getUsersOnFoursquare() { return mUsersOnFoursquare; } public void setUsersOnFoursquare(Group<User> usersOnFoursquare) { mUsersOnFoursquare = usersOnFoursquare; mRanOnce = true; } public List<ContactSimple> getUsersNotOnFoursquare() { return mUsersNotOnFoursquare; } public void setUsersNotOnFoursquare(List<ContactSimple> usersNotOnFoursquare) { mUsersNotOnFoursquare = usersNotOnFoursquare; } public void startTaskFindFriends(AddFriendsByUserInputActivity activity, String input) { mIsRunningTaskFindFriends = true; mTaskFindFriends = new FindFriendsTask(activity); mTaskFindFriends.execute(input); } public void startTaskSendFriendRequest(AddFriendsByUserInputActivity activity, String userId) { mIsRunningTaskSendFriendRequest = true; mTaskSendFriendRequest = new SendFriendRequestTask(activity); mTaskSendFriendRequest.execute(userId); } public void startTaskSendInvite(AddFriendsByUserInputActivity activity, String email, boolean isAllEmails) { mIsRunningTaskSendInvite = true; mTaskSendInvite = new SendInviteTask(activity, isAllEmails); mTaskSendInvite.execute(email); } public void setActivityForTaskFindFriends(AddFriendsByUserInputActivity activity) { if (mTaskFindFriends != null) { mTaskFindFriends.setActivity(activity); } } public void setActivityForTaskFriendRequest(AddFriendsByUserInputActivity activity) { if (mTaskSendFriendRequest != null) { mTaskSendFriendRequest.setActivity(activity); } } public void setActivityForTaskSendInvite(AddFriendsByUserInputActivity activity) { if (mTaskSendInvite != null) { mTaskSendInvite.setActivity(activity); } } public void setIsRunningTaskFindFriends(boolean isRunning) { mIsRunningTaskFindFriends = isRunning; } public void setIsRunningTaskSendFriendRequest(boolean isRunning) { mIsRunningTaskSendFriendRequest = isRunning; } public void setIsRunningTaskSendInvite(boolean isRunning) { mIsRunningTaskSendInvite = isRunning; } public boolean getIsRunningTaskFindFriends() { return mIsRunningTaskFindFriends; } public boolean getIsRunningTaskSendFriendRequest() { return mIsRunningTaskSendFriendRequest; } public boolean getIsRunningTaskSendInvite() { return mIsRunningTaskSendInvite; } public boolean getRanOnce() { return mRanOnce; } public String getUsersNotOnFoursquareAsCommaSepString() { StringBuilder sb = new StringBuilder(2048); for (ContactSimple it : mUsersNotOnFoursquare) { if (sb.length() > 0) { sb.append(","); } sb.append(it.mEmail); } return sb.toString(); } } private TextWatcher mNamesFieldWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mBtnSearch.setEnabled(!TextUtils.isEmpty(s)); } }; /** * This handler will be called when the user clicks on buttons in one of the * listview's rows. */ private FriendSearchAddFriendAdapter.ButtonRowClickHandler mButtonRowClickHandler = new FriendSearchAddFriendAdapter.ButtonRowClickHandler() { @Override public void onBtnClickAdd(User user) { userAdd(user); } @Override public void onInfoAreaClick(User user) { userInfo(user); } }; private FriendSearchInviteNonFoursquareUserAdapter.AdapterListener mAdapterListenerInvites = new FriendSearchInviteNonFoursquareUserAdapter.AdapterListener() { @Override public void onBtnClickInvite(ContactSimple contact) { userInvite(contact); } @Override public void onInfoAreaClick(ContactSimple contact) { // We could popup an intent for this contact so they can see // who we're talking about? } @Override public void onInviteAll() { showDialog(DIALOG_ID_CONFIRM_INVITE_ALL); } }; private static class FindFriendsResult { private Group<User> mUsersOnFoursquare; private List<ContactSimple> mUsersNotOnFoursquare; public FindFriendsResult() { mUsersOnFoursquare = new Group<User>(); mUsersNotOnFoursquare = new ArrayList<ContactSimple>(); } public Group<User> getUsersOnFoursquare() { return mUsersOnFoursquare; } public void setUsersOnFoursquare(Group<User> users) { if (users != null) { mUsersOnFoursquare = users; } } public List<ContactSimple> getUsersNotOnFoursquare() { return mUsersNotOnFoursquare; } public void setUsersNotOnFoursquare(List<ContactSimple> usersNotOnFoursquare) { if (usersNotOnFoursquare != null) { mUsersNotOnFoursquare = usersNotOnFoursquare; } } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.http.AbstractHttpApi; import com.joelapenna.foursquared.util.NotificationsUtil; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.protocol.ClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.webkit.WebView; import java.io.IOException; /** * Displays a special in a webview. Ideally we could use WebView.setHttpAuthUsernamePassword(), * but it is unfortunately not working. Instead we download the html content manually, then * feed it to our webview. Not ideal and we should update this in the future. * * @date April 4, 2010. * @author Mark Wyszomierski (markww@gmail.com), foursquare. * */ public class SpecialWebViewActivity extends Activity { private static final String TAG = "WebViewActivity"; public static final String EXTRA_CREDENTIALS_USERNAME = Foursquared.PACKAGE_NAME + ".SpecialWebViewActivity.EXTRA_CREDENTIALS_USERNAME"; public static final String EXTRA_CREDENTIALS_PASSWORD = Foursquared.PACKAGE_NAME + ".SpecialWebViewActivity.EXTRA_CREDENTIALS_PASSWORD"; public static final String EXTRA_SPECIAL_ID = Foursquared.PACKAGE_NAME + ".SpecialWebViewActivity.EXTRA_SPECIAL_ID"; private WebView mWebView; private StateHolder mStateHolder; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.special_webview_activity); mWebView = (WebView)findViewById(R.id.webView); mWebView.getSettings().setJavaScriptEnabled(true); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTask(this); if (mStateHolder.getIsRunningTask() == false) { mWebView.loadDataWithBaseURL("--", mStateHolder.getHtml(), "text/html", "utf-8", ""); } } else { mStateHolder = new StateHolder(); if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EXTRA_CREDENTIALS_USERNAME) && getIntent().getExtras().containsKey(EXTRA_CREDENTIALS_PASSWORD) && getIntent().getExtras().containsKey(EXTRA_SPECIAL_ID)) { String username = getIntent().getExtras().getString(EXTRA_CREDENTIALS_USERNAME); String password = getIntent().getExtras().getString(EXTRA_CREDENTIALS_PASSWORD); String specialid = getIntent().getExtras().getString(EXTRA_SPECIAL_ID); mStateHolder.startTask(this, username, password, specialid); } else { Log.e(TAG, TAG + " intent missing required extras parameters."); finish(); } } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTask(null); return mStateHolder; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } private void onTaskComplete(String html, Exception ex) { mStateHolder.setIsRunningTask(false); if (html != null) { mStateHolder.setHtml(html); mWebView.loadDataWithBaseURL("--", mStateHolder.getHtml(), "text/html", "utf-8", ""); } else { NotificationsUtil.ToastReasonForFailure(this, ex); } } private static class SpecialTask extends AsyncTask<String, Void, String> { private SpecialWebViewActivity mActivity; private Exception mReason; public SpecialTask(SpecialWebViewActivity activity) { mActivity = activity; } public void setActivity(SpecialWebViewActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { } @Override protected String doInBackground(String... params) { String html = null; try { String username = params[0]; String password = params[1]; String specialid = params[2]; StringBuilder sbUrl = new StringBuilder(128); sbUrl.append("https://api.foursquare.com/iphone/special?sid="); sbUrl.append(specialid); AuthScope authScope = new AuthScope("api.foursquare.com", 80); DefaultHttpClient httpClient = AbstractHttpApi.createHttpClient(); httpClient.getCredentialsProvider().setCredentials(authScope, new UsernamePasswordCredentials(username, password)); httpClient.addRequestInterceptor(preemptiveAuth, 0); HttpGet httpGet = new HttpGet(sbUrl.toString()); try { HttpResponse response = httpClient.execute(httpGet); String responseText = EntityUtils.toString(response.getEntity()); html = responseText.replace("('/img", "('http://www.foursquare.com/img"); } catch (Exception e) { mReason = e; } } catch (Exception e) { mReason = e; } return html; } @Override protected void onPostExecute(String html) { if (mActivity != null) { mActivity.onTaskComplete(html, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskComplete(null, new Exception("Special task cancelled.")); } } private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider)context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; } private static class StateHolder { private String mHtml; private boolean mIsRunningTask; private SpecialTask mTask; public StateHolder() { mIsRunningTask = false; } public void setHtml(String html) { mHtml = html; } public String getHtml() { return mHtml; } public void startTask(SpecialWebViewActivity activity, String username, String password, String specialid) { mIsRunningTask = true; mTask = new SpecialTask(activity); mTask.execute(username, password, specialid); } public void setActivityForTask(SpecialWebViewActivity activity) { if (mTask != null) { mTask.setActivity(activity); } } public void setIsRunningTask(boolean isRunningTipTask) { mIsRunningTask = isRunningTipTask; } public boolean getIsRunningTask() { return mIsRunningTask; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.UserUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @date September 25, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class FriendActionableListAdapter extends BaseGroupAdapter<User> implements ObservableAdapter { private LayoutInflater mInflater; private int mLayoutToInflate; private ButtonRowClickHandler mClickListener; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private int mLoadedPhotoIndex; public FriendActionableListAdapter(Context context, ButtonRowClickHandler clickListener, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.friend_actionable_list_item; mClickListener = clickListener; mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mLoadedPhotoIndex = 0; mRrm.addObserver(mResourcesObserver); } public FriendActionableListAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } public void removeObserver() { mHandler.removeCallbacks(mRunnableLoadPhotos); mHandler.removeCallbacks(mUpdatePhotos); mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); holder = new ViewHolder(); holder.photo = (ImageView) convertView.findViewById(R.id.photo); holder.name = (TextView) convertView.findViewById(R.id.name); holder.btn1 = (Button) convertView.findViewById(R.id.btn1); holder.btn2 = (Button) convertView.findViewById(R.id.btn2); convertView.setTag(holder); holder.btn1.setOnClickListener(mOnClickListenerBtn1); holder.btn2.setOnClickListener(mOnClickListenerBtn2); } else { holder = (ViewHolder) convertView.getTag(); } User user = (User) getItem(position); final Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } } holder.name.setText(user.getFirstname() + " " + (user.getLastname() != null ? user.getLastname() : "")); if (UserUtils.isFollower(user)) { holder.btn1.setVisibility(View.VISIBLE); holder.btn2.setVisibility(View.VISIBLE); holder.btn1.setTag(user); holder.btn2.setTag(user); } else { // Eventually we may have items for this case, like 'delete friend'. holder.btn1.setVisibility(View.GONE); holder.btn2.setVisibility(View.GONE); } return convertView; } private OnClickListener mOnClickListenerBtn1 = new OnClickListener() { @Override public void onClick(View v) { if (mClickListener != null) { User user = (User) v.getTag(); mClickListener.onBtnClickBtn1(user); } } }; private OnClickListener mOnClickListenerBtn2 = new OnClickListener() { @Override public void onClick(View v) { if (mClickListener != null) { User user = (User) v.getTag(); mClickListener.onBtnClickBtn2(user); } } }; public void removeItem(int position) throws IndexOutOfBoundsException { group.remove(position); notifyDataSetInvalidated(); } @Override public void setGroup(Group<User> g) { super.setGroup(g); mLoadedPhotoIndex = 0; mHandler.postDelayed(mRunnableLoadPhotos, 10L); } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(mUpdatePhotos); } } private Runnable mUpdatePhotos = new Runnable() { @Override public void run() { notifyDataSetChanged(); } }; private Runnable mRunnableLoadPhotos = new Runnable() { @Override public void run() { if (mLoadedPhotoIndex < getCount()) { User user = (User)getItem(mLoadedPhotoIndex++); Uri photoUri = Uri.parse(user.getPhoto()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } mHandler.postDelayed(mRunnableLoadPhotos, 200L); } } }; static class ViewHolder { ImageView photo; TextView name; Button btn1; Button btn2; } public interface ButtonRowClickHandler { public void onBtnClickBtn1(User user); public void onBtnClickBtn2(User user); } }
Java
package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.io.File; import java.io.IOException; import java.util.Observable; import java.util.Observer; public class CategoryPickerAdapter extends BaseAdapter implements ObservableAdapter { private static final String TAG = "CheckinListAdapter"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private LayoutInflater mInflater; private int mLayoutToInflate; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private Category mCategory; public CategoryPickerAdapter(Context context, RemoteResourceManager rrm, Category category) { super(); mCategory = category; mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.category_picker_list_item; mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); for (Category it : mCategory.getChildCategories()) { Uri photoUri = Uri.parse(it.getIconUrl()); File file = mRrm.getFile(photoUri); if (file != null) { if (System.currentTimeMillis() - file.lastModified() > FoursquaredSettings.CATEGORY_ICON_EXPIRATION) { mRrm.invalidate(photoUri); file = null; } } if (file == null) { mRrm.request(photoUri); } } } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.icon = (ImageView) convertView.findViewById(R.id.categoryPickerIcon); holder.name = (TextView) convertView.findViewById(R.id.categoryPickerName); holder.disclosure = (ImageView) convertView.findViewById(R.id.categoryPickerIconDisclosure); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } Category category = (Category) getItem(position); final Uri photoUri = Uri.parse(category.getIconUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.icon.setImageBitmap(bitmap); } catch (IOException e) { if (DEBUG) Log.e(TAG, "Error loading category icon.", e); } if (category.getChildCategories() != null && category.getChildCategories().size() > 0) { holder.disclosure.setVisibility(View.VISIBLE); } else { holder.disclosure.setVisibility(View.GONE); } holder.name.setText(category.getNodeName()); return convertView; } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } private static class ViewHolder { ImageView icon; TextView name; ImageView disclosure; } @Override public int getCount() { return mCategory.getChildCategories().size(); } @Override public Object getItem(int position) { return mCategory.getChildCategories().get(position); } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return true; } public static class CategoryFlat { private Category mCategory; private int mDepth; public CategoryFlat(Category category, int depth) { mCategory = category; mDepth = depth; } public Category getCategory() { return mCategory; } public int getDepth() { return mDepth; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import java.io.IOException; import java.util.Observable; import java.util.Observer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; /** * @date February 14, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class FriendSearchAddFriendAdapter extends BaseGroupAdapter<User> implements ObservableAdapter { private static final String TAG = ""; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private LayoutInflater mInflater; private int mLayoutToInflate; private ButtonRowClickHandler mClickListener; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); public FriendSearchAddFriendAdapter(Context context, ButtonRowClickHandler clickListener, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.add_friends_list_item; mClickListener = clickListener; mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } public FriendSearchAddFriendAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.clickable = (LinearLayout) convertView .findViewById(R.id.addFriendListItemClickableArea); holder.photo = (ImageView) convertView.findViewById(R.id.addFriendListItemPhoto); holder.name = (TextView) convertView.findViewById(R.id.addFriendListItemName); holder.add = (Button) convertView.findViewById(R.id.addFriendListItemAddButton); convertView.setTag(holder); holder.clickable.setOnClickListener(mOnClickListenerInfo); holder.add.setOnClickListener(mOnClickListenerAdd); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } User user = (User) getItem(position); final Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } } holder.clickable.setTag(new Integer(position)); holder.name.setText(user.getFirstname() + " " + (user.getLastname() != null ? user.getLastname() : "")); holder.add.setTag(new Integer(position)); return convertView; } private OnClickListener mOnClickListenerAdd = new OnClickListener() { @Override public void onClick(View v) { Integer position = (Integer) v.getTag(); mClickListener.onBtnClickAdd((User) getItem(position)); } }; private OnClickListener mOnClickListenerInfo = new OnClickListener() { @Override public void onClick(View v) { if (mClickListener != null) { Integer position = (Integer) v.getTag(); mClickListener.onInfoAreaClick((User) getItem(position)); } } }; public void removeItem(int position) throws IndexOutOfBoundsException { group.remove(position); notifyDataSetInvalidated(); } @Override public void setGroup(Group<User> g) { super.setGroup(g); for (int i = 0; i < g.size(); i++) { Uri photoUri = Uri.parse(g.get(i).getPhoto()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Fetcher got: " + data); mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } static class ViewHolder { LinearLayout clickable; ImageView photo; TextView name; Button add; } public interface ButtonRowClickHandler { public void onBtnClickAdd(User user); public void onInfoAreaClick(User user); } }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Venue; import android.content.Context; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract public class BaseVenueAdapter extends BaseGroupAdapter<Venue> { public BaseVenueAdapter(Context context) { super(context); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @date March 9, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class HistoryListAdapter extends BaseCheckinAdapter implements ObservableAdapter { private LayoutInflater mInflater; private RemoteResourceManager mRrm; private Handler mHandler; private RemoteResourceManagerObserver mResourcesObserver; public HistoryListAdapter(Context context, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mHandler = new Handler(); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.history_list_item, null); holder = new ViewHolder(); holder.icon = (ImageView) convertView.findViewById(R.id.icon); holder.firstLine = (TextView) convertView.findViewById(R.id.firstLine); holder.shoutTextView = (TextView) convertView.findViewById(R.id.shoutTextView); holder.timeTextView = (TextView) convertView.findViewById(R.id.timeTextView); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } Checkin checkin = (Checkin) getItem(position); if (checkin.getVenue() != null) { holder.firstLine.setText(checkin.getVenue().getName()); holder.firstLine.setVisibility(View.VISIBLE); Category category = checkin.getVenue().getCategory(); if (category != null) { Uri photoUri = Uri.parse(category.getIconUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.icon.setImageBitmap(bitmap); } catch (IOException e) { holder.icon.setImageResource(R.drawable.category_none); } } else { holder.icon.setImageResource(R.drawable.category_none); } } else { // This is going to be a shout then. holder.icon.setImageResource(R.drawable.ic_menu_shout); holder.firstLine.setVisibility(View.GONE); } if (TextUtils.isEmpty(checkin.getShout()) == false) { holder.shoutTextView.setText(checkin.getShout()); holder.shoutTextView.setVisibility(View.VISIBLE); } else { holder.shoutTextView.setVisibility(View.GONE); } holder.timeTextView.setText( StringFormatters.getRelativeTimeSpanString(checkin.getCreated())); return convertView; } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } private static class ViewHolder { ImageView icon; TextView firstLine; TextView shoutTextView; TextView timeTextView; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquared.R; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; /** * @date June 24, 2010 * @author Mark Wyszomierski (mark@gmail.com) */ public class MapCalloutView extends LinearLayout { private TextView mTextViewTitle; private TextView mTextViewMessage; public MapCalloutView(Context context) { super(context); } public MapCalloutView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void onFinishInflate() { super.onFinishInflate(); ((Activity)getContext()).getLayoutInflater().inflate(R.layout.map_callout_view, this); mTextViewTitle = (TextView)findViewById(R.id.title); mTextViewMessage = (TextView)findViewById(R.id.message); } public void setTitle(String title) { mTextViewTitle.setText(title); } public void setMessage(String message) { mTextViewMessage.setText(message); } }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.CheckinTimestampSort; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import com.joelapenna.foursquared.util.UiUtil; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -Added local hashmap of cached timestamps processed at setGroup() * time to conform to the same timestamp conventions other foursquare * apps are using. */ public class CheckinListAdapter extends BaseCheckinAdapter implements ObservableAdapter { private LayoutInflater mInflater; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private HashMap<String, String> mCachedTimestamps; private boolean mIsSdk3; public CheckinListAdapter(Context context, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mCachedTimestamps = new HashMap<String, String>(); mRrm.addObserver(mResourcesObserver); mIsSdk3 = UiUtil.sdkVersion() == 3; } public void removeObserver() { mHandler.removeCallbacks(mUpdatePhotos); mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. final ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(R.layout.checkin_list_item, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.photo = (ImageView) convertView.findViewById(R.id.photo); holder.firstLine = (TextView) convertView.findViewById(R.id.firstLine); holder.secondLine = (TextView) convertView.findViewById(R.id.secondLine); holder.timeTextView = (TextView) convertView.findViewById(R.id.timeTextView); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } Checkin checkin = (Checkin) getItem(position); final User user = checkin.getUser(); final Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } } String checkinMsgLine1 = StringFormatters.getCheckinMessageLine1(checkin, true); String checkinMsgLine2 = StringFormatters.getCheckinMessageLine2(checkin); String checkinMsgLine3 = mCachedTimestamps.get(checkin.getId()); holder.firstLine.setText(checkinMsgLine1); if (!TextUtils.isEmpty(checkinMsgLine2)) { holder.secondLine.setVisibility(View.VISIBLE); holder.secondLine.setText(checkinMsgLine2); } else { if (!mIsSdk3) { holder.secondLine.setVisibility(View.GONE); } else { holder.secondLine.setVisibility(View.INVISIBLE); } } holder.timeTextView.setText(checkinMsgLine3); return convertView; } @Override public void setGroup(Group<Checkin> g) { super.setGroup(g); mCachedTimestamps.clear(); CheckinTimestampSort timestamps = new CheckinTimestampSort(); for (Checkin it : g) { Uri photoUri = Uri.parse(it.getUser().getPhoto()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } Date date = new Date(it.getCreated()); if (date.after(timestamps.getBoundaryRecent())) { mCachedTimestamps.put(it.getId(), StringFormatters.getRelativeTimeSpanString(it.getCreated()).toString()); } else if (date.after(timestamps.getBoundaryToday())) { mCachedTimestamps.put(it.getId(), StringFormatters.getTodayTimeString(it.getCreated())); } else if (date.after(timestamps.getBoundaryYesterday())) { mCachedTimestamps.put(it.getId(), StringFormatters.getYesterdayTimeString(it.getCreated())); } else { mCachedTimestamps.put(it.getId(), StringFormatters.getOlderTimeString(it.getCreated())); } } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(mUpdatePhotos); } } private Runnable mUpdatePhotos = new Runnable() { @Override public void run() { notifyDataSetChanged(); } }; private static class ViewHolder { ImageView photo; TextView firstLine; TextView secondLine; TextView timeTextView; } }
Java
package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.UserUtils; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.net.Uri; import android.util.AttributeSet; import android.view.View; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Observable; import java.util.Observer; /** * A single horizontal strip of user photo views. Expected to be used from * xml resource, needs more work to make this a robust and generic control. * * @date September 15, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PhotoStrip extends View implements ObservableAdapter { private int mPhotoSize; private int mPhotoSpacing; private int mPhotoBorder; private int mPhotoBorderStroke; private int mPhotoBorderColor; private int mPhotoBorderStrokeColor; private Group<User> mTypes; private Map<String, Bitmap> mCachedBitmaps = new HashMap<String, Bitmap>(); private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; public PhotoStrip(Context context) { super(context); } public PhotoStrip(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PhotoStrip, 0, 0); mPhotoSize = a.getDimensionPixelSize(R.styleable.PhotoStrip_photoSize, 44); mPhotoSpacing = a.getDimensionPixelSize(R.styleable.PhotoStrip_photoSpacing, 10); mPhotoBorder = a.getDimensionPixelSize(R.styleable.PhotoStrip_photoBorder, 2); mPhotoBorderStroke = a.getDimensionPixelSize(R.styleable.PhotoStrip_photoBorderStroke, 0); mPhotoBorderColor = a.getColor(R.styleable.PhotoStrip_photoBorderColor, 0xFFFFFFFF); mPhotoBorderStrokeColor = a.getColor(R.styleable.PhotoStrip_photoBorderStrokeColor, 0xFFD0D0D); a.recycle(); } public void setUsersAndRemoteResourcesManager(Group<User> users, RemoteResourceManager rrm) { mTypes = users; mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); invalidate(); } public void setCheckinsAndRemoteResourcesManager(Group<Checkin> checkins, RemoteResourceManager rrm) { Group<User> users = new Group<User>(); for (Checkin it : checkins) { if (it.getUser() != null) { users.add(it.getUser()); } } setUsersAndRemoteResourcesManager(users, rrm); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mRrm != null && mResourcesObserver != null) { mRrm.deleteObserver(mResourcesObserver); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG); paint.setAntiAlias(true); int width = getWidth(); int sum = mPhotoSize + mPhotoSpacing; int index = 0; while (sum < width) { if (mTypes == null || index >= mTypes.size()) { break; } Rect rcDst = new Rect( index * (mPhotoSize + mPhotoSpacing), 0, index * (mPhotoSize + mPhotoSpacing) + mPhotoSize, mPhotoSize); paint.setColor(mPhotoBorderStrokeColor); canvas.drawRect(rcDst, paint); rcDst.inset(mPhotoBorderStroke, mPhotoBorderStroke); paint.setColor(mPhotoBorderColor); canvas.drawRect(rcDst, paint); rcDst.inset(mPhotoBorder, mPhotoBorder); FoursquareType type = mTypes.get(index); Bitmap bmp = fetchBitmapForUser(type); if (bmp != null) { Rect rcSrc = new Rect(0, 0, bmp.getWidth(), bmp.getHeight()); canvas.drawBitmap(bmp, rcSrc, rcDst, paint); } sum += (mPhotoSize + mPhotoSpacing); index++; } } private Bitmap fetchBitmapForUser(FoursquareType type) { User user = null; if (type instanceof User) { user = (User)type; } else if (type instanceof Checkin) { Checkin checkin = (Checkin)type; user = checkin.getUser(); if (user == null) { return null; } } else { throw new RuntimeException("PhotoStrip can only accept Users or Checkins."); } String photoUrl = user.getPhoto(); if (mCachedBitmaps.containsKey(photoUrl)) { return mCachedBitmaps.get(photoUrl); } Uri uriPhoto = Uri.parse(photoUrl); if (mRrm.exists(uriPhoto)) { try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(photoUrl))); mCachedBitmaps.put(photoUrl, bitmap); return bitmap; } catch (IOException e) { } } else { mRrm.request(uriPhoto); } return BitmapFactory.decodeResource(getResources(), UserUtils.getDrawableByGenderForUserThumbnail(user)); } /** * @see android.view.View#measure(int, int) */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension( measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } /** * Determines the width of this view * @param measureSpec A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be. result = specSize; } else { if (specMode == MeasureSpec.AT_MOST) { // Use result. } else { // Use result. } } return result; } private int measureHeight(int measureSpec) { // We should be exactly as high as the specified photo size. // An exception would be if we have zero photos to display, // we're not dealing with that at the moment. return mPhotoSize + getPaddingTop() + getPaddingBottom(); } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { postInvalidate(); } } }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Mayor; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class MayorListAdapter extends BaseMayorAdapter implements ObservableAdapter { private static final String TAG = "MayorListAdapter"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private LayoutInflater mInflater; private RemoteResourceManager mRrm; private Handler mHandler = new Handler(); private RemoteResourceManagerObserver mResourcesObserver; public MayorListAdapter(Context context, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. final ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(R.layout.mayor_list_item, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.photo = (ImageView)convertView.findViewById(R.id.photo); holder.firstLine = (TextView)convertView.findViewById(R.id.firstLine); holder.secondLine = (TextView)convertView.findViewById(R.id.mayorMessageTextView); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder)convertView.getTag(); } Mayor mayor = (Mayor)getItem(position); final User user = mayor.getUser(); final Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } } holder.firstLine.setText(mayor.getUser().getFirstname()); holder.secondLine.setText(mayor.getMessage()); return convertView; } @Override public void setGroup(Group<Mayor> g) { super.setGroup(g); for (int i = 0; i < g.size(); i++) { Uri photoUri = Uri.parse((g.get(i)).getUser().getPhoto()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Fetcher got: " + data); mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } private static class ViewHolder { ImageView photo; TextView firstLine; TextView secondLine; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; /** * Interface that our adapters can implement to release any observers they * may have registered with remote resources manager. Most of the adapters * register an observer in their constructor, but there is was no appropriate * place to release them. Parent activities can call this method in their * onPause(isFinishing()) block to properly release the observers. * * If the observers are not released, it will cause a memory leak. * * @date March 8, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public interface ObservableAdapter { public void removeObserver(); }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Badge; import com.joelapenna.foursquared.R; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; /** * @author jlapenna */ public class BadgeListAdapter extends BaseBadgeAdapter { private LayoutInflater mInflater; private int mLayoutToInflate; public BadgeListAdapter(Context context) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.badge_item; } public BadgeListAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.icon = (ImageView)convertView.findViewById(R.id.icon); holder.name = (TextView)convertView.findViewById(R.id.name); holder.description = (TextView)convertView.findViewById(R.id.description); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder)convertView.getTag(); } Badge badge = (Badge)getItem(position); holder.name.setText(badge.getName()); if (holder.description != null) { if (!TextUtils.isEmpty(badge.getDescription())) { holder.description.setText(badge.getDescription()); } else { holder.description.setText(""); } } return convertView; } static class ViewHolder { ImageView icon; TextView name; TextView description; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @date February 15, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class FriendRequestsAdapter extends BaseGroupAdapter<User> implements ObservableAdapter { private static final String TAG = "FriendRequestsAdapter"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private LayoutInflater mInflater; private int mLayoutToInflate; private ButtonRowClickHandler mClickListener; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private int mLoadedPhotoIndex; public FriendRequestsAdapter(Context context, ButtonRowClickHandler clickListener, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.friend_request_list_item; mClickListener = clickListener; mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mLoadedPhotoIndex = 0; mRrm.addObserver(mResourcesObserver); } public FriendRequestsAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } public void removeObserver() { mHandler.removeCallbacks(mRunnableLoadPhotos); mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.photo = (ImageView) convertView.findViewById(R.id.friendRequestListItemPhoto); holder.name = (TextView) convertView.findViewById(R.id.friendRequestListItemName); holder.add = (Button) convertView.findViewById(R.id.friendRequestApproveButton); holder.ignore = (Button) convertView.findViewById(R.id.friendRequestDenyButton); holder.clickable = (LinearLayout) convertView.findViewById(R.id.friendRequestListItemClickableArea); convertView.setTag(holder); holder.clickable.setOnClickListener(mOnClickListenerInfo); holder.add.setOnClickListener(mOnClickListenerApprove); holder.ignore.setOnClickListener(mOnClickListenerDeny); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } User user = (User) getItem(position); final Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } } holder.name.setText(user.getFirstname() + " " + (user.getLastname() != null ? user.getLastname() : "")); holder.clickable.setTag(new Integer(position)); holder.add.setTag(new Integer(position)); holder.ignore.setTag(new Integer(position)); return convertView; } private OnClickListener mOnClickListenerInfo = new OnClickListener() { @Override public void onClick(View v) { Integer position = (Integer) v.getTag(); mClickListener.onInfoAreaClick((User) getItem(position)); } }; private OnClickListener mOnClickListenerApprove = new OnClickListener() { @Override public void onClick(View v) { Integer position = (Integer) v.getTag(); mClickListener.onBtnClickAdd((User) getItem(position)); } }; private OnClickListener mOnClickListenerDeny = new OnClickListener() { @Override public void onClick(View v) { if (mClickListener != null) { Integer position = (Integer) v.getTag(); mClickListener.onBtnClickIgnore((User) getItem(position)); } } }; public void removeItem(int position) throws IndexOutOfBoundsException { group.remove(position); notifyDataSetInvalidated(); } @Override public void setGroup(Group<User> g) { super.setGroup(g); mLoadedPhotoIndex = 0; mHandler.postDelayed(mRunnableLoadPhotos, 10L); } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Fetcher got: " + data); mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } private Runnable mRunnableLoadPhotos = new Runnable() { @Override public void run() { if (mLoadedPhotoIndex < getCount()) { User user = (User)getItem(mLoadedPhotoIndex++); Uri photoUri = Uri.parse(user.getPhoto()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } mHandler.postDelayed(mRunnableLoadPhotos, 200L); } } }; static class ViewHolder { LinearLayout clickable; ImageView photo; TextView name; Button add; Button ignore; } public interface ButtonRowClickHandler { public void onInfoAreaClick(User user); public void onBtnClickAdd(User user); public void onBtnClickIgnore(User user); } }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import android.content.Context; import android.widget.BaseAdapter; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract class BaseGroupAdapter<T extends FoursquareType> extends BaseAdapter { Group<T> group = null; public BaseGroupAdapter(Context context) { } @Override public int getCount() { return (group == null) ? 0 : group.size(); } @Override public Object getItem(int position) { return group.get(position); } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return true; } @Override public boolean isEmpty() { return (group == null) ? true : group.isEmpty(); } public void setGroup(Group<T> g) { group = g; notifyDataSetInvalidated(); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.UserUtils; import android.content.Context; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; /** * * @date September 23, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class UserContactAdapter extends BaseAdapter { private LayoutInflater mInflater; private int mLayoutToInflate; private User mUser; private ArrayList<Action> mActions; public UserContactAdapter(Context context, User user) { super(); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.user_actions_list_item; mUser = user; mActions = new ArrayList<Action>(); if (user != null) { if (UserUtils.isFriend(user)) { if (TextUtils.isEmpty(mUser.getPhone()) == false) { mActions.add(new Action(context.getResources().getString( R.string.user_actions_activity_action_sms), R.drawable.user_action_text, Action.ACTION_ID_SMS, false)); } if (TextUtils.isEmpty(mUser.getEmail()) == false) { mActions.add(new Action(context.getResources().getString( R.string.user_actions_activity_action_email), R.drawable.user_action_email, Action.ACTION_ID_EMAIL, false)); } if (TextUtils.isEmpty(mUser.getEmail()) == false) { mActions.add(new Action(context.getResources().getString( R.string.user_actions_activity_action_phone), R.drawable.user_action_phone, Action.ACTION_ID_PHONE, false)); } } if (TextUtils.isEmpty(mUser.getTwitter()) == false) { mActions.add(new Action(context.getResources().getString( R.string.user_actions_activity_action_twitter), R.drawable.user_action_twitter, Action.ACTION_ID_TWITTER, true)); } if (TextUtils.isEmpty(mUser.getFacebook()) == false) { mActions.add(new Action(context.getResources().getString( R.string.user_actions_activity_action_facebook), R.drawable.user_action_facebook, Action.ACTION_ID_FACEBOOK, true)); } } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); } ImageView iv = (ImageView) convertView.findViewById(R.id.userActionsListItemIcon); TextView tv = (TextView) convertView.findViewById(R.id.userActionsListItemLabel); Action action = (Action) getItem(position); iv.setImageResource(action.getIconId()); tv.setText(action.getLabel()); return convertView; } @Override public int getCount() { return mActions.size(); } @Override public Object getItem(int position) { return mActions.get(position); } @Override public long getItemId(int position) { return position; } public static class Action { public static final int ACTION_ID_SMS = 0; public static final int ACTION_ID_EMAIL = 1; public static final int ACTION_ID_PHONE = 2; public static final int ACTION_ID_TWITTER = 3; public static final int ACTION_ID_FACEBOOK = 4; private String mLabel; private int mIconId; private int mActionId; private boolean mIsExternalAction; public Action(String label, int iconId, int actionId, boolean isExternalAction) { mLabel = label; mIconId = iconId; mActionId = actionId; mIsExternalAction = isExternalAction; } public String getLabel() { return mLabel; } public int getIconId() { return mIconId; } public int getActionId() { return mActionId; } public boolean getIsExternalAction() { return mIsExternalAction; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.HashSet; import java.util.Observable; import java.util.Observer; import java.util.Set; /** * @date March 8, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class FriendListAdapter extends BaseGroupAdapter<User> implements ObservableAdapter { private LayoutInflater mInflater; private int mLayoutToInflate; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private Set<String> mLaunchedPhotoFetches; public FriendListAdapter(Context context, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.friend_list_item; mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mLaunchedPhotoFetches = new HashSet<String>(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mHandler.removeCallbacks(mUpdatePhoto); mRrm.deleteObserver(mResourcesObserver); } public FriendListAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.photo = (ImageView) convertView.findViewById(R.id.friendListItemPhoto); holder.name = (TextView) convertView.findViewById(R.id.friendListItemName); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } User user = (User) getItem(position); Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } if (!mLaunchedPhotoFetches.contains(user.getId())) { mLaunchedPhotoFetches.add(user.getId()); mRrm.request(photoUri); } } holder.name.setText(user.getFirstname() + " " + (user.getLastname() != null ? user.getLastname() : "")); return convertView; } public void removeItem(int position) throws IndexOutOfBoundsException { group.remove(position); notifyDataSetInvalidated(); } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(mUpdatePhoto); } } private Runnable mUpdatePhoto = new Runnable() { @Override public void run() { notifyDataSetChanged(); } }; static class ViewHolder { ImageView photo; TextView name; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Tip; import android.content.Context; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract public class BaseTipAdapter extends BaseGroupAdapter<Tip> { public BaseTipAdapter(Context context) { super(context); } }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Stats; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import com.joelapenna.foursquared.util.VenueUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.File; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueListAdapter extends BaseVenueAdapter implements ObservableAdapter { private static final String TAG = "VenueListAdapter"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private LayoutInflater mInflater; private RemoteResourceManager mRrm; private Handler mHandler; private RemoteResourceManagerObserver mResourcesObserver; public VenueListAdapter(Context context, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mHandler = new Handler(); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } /** * Make a view to hold each row. * * @see android.widget.ListAdapter#getView(int, android.view.View, * android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(R.layout.venue_list_item, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.icon = (ImageView) convertView.findViewById(R.id.icon); holder.venueName = (TextView) convertView.findViewById(R.id.venueName); holder.locationLine1 = (TextView) convertView.findViewById(R.id.venueLocationLine1); holder.iconSpecial = (ImageView) convertView.findViewById(R.id.iconSpecialHere); holder.venueDistance = (TextView) convertView.findViewById(R.id.venueDistance); holder.iconTrending = (ImageView) convertView.findViewById(R.id.iconTrending); holder.venueCheckinCount = (TextView) convertView.findViewById(R.id.venueCheckinCount); holder.todoHere = (ImageView) convertView.findViewById(R.id.venueTodoCorner); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } // Check if the venue category icon exists on disk, if not default to a // venue pin icon. Venue venue = (Venue) getItem(position); Category category = venue.getCategory(); if (category != null) { Uri photoUri = Uri.parse(category.getIconUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.icon.setImageBitmap(bitmap); } catch (IOException e) { setDefaultVenueCategoryIcon(venue, holder); } } else { // If there is no category for this venue, fall back to the original // method of the // blue/grey pin depending on if the user has been there or not. setDefaultVenueCategoryIcon(venue, holder); } // Venue name. holder.venueName.setText(venue.getName()); // Venue street address (cross streets | city, state zip). if (!TextUtils.isEmpty(venue.getAddress())) { holder.locationLine1.setText(StringFormatters.getVenueLocationFull(venue)); } else { holder.locationLine1.setText(""); } // If there's a special here, show the special here icon. if (VenueUtils.getSpecialHere(venue)) { holder.iconSpecial.setVisibility(View.VISIBLE); } else { holder.iconSpecial.setVisibility(View.GONE); } // Show venue distance. if (venue.getDistance() != null) { holder.venueDistance.setText(venue.getDistance() + " meters"); } else { holder.venueDistance.setText(""); } // If more than two people here, then show trending text. Stats stats = venue.getStats(); if (stats != null && !stats.getHereNow().equals("0") && !stats.getHereNow().equals("1") && !stats.getHereNow().equals("2")) { holder.iconTrending.setVisibility(View.VISIBLE); holder.venueCheckinCount.setVisibility(View.VISIBLE); holder.venueCheckinCount.setText(stats.getHereNow() + " people here"); } else { holder.iconTrending.setVisibility(View.GONE); holder.venueCheckinCount.setVisibility(View.GONE); } // If we have a todo here, show the corner folded over. if (venue.getHasTodo()) { holder.todoHere.setVisibility(View.VISIBLE); } else { holder.todoHere.setVisibility(View.INVISIBLE); } return convertView; } private void setDefaultVenueCategoryIcon(Venue venue, ViewHolder holder) { holder.icon.setImageResource(R.drawable.category_none); } @Override public void setGroup(Group<Venue> g) { super.setGroup(g); for (Venue it : g) { // Start download of category icon if not already in the cache. // At the same time, check the age of each of these images, if // expired, delete and request a fresh copy. This should be // removed once category icon set urls are versioned. Category category = it.getCategory(); if (category != null) { Uri photoUri = Uri.parse(category.getIconUrl()); File file = mRrm.getFile(photoUri); if (file != null) { if (System.currentTimeMillis() - file.lastModified() > FoursquaredSettings.CATEGORY_ICON_EXPIRATION) { mRrm.invalidate(photoUri); file = null; } } if (file == null) { mRrm.request(photoUri); } } } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Fetcher got: " + data); mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } private static class ViewHolder { ImageView icon; TextView venueName; TextView locationLine1; ImageView iconSpecial; TextView venueDistance; ImageView iconTrending; TextView venueCheckinCount; ImageView todoHere; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import com.joelapenna.foursquared.util.TipUtils; import com.joelapenna.foursquared.util.UiUtil; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Observable; import java.util.Observer; /** * @date September 12, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TodosListAdapter extends BaseGroupAdapter<Todo> implements ObservableAdapter { private LayoutInflater mInflater; private int mLayoutToInflate; private Resources mResources; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private int mLoadedPhotoIndex; private Map<String, String> mCachedTimestamps; private boolean mDisplayVenueTitles; private int mSdk; public TodosListAdapter(Context context, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.todo_list_item; mResources = context.getResources(); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mLoadedPhotoIndex = 0; mCachedTimestamps = new HashMap<String, String>(); mDisplayVenueTitles = true; mSdk = UiUtil.sdkVersion(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mHandler.removeCallbacks(mUpdatePhotos); mHandler.removeCallbacks(mRunnableLoadPhotos); mRrm.deleteObserver(mResourcesObserver); } public TodosListAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.photo = (ImageView) convertView.findViewById(R.id.ivVenueCategory); holder.title = (TextView) convertView.findViewById(R.id.tvTitle); holder.body = (TextView) convertView.findViewById(R.id.tvBody); holder.dateAndAuthor = (TextView) convertView.findViewById(R.id.tvDateAndAuthor); holder.corner = (ImageView) convertView.findViewById(R.id.ivTipCorner); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } Todo todo = (Todo)getItem(position); Tip tip = todo.getTip(); if (tip != null) { if (mDisplayVenueTitles && tip.getVenue() != null) { holder.title.setText("@ " + tip.getVenue().getName()); holder.title.setVisibility(View.VISIBLE); } else { holder.title.setVisibility(View.GONE); holder.body.setPadding( holder.body.getPaddingLeft(), holder.title.getPaddingTop(), holder.body.getPaddingRight(), holder.body.getPaddingBottom()); } if (tip.getVenue() != null && tip.getVenue().getCategory() != null) { Uri photoUri = Uri.parse(tip.getVenue().getCategory().getIconUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { holder.photo.setImageResource(R.drawable.category_none); } } else { holder.photo.setImageResource(R.drawable.category_none); } if (!TextUtils.isEmpty(tip.getText())) { holder.body.setText(tip.getText()); holder.body.setVisibility(View.VISIBLE); } else { if (mSdk > 3) { holder.body.setVisibility(View.GONE); } else { holder.body.setText(""); holder.body.setVisibility(View.INVISIBLE); } } if (tip.getUser() != null) { holder.dateAndAuthor.setText( holder.dateAndAuthor.getText() + mResources.getString( R.string.tip_age_via, StringFormatters.getUserFullName(tip.getUser()))); } if (TipUtils.isDone(tip)) { holder.corner.setVisibility(View.VISIBLE); holder.corner.setImageResource(R.drawable.tip_list_item_corner_done); } else if (TipUtils.isTodo(tip)) { holder.corner.setVisibility(View.VISIBLE); holder.corner.setImageResource(R.drawable.tip_list_item_corner_todo); } else { holder.corner.setVisibility(View.GONE); } } else { holder.title.setText(""); holder.body.setText(""); holder.corner.setVisibility(View.VISIBLE); holder.corner.setImageResource(R.drawable.tip_list_item_corner_todo); holder.photo.setImageResource(R.drawable.category_none); } holder.dateAndAuthor.setText(mResources.getString( R.string.todo_added_date, mCachedTimestamps.get(todo.getId()))); return convertView; } public void removeItem(int position) throws IndexOutOfBoundsException { group.remove(position); notifyDataSetInvalidated(); } @Override public void setGroup(Group<Todo> g) { super.setGroup(g); mLoadedPhotoIndex = 0; mHandler.postDelayed(mRunnableLoadPhotos, 10L); mCachedTimestamps.clear(); for (Todo it : g) { String formatted = StringFormatters.getTipAge(mResources, it.getCreated()); mCachedTimestamps.put(it.getId(), formatted); } } public void setDisplayTodoVenueTitles(boolean displayTodoVenueTitles) { mDisplayVenueTitles = displayTodoVenueTitles; } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(mUpdatePhotos); } } private Runnable mUpdatePhotos = new Runnable() { @Override public void run() { notifyDataSetChanged(); } }; private Runnable mRunnableLoadPhotos = new Runnable() { @Override public void run() { if (mLoadedPhotoIndex < getCount()) { Todo todo = (Todo)getItem(mLoadedPhotoIndex++); if (todo.getTip() != null && todo.getTip().getVenue() != null) { Venue venue = todo.getTip().getVenue(); if (venue.getCategory() != null) { Uri photoUri = Uri.parse(venue.getCategory().getIconUrl()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } mHandler.postDelayed(mRunnableLoadPhotos, 200L); } } } } }; static class ViewHolder { ImageView photo; TextView title; TextView body; TextView dateAndAuthor; ImageView corner; } }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Checkin; import android.content.Context; /** * @author Joe LaPenna (joe@joelapenna.com) */ public abstract class BaseCheckinAdapter extends BaseGroupAdapter<Checkin> { public BaseCheckinAdapter(Context context) { super(context); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Badge; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class BadgeWithIconListAdapter extends BadgeListAdapter implements ObservableAdapter { private static final String TAG = "BadgeWithIconListAdapter"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private RemoteResourceManager mRrm; private Handler mHandler = new Handler(); private RemoteResourceManagerObserver mResourcesObserver; /** * @param context * @param venues */ public BadgeWithIconListAdapter(Context context, RemoteResourceManager rrm) { super(context); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); } public BadgeWithIconListAdapter(Context context, RemoteResourceManager rrm, int layoutResource) { super(context, layoutResource); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); Badge badge = (Badge)getItem(position); ImageView icon = ((BadgeWithIconListAdapter.ViewHolder)view.getTag()).icon; try { Bitmap bitmap = BitmapFactory.decodeStream(// mRrm.getInputStream(Uri.parse(badge.getIcon()))); icon.setImageBitmap(bitmap); } catch (IOException e) { if (DEBUG) Log.d(TAG, "Could not load bitmap. We don't have it yet."); icon.setImageResource(R.drawable.default_on); } return view; } @Override public void setGroup(Group<Badge> g) { super.setGroup(g); for (int i = 0; i < group.size(); i++) { Uri photoUri = Uri.parse((group.get(i)).getIcon()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Fetcher got: " + data); mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.User; import android.content.Context; /** * @author Joe LaPenna (joe@joelapenna.com) */ public abstract class BaseUserAdapter extends BaseGroupAdapter<User> { public BaseUserAdapter(Context context) { super(context); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import com.joelapenna.foursquared.util.TipUtils; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Observable; import java.util.Observer; /** * @date August 31, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class TipsListAdapter extends BaseGroupAdapter<Tip> implements ObservableAdapter { private LayoutInflater mInflater; private int mLayoutToInflate; private Resources mResources; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private int mLoadedPhotoIndex; private boolean mDisplayTipVenueTitles; private Map<String, String> mCachedTimestamps; public TipsListAdapter(Context context, RemoteResourceManager rrm, int layout) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layout; mResources = context.getResources(); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mLoadedPhotoIndex = 0; mDisplayTipVenueTitles = true; mCachedTimestamps = new HashMap<String, String>(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mHandler.removeCallbacks(mUpdatePhotos); mHandler.removeCallbacks(mRunnableLoadPhotos); mRrm.deleteObserver(mResourcesObserver); } public TipsListAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.photo = (ImageView) convertView.findViewById(R.id.icon); holder.title = (TextView) convertView.findViewById(R.id.tvTitle); holder.body = (TextView) convertView.findViewById(R.id.tvBody); holder.dateAndAuthor = (TextView) convertView.findViewById(R.id.tvDateAndAuthor); //holder.friendCountTodoImg = (ImageView) convertView.findViewById(R.id.ivFriendCountAsTodo); //holder.friendCountTodo = (TextView) convertView.findViewById(R.id.tvFriendCountAsTodo); holder.friendCountCompletedImg = (ImageView) convertView.findViewById(R.id.ivFriendCountCompleted); holder.friendCountCompleted = (TextView) convertView.findViewById(R.id.tvFriendCountCompleted); holder.corner = (ImageView) convertView.findViewById(R.id.ivTipCorner); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } Tip tip = (Tip) getItem(position); User user = tip.getUser(); if (user != null) { Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } } } else { Venue venue = tip.getVenue(); Category category = venue.getCategory(); if (category != null) { holder.photo.setBackgroundDrawable(null); Uri photoUri = Uri.parse(category.getIconUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { holder.photo.setImageResource(R.drawable.category_none); } } else { // If there is no category for this venue, fall back to the original // method of the // blue/grey pin depending on if the user has been there or not. holder.photo.setImageResource(R.drawable.category_none); } } if (mDisplayTipVenueTitles && tip.getVenue() != null) { holder.title.setText("@ " + tip.getVenue().getName()); holder.title.setVisibility(View.VISIBLE); } else { holder.title.setVisibility(View.GONE); holder.body.setPadding( holder.body.getPaddingLeft(), holder.title.getPaddingTop(), holder.body.getPaddingRight(), holder.title.getPaddingBottom()); } holder.body.setText(tip.getText()); holder.dateAndAuthor.setText(mCachedTimestamps.get(tip.getId())); if (user != null) { holder.dateAndAuthor.setText( holder.dateAndAuthor.getText() + mResources.getString( R.string.tip_age_via, StringFormatters.getUserFullName(user))); } /* if (tip.getStats().getTodoCount() > 0) { holder.friendCountTodoImg.setVisibility(View.VISIBLE); holder.friendCountTodo.setVisibility(View.VISIBLE); holder.friendCountTodo.setText(String.valueOf(tip.getStats().getTodoCount())); } else { holder.friendCountTodoImg.setVisibility(View.GONE); holder.friendCountTodo.setVisibility(View.GONE); } */ if (tip.getStats().getDoneCount() > 0) { holder.friendCountCompletedImg.setVisibility(View.VISIBLE); holder.friendCountCompleted.setVisibility(View.VISIBLE); holder.friendCountCompleted.setText(String.valueOf(tip.getStats().getDoneCount())); } else { holder.friendCountCompletedImg.setVisibility(View.GONE); holder.friendCountCompleted.setVisibility(View.GONE); } if (TipUtils.isDone(tip)) { holder.corner.setVisibility(View.VISIBLE); holder.corner.setImageResource(R.drawable.tip_list_item_corner_done); } else if (TipUtils.isTodo(tip)) { holder.corner.setVisibility(View.VISIBLE); holder.corner.setImageResource(R.drawable.tip_list_item_corner_todo); } else { holder.corner.setVisibility(View.GONE); } return convertView; } public void removeItem(int position) throws IndexOutOfBoundsException { group.remove(position); notifyDataSetInvalidated(); } @Override public void setGroup(Group<Tip> g) { super.setGroup(g); mLoadedPhotoIndex = 0; mHandler.postDelayed(mRunnableLoadPhotos, 10L); mCachedTimestamps.clear(); for (Tip it : g) { String formatted = StringFormatters.getTipAge(mResources, it.getCreated()); mCachedTimestamps.put(it.getId(), formatted); } } public void setDisplayTipVenueTitles(boolean displayTipVenueTitles) { mDisplayTipVenueTitles = displayTipVenueTitles; } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(mUpdatePhotos); } } private Runnable mUpdatePhotos = new Runnable() { @Override public void run() { notifyDataSetChanged(); } }; private Runnable mRunnableLoadPhotos = new Runnable() { @Override public void run() { if (mLoadedPhotoIndex < getCount()) { Tip tip = (Tip)getItem(mLoadedPhotoIndex++); if (tip.getUser() != null) { Uri photoUri = Uri.parse(tip.getUser().getPhoto()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } mHandler.postDelayed(mRunnableLoadPhotos, 200L); } } } }; static class ViewHolder { ImageView photo; TextView title; TextView body; TextView dateAndAuthor; //ImageView friendCountTodoImg; //TextView friendCountTodo; ImageView friendCountCompletedImg; TextView friendCountCompleted; ImageView corner; } }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Mayor; import android.content.Context; /** * @author Joe LaPenna (joe@joelapenna.com) */ public abstract class BaseMayorAdapter extends BaseGroupAdapter<Mayor> { public BaseMayorAdapter(Context context) { super(context); } }
Java
/* Copyright 2008 Jeff Sharkey * * From: http://www.jsharkey.org/blog/2008/08/18/separating-lists-with-headers-in-android-09/ */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquared.R; import android.content.Context; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import java.util.LinkedHashMap; import java.util.Map; public class SeparatedListAdapter extends BaseAdapter implements ObservableAdapter { public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>(); public final ArrayAdapter<String> headers; public final static int TYPE_SECTION_HEADER = 0; public SeparatedListAdapter(Context context) { super(); headers = new ArrayAdapter<String>(context, R.layout.list_header); } public SeparatedListAdapter(Context context, int layoutId) { super(); headers = new ArrayAdapter<String>(context, layoutId); } public void addSection(String section, Adapter adapter) { this.headers.add(section); this.sections.put(section, adapter); // Register an observer so we can call notifyDataSetChanged() when our // children adapters are modified, otherwise no change will be visible. adapter.registerDataSetObserver(mDataSetObserver); } public void removeObserver() { // Notify all our children that they should release their observers too. for (Map.Entry<String, Adapter> it : sections.entrySet()) { if (it.getValue() instanceof ObservableAdapter) { ObservableAdapter adapter = (ObservableAdapter)it.getValue(); adapter.removeObserver(); } } } public void clear() { headers.clear(); sections.clear(); notifyDataSetInvalidated(); } @Override public Object getItem(int position) { for (Object section : this.sections.keySet()) { Adapter adapter = sections.get(section); int size = adapter.getCount() + 1; // check if position inside this section if (position == 0) return section; if (position < size) return adapter.getItem(position - 1); // otherwise jump into next section position -= size; } return null; } @Override public int getCount() { // total together all sections, plus one for each section header int total = 0; for (Adapter adapter : this.sections.values()) total += adapter.getCount() + 1; return total; } @Override public int getViewTypeCount() { // assume that headers count as one, then total all sections int total = 1; for (Adapter adapter : this.sections.values()) total += adapter.getViewTypeCount(); return total; } @Override public int getItemViewType(int position) { int type = 1; for (Object section : this.sections.keySet()) { Adapter adapter = sections.get(section); int size = adapter.getCount() + 1; // check if position inside this section if (position == 0) return TYPE_SECTION_HEADER; if (position < size) return type + adapter.getItemViewType(position - 1); // otherwise jump into next section position -= size; type += adapter.getViewTypeCount(); } return -1; } @Override public boolean areAllItemsEnabled() { return false; } @Override public boolean isEnabled(int position) { return (getItemViewType(position) != TYPE_SECTION_HEADER); } @Override public boolean isEmpty() { return getCount() == 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { int sectionnum = 0; for (Object section : this.sections.keySet()) { Adapter adapter = sections.get(section); int size = adapter.getCount() + 1; if (position == 0) return headers.getView(sectionnum, convertView, parent); if (position < size) return adapter.getView(position - 1, convertView, parent); // otherwise jump into next section position -= size; sectionnum++; } return null; } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return false; } private DataSetObserver mDataSetObserver = new DataSetObserver() { @Override public void onChanged() { notifyDataSetChanged(); } }; }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquared.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.StateListDrawable; import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.List; /** * A multi-button control which can only have one pressed button at * any given time. Its functionality is quite similar to a tab control. * Tabs can't be skinned in android 1.5, and our main frame is a tab * host - which causes some different android problems, thus this control * was created. * * @date September 15, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class SegmentedButton extends LinearLayout { private StateListDrawable mBgLeftOn; private StateListDrawable mBgRightOn; private StateListDrawable mBgCenterOn; private StateListDrawable mBgLeftOff; private StateListDrawable mBgRightOff; private StateListDrawable mBgCenterOff; private int mSelectedButtonIndex = 0; private List<String> mButtonTitles = new ArrayList<String>(); private int mColorOnStart; private int mColorOnEnd; private int mColorOffStart; private int mColorOffEnd; private int mColorSelectedStart; private int mColorSelectedEnd; private int mColorStroke; private int mStrokeWidth; private int mCornerRadius; private int mTextStyle; private int mBtnPaddingTop; private int mBtnPaddingBottom; private OnClickListenerSegmentedButton mOnClickListenerExternal; public SegmentedButton(Context context) { super(context); } public SegmentedButton(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SegmentedButton, 0, 0); CharSequence btnText1 = a.getString(R.styleable.SegmentedButton_btnText1); CharSequence btnText2 = a.getString(R.styleable.SegmentedButton_btnText2); if (btnText1 != null) { mButtonTitles.add(btnText1.toString()); } if (btnText2 != null) { mButtonTitles.add(btnText2.toString()); } mColorOnStart = a.getColor(R.styleable.SegmentedButton_gradientColorOnStart, 0xFF0000); mColorOnEnd = a.getColor(R.styleable.SegmentedButton_gradientColorOnEnd, 0xFF0000); mColorOffStart = a.getColor(R.styleable.SegmentedButton_gradientColorOffStart, 0xFF0000); mColorOffEnd = a.getColor(R.styleable.SegmentedButton_gradientColorOffEnd, 0xFF0000); mColorStroke = a.getColor(R.styleable.SegmentedButton_strokeColor, 0xFF0000); mColorSelectedEnd = a.getColor(R.styleable.SegmentedButton_gradientColorSelectedEnd, 0xFF0000); mColorSelectedStart = a.getColor(R.styleable.SegmentedButton_gradientColorSelectedStart, 0xFF0000); mStrokeWidth = a.getDimensionPixelSize(R.styleable.SegmentedButton_strokeWidth, 1); mCornerRadius = a.getDimensionPixelSize(R.styleable.SegmentedButton_cornerRadius, 4); mTextStyle = a.getResourceId(R.styleable.SegmentedButton_textStyle, -1); mBtnPaddingTop = a.getDimensionPixelSize(R.styleable.SegmentedButton_btnPaddingTop, 0); mBtnPaddingBottom = a.getDimensionPixelSize(R.styleable.SegmentedButton_btnPaddingBottom, 0); a.recycle(); buildDrawables(mColorOnStart, mColorOnEnd, mColorOffStart, mColorOffEnd, mColorSelectedStart, mColorSelectedEnd, mCornerRadius, mColorStroke, mStrokeWidth); if (mButtonTitles.size() > 0) { _addButtons(new String[mButtonTitles.size()]); } } public void clearButtons() { removeAllViews(); } public void addButtons(String ... titles) { _addButtons(titles); } private void _addButtons(String[] titles) { for (int i = 0; i < titles.length; i++) { Button button = new Button(getContext()); button.setText(titles[i]); button.setTag(new Integer(i)); button.setOnClickListener(mOnClickListener); if (mTextStyle != -1) { button.setTextAppearance(getContext(), mTextStyle); } if (titles.length == 1) { // Don't use a segmented button with one button. return; } else if (titles.length == 2) { if (i == 0) { button.setBackgroundDrawable(mBgLeftOff); } else { button.setBackgroundDrawable(mBgRightOn); } } else { if (i == 0) { button.setBackgroundDrawable(mBgLeftOff); } else if (i == titles.length-1) { button.setBackgroundDrawable(mBgRightOn); } else { button.setBackgroundDrawable(mBgCenterOn); } } LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams( 0, LinearLayout.LayoutParams.WRAP_CONTENT, 1); addView(button, llp); button.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom); } } private void buildDrawables(int colorOnStart, int colorOnEnd, int colorOffStart, int colorOffEnd, int colorSelectedStart, int colorSelectedEnd, float crad, int strokeColor, int strokeWidth) { // top-left, top-right, bottom-right, bottom-left float[] radiiLeft = new float[] { crad, crad, 0, 0, 0, 0, crad, crad }; float[] radiiRight = new float[] { 0, 0, crad, crad, crad, crad, 0, 0 }; float[] radiiCenter = new float[] { 0, 0, 0, 0, 0, 0, 0, 0 }; GradientDrawable leftOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor); leftOn.setCornerRadii(radiiLeft); GradientDrawable leftOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor); leftOff.setCornerRadii(radiiLeft); GradientDrawable leftSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor); leftSelected.setCornerRadii(radiiLeft); GradientDrawable rightOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor); rightOn.setCornerRadii(radiiRight); GradientDrawable rightOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor); rightOff.setCornerRadii(radiiRight); GradientDrawable rightSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor); rightSelected.setCornerRadii(radiiRight); GradientDrawable centerOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor); centerOn.setCornerRadii(radiiCenter); GradientDrawable centerOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor); centerOff.setCornerRadii(radiiCenter); GradientDrawable centerSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor); centerSelected.setCornerRadii(radiiCenter); List<int[]> onStates = buildOnStates(); List<int[]> offStates = buildOffStates(); mBgLeftOn = new StateListDrawable(); mBgRightOn = new StateListDrawable(); mBgCenterOn = new StateListDrawable(); mBgLeftOff = new StateListDrawable(); mBgRightOff = new StateListDrawable(); mBgCenterOff = new StateListDrawable(); for (int[] it : onStates) { mBgLeftOn.addState(it, leftSelected); mBgRightOn.addState(it, rightSelected); mBgCenterOn.addState(it, centerSelected); mBgLeftOff.addState(it, leftSelected); mBgRightOff.addState(it, rightSelected); mBgCenterOff.addState(it, centerSelected); } for (int[] it : offStates) { mBgLeftOn.addState(it, leftOn); mBgRightOn.addState(it, rightOn); mBgCenterOn.addState(it, centerOn); mBgLeftOff.addState(it, leftOff); mBgRightOff.addState(it, rightOff); mBgCenterOff.addState(it, centerOff); } } private List<int[]> buildOnStates() { List<int[]> res = new ArrayList<int[]>(); res.add(new int[] { android.R.attr.state_focused, android.R.attr.state_enabled}); res.add(new int[] { android.R.attr.state_focused, android.R.attr.state_selected, android.R.attr.state_enabled}); res.add(new int[] { android.R.attr.state_pressed}); return res; } private List<int[]> buildOffStates() { List<int[]> res = new ArrayList<int[]>(); res.add(new int[] { android.R.attr.state_enabled}); res.add(new int[] { android.R.attr.state_selected, android.R.attr.state_enabled}); return res; } private GradientDrawable buildGradientDrawable(int colorStart, int colorEnd, int strokeWidth, int strokeColor) { GradientDrawable gd = new GradientDrawable( GradientDrawable.Orientation.TOP_BOTTOM, new int[] { colorStart, colorEnd }); gd.setShape(GradientDrawable.RECTANGLE); gd.setStroke(strokeWidth, strokeColor); return gd; } private OnClickListener mOnClickListener = new OnClickListener() { @Override public void onClick(View v) { Button btnNext = (Button)v; int btnNextIndex = ((Integer)btnNext.getTag()).intValue(); if (btnNextIndex == mSelectedButtonIndex) { return; } handleStateChange(mSelectedButtonIndex, btnNextIndex); if (mOnClickListenerExternal != null) { mOnClickListenerExternal.onClick(mSelectedButtonIndex); } } }; private void handleStateChange(int btnLastIndex, int btnNextIndex) { int count = getChildCount(); Button btnLast = (Button)getChildAt(btnLastIndex); Button btnNext = (Button)getChildAt(btnNextIndex); if (count < 3) { if (btnLastIndex == 0) { btnLast.setBackgroundDrawable(mBgLeftOn); } else { btnLast.setBackgroundDrawable(mBgRightOn); } if (btnNextIndex == 0) { btnNext.setBackgroundDrawable(mBgLeftOff); } else { btnNext.setBackgroundDrawable(mBgRightOff); } } else { if (btnLastIndex == 0) { btnLast.setBackgroundDrawable(mBgLeftOn); } else if (btnLastIndex == count-1) { btnLast.setBackgroundDrawable(mBgRightOn); } else { btnLast.setBackgroundDrawable(mBgCenterOn); } if (btnNextIndex == 0) { btnNext.setBackgroundDrawable(mBgLeftOff); } else if (btnNextIndex == count-1) { btnNext.setBackgroundDrawable(mBgRightOff); } else { btnNext.setBackgroundDrawable(mBgCenterOff); } } btnLast.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom); btnNext.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom); mSelectedButtonIndex = btnNextIndex; } public int getSelectedButtonIndex() { return mSelectedButtonIndex; } public void setPushedButtonIndex(int index) { handleStateChange(mSelectedButtonIndex, index); } public void setOnClickListener(OnClickListenerSegmentedButton listener) { mOnClickListenerExternal = listener; } public interface OnClickListenerSegmentedButton { public void onClick(int index); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.AddressBookEmailBuilder.ContactSimple; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; import java.util.List; /** * @date April 26, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class FriendSearchInviteNonFoursquareUserAdapter extends BaseAdapter implements ObservableAdapter { private LayoutInflater mInflater; private int mLayoutToInflate; private AdapterListener mAdapterListener; private List<ContactSimple> mEmailsAndNames; public FriendSearchInviteNonFoursquareUserAdapter( Context context, AdapterListener adapterListener) { super(); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.add_friends_invite_non_foursquare_user_list_item; mAdapterListener = adapterListener; mEmailsAndNames = new ArrayList<ContactSimple>(); } public void removeObserver() { } public FriendSearchInviteNonFoursquareUserAdapter(Context context, int layoutResource) { super(); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position == 0) { ViewHolderInviteAll holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.add_friends_invite_non_foursquare_all_list_item, null); holder = new ViewHolderInviteAll(); holder.addAll = (Button) convertView.findViewById(R.id.addFriendNonFoursquareAllListItemBtn); convertView.setTag(holder); } else { holder = (ViewHolderInviteAll) convertView.getTag(); } holder.addAll.setOnClickListener(mOnClickListenerInviteAll); } else { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.name = (TextView) convertView.findViewById(R.id.addFriendNonFoursquareUserListItemName); holder.email = (TextView) convertView.findViewById(R.id.addFriendNonFoursquareUserListItemEmail); holder.add = (Button) convertView.findViewById(R.id.addFriendNonFoursquareUserListItemBtn); convertView.setTag(holder); holder.add.setOnClickListener(mOnClickListenerInvite); } else { holder = (ViewHolder) convertView.getTag(); } holder.name.setText(mEmailsAndNames.get(position - 1).mName); holder.email.setText(mEmailsAndNames.get(position - 1).mEmail); holder.add.setTag(new Integer(position)); } return convertView; } private OnClickListener mOnClickListenerInvite = new OnClickListener() { @Override public void onClick(View v) { Integer position = (Integer) v.getTag(); mAdapterListener.onBtnClickInvite((ContactSimple) getItem(position)); } }; private OnClickListener mOnClickListenerInviteAll = new OnClickListener() { @Override public void onClick(View v) { mAdapterListener.onInviteAll(); } }; public void removeItem(int position) throws IndexOutOfBoundsException { mEmailsAndNames.remove(position); notifyDataSetInvalidated(); } public void setContacts(List<ContactSimple> contacts) { mEmailsAndNames = contacts; } static class ViewHolder { TextView name; TextView email; Button add; } static class ViewHolderInviteAll { Button addAll; } public interface AdapterListener { public void onBtnClickInvite(ContactSimple contact); public void onInfoAreaClick(ContactSimple contact); public void onInviteAll(); } @Override public int getCount() { if (mEmailsAndNames.size() > 0) { return mEmailsAndNames.size() + 1; } return 0; } @Override public Object getItem(int position) { if (position == 0) { return ""; } return mEmailsAndNames.get(position - 1); } @Override public long getItemId(int position) { return position; } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { if (position == 0) { return 0; } return 1; } }
Java
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Special; import com.joelapenna.foursquared.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * @author avolovoy */ public class SpecialListAdapter extends BaseGroupAdapter<Special> { private LayoutInflater mInflater; private int mLayoutToInflate; public SpecialListAdapter(Context context) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.special_list_item; } public SpecialListAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); // holder.icon = (ImageView)convertView.findViewById(R.id.icon); holder.message = (TextView)convertView.findViewById(R.id.message); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder)convertView.getTag(); } Special special = (Special)getItem(position); holder.message.setText(special.getMessage()); return convertView; } static class ViewHolder { // ImageView icon; TextView message; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Badge; import android.content.Context; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract public class BaseBadgeAdapter extends BaseGroupAdapter<Badge> { public BaseBadgeAdapter(Context context) { super(context); } }
Java
package com.joelapenna.foursquared.widget; import java.io.IOException; import java.util.Observable; import java.util.Observer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Score; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; public class ScoreListAdapter extends BaseGroupAdapter<Score> implements ObservableAdapter { private static final String TAG = "ScoreListAdapter"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final String PLUS = " +"; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private LayoutInflater mInflater; public ScoreListAdapter(Context context, RemoteResourceManager rrm) { super(context); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mInflater = LayoutInflater.from(context); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(R.layout.score_list_item, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.scoreIcon = (ImageView) convertView.findViewById(R.id.scoreIcon); holder.scoreDesc = (TextView) convertView.findViewById(R.id.scoreDesc); holder.scoreNum = (TextView) convertView.findViewById(R.id.scoreNum); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } Score score = (Score) getItem(position); holder.scoreDesc.setText(score.getMessage()); String scoreIconUrl = score.getIcon(); if (!TextUtils.isEmpty(scoreIconUrl)) { try { Bitmap bitmap = BitmapFactory.decodeStream(// mRrm.getInputStream(Uri.parse(score.getIcon()))); holder.scoreIcon.setImageBitmap(bitmap); } catch (IOException e) { if (DEBUG) Log.d(TAG, "Could not load bitmap. We don't have it yet."); holder.scoreIcon.setImageResource(R.drawable.default_on); } holder.scoreIcon.setVisibility(View.VISIBLE); holder.scoreNum.setText(PLUS + score.getPoints()); } else { holder.scoreIcon.setVisibility(View.INVISIBLE); holder.scoreNum.setText(score.getPoints()); } return convertView; } static class ViewHolder { ImageView scoreIcon; TextView scoreDesc; TextView scoreNum; } @Override public void setGroup(Group<Score> g) { super.setGroup(g); for (int i = 0; i < group.size(); i++) { Uri iconUri = Uri.parse((group.get(i)).getIcon()); if (!mRrm.exists(iconUri)) { mRrm.request(iconUri); } } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Fetcher got: " + data); mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } }
Java
/* * Copyright (C) 2010 Mark Wyszomierski * * Portions Copyright (C) 2009 Xtralogic, Inc. */ package com.joelapenna.foursquared; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /** * This is taken from the android-log-collector project here: * * http://code.google.com/p/android-log-collector/ * * so as we can dump the last set of system logs from the user's device at the * bottom of their feedback email. If they are reporting a crash, the logs * might show exceptions etc. Android 2.2+ reports this directly to the marketplace * for us so this will be phased out eventually. * * @date July 8, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class SendLogActivity extends Activity { public final static String TAG = "com.xtralogic.android.logcollector";//$NON-NLS-1$ private static final String FEEDBACK_EMAIL_ADDRESS = "crashreport-android@foursquare.com"; public static final String ACTION_SEND_LOG = "com.xtralogic.logcollector.intent.action.SEND_LOG";//$NON-NLS-1$ public static final String EXTRA_SEND_INTENT_ACTION = "com.xtralogic.logcollector.intent.extra.SEND_INTENT_ACTION";//$NON-NLS-1$ public static final String EXTRA_DATA = "com.xtralogic.logcollector.intent.extra.DATA";//$NON-NLS-1$ public static final String EXTRA_ADDITIONAL_INFO = "com.xtralogic.logcollector.intent.extra.ADDITIONAL_INFO";//$NON-NLS-1$ public static final String EXTRA_SHOW_UI = "com.xtralogic.logcollector.intent.extra.SHOW_UI";//$NON-NLS-1$ public static final String EXTRA_FILTER_SPECS = "com.xtralogic.logcollector.intent.extra.FILTER_SPECS";//$NON-NLS-1$ public static final String EXTRA_FORMAT = "com.xtralogic.logcollector.intent.extra.FORMAT";//$NON-NLS-1$ public static final String EXTRA_BUFFER = "com.xtralogic.logcollector.intent.extra.BUFFER";//$NON-NLS-1$ private static final String LINE_SEPARATOR = System.getProperty("line.separator"); final int MAX_LOG_MESSAGE_LENGTH = 100000; private AlertDialog mMainDialog; private Intent mSendIntent; private CollectLogTask mCollectLogTask; private ProgressDialog mProgressDialog; private String mAdditonalInfo; private String[] mFilterSpecs; private String mFormat; private String mBuffer; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); mSendIntent = new Intent(Intent.ACTION_SEND); mSendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.send_log_message_subject)); mSendIntent.setType("text/plain"); Foursquared foursquared = (Foursquared)getApplication(); StringBuilder body = new StringBuilder(); Resources res = getResources(); body.append(res.getString(R.string.feedback_more)); body.append(LINE_SEPARATOR); body.append(res.getString(R.string.feedback_question_how_to_reproduce)); body.append(LINE_SEPARATOR); body.append(LINE_SEPARATOR); body.append(res.getString(R.string.feedback_question_expected_output)); body.append(LINE_SEPARATOR); body.append(LINE_SEPARATOR); body.append(res.getString(R.string.feedback_question_additional_information)); body.append(LINE_SEPARATOR); body.append(LINE_SEPARATOR); body.append("--------------------------------------"); body.append(LINE_SEPARATOR); body.append("ver: "); body.append(foursquared.getVersion()); body.append(LINE_SEPARATOR); body.append("user: "); body.append(foursquared.getUserId()); body.append(LINE_SEPARATOR); body.append("p: "); body.append(Build.MODEL); body.append(LINE_SEPARATOR); body.append("os: "); body.append(Build.VERSION.RELEASE); body.append(LINE_SEPARATOR); body.append("build#: "); body.append(Build.DISPLAY); body.append(LINE_SEPARATOR); body.append(LINE_SEPARATOR); mSendIntent.putExtra(Intent.EXTRA_SUBJECT, res.getString(R.string.feedback_subject)); mSendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { FEEDBACK_EMAIL_ADDRESS }); mSendIntent.setType("message/rfc822"); mAdditonalInfo = body.toString(); mFormat = "process"; collectAndSendLog(); } @SuppressWarnings("unchecked") void collectAndSendLog(){ /*Usage: logcat [options] [filterspecs] options include: -s Set default filter to silent. Like specifying filterspec '*:s' -f <filename> Log to file. Default to stdout -r [<kbytes>] Rotate log every kbytes. (16 if unspecified). Requires -f -n <count> Sets max number of rotated logs to <count>, default 4 -v <format> Sets the log print format, where <format> is one of: brief process tag thread raw time threadtime long -c clear (flush) the entire log and exit -d dump the log and then exit (don't block) -g get the size of the log's ring buffer and exit -b <buffer> request alternate ring buffer ('main' (default), 'radio', 'events') -B output the log in binary filterspecs are a series of <tag>[:priority] where <tag> is a log component tag (or * for all) and priority is: V Verbose D Debug I Info W Warn E Error F Fatal S Silent (supress all output) '*' means '*:d' and <tag> by itself means <tag>:v If not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS. If no filterspec is found, filter defaults to '*:I' If not specified with -v, format is set from ANDROID_PRINTF_LOG or defaults to "brief"*/ ArrayList<String> list = new ArrayList<String>(); if (mFormat != null){ list.add("-v"); list.add(mFormat); } if (mBuffer != null){ list.add("-b"); list.add(mBuffer); } if (mFilterSpecs != null){ for (String filterSpec : mFilterSpecs){ list.add(filterSpec); } } mCollectLogTask = (CollectLogTask) new CollectLogTask().execute(list); } private class CollectLogTask extends AsyncTask<ArrayList<String>, Void, StringBuilder>{ @Override protected void onPreExecute(){ showProgressDialog(getString(R.string.send_log_acquiring_log_progress_dialog_message)); } @Override protected StringBuilder doInBackground(ArrayList<String>... params){ final StringBuilder log = new StringBuilder(); try{ ArrayList<String> commandLine = new ArrayList<String>(); commandLine.add("logcat");//$NON-NLS-1$ commandLine.add("-d");//$NON-NLS-1$ ArrayList<String> arguments = ((params != null) && (params.length > 0)) ? params[0] : null; if (null != arguments){ commandLine.addAll(arguments); } Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0])); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = bufferedReader.readLine()) != null){ log.append(line); log.append(LINE_SEPARATOR); } } catch (IOException e){ Log.e(TAG, "CollectLogTask.doInBackground failed", e);//$NON-NLS-1$ } return log; } @Override protected void onPostExecute(StringBuilder log){ if (null != log){ //truncate if necessary int keepOffset = Math.max(log.length() - MAX_LOG_MESSAGE_LENGTH, 0); if (keepOffset > 0){ log.delete(0, keepOffset); } if (mAdditonalInfo != null){ log.insert(0, mAdditonalInfo); } mSendIntent.putExtra(Intent.EXTRA_TEXT, log.toString()); startActivity(Intent.createChooser(mSendIntent, getString(R.string.send_log_chooser_title))); dismissProgressDialog(); dismissMainDialog(); finish(); } else{ dismissProgressDialog(); showErrorDialog(getString(R.string.send_log_failed_to_get_log_message)); } } } void showErrorDialog(String errorMessage){ new AlertDialog.Builder(this) .setTitle(getString(R.string.app_name)) .setMessage(errorMessage) .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int whichButton){ finish(); } }) .show(); } void dismissMainDialog(){ if (null != mMainDialog && mMainDialog.isShowing()){ mMainDialog.dismiss(); mMainDialog = null; } } void showProgressDialog(String message){ mProgressDialog = new ProgressDialog(this); mProgressDialog.setIndeterminate(true); mProgressDialog.setMessage(message); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog){ cancellCollectTask(); finish(); } }); mProgressDialog.show(); } private void dismissProgressDialog(){ if (null != mProgressDialog && mProgressDialog.isShowing()) { mProgressDialog.dismiss(); mProgressDialog = null; } } void cancellCollectTask(){ if (mCollectLogTask != null && mCollectLogTask.getStatus() == AsyncTask.Status.RUNNING) { mCollectLogTask.cancel(true); mCollectLogTask = null; } } @Override protected void onPause(){ cancellCollectTask(); dismissProgressDialog(); dismissMainDialog(); super.onPause(); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.DialogInterface.OnCancelListener; import android.location.Location; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Window; /** * Can be called to execute a checkin. Should be presented with the transparent * dialog theme to appear only as a progress bar. When execution is complete, a * successful checkin will show an instance of CheckinResultDialog to handle * rendering the CheckinResult response object. A failed checkin will show a * toast with the error message. Ideally we could launch another activity for * rendering the result, but passing the CheckinResult between activities using * the extras data will have to be done when we have more time. * * For the location paramters of the checkin method, this activity will grab the * global last-known best location. * * The activity will setResult(RESULT_OK) if the checkin worked, and will * setResult(RESULT_CANCELED) if it did not work. * * @date March 2, 2010 * @author Mark Wyszomierski (markww@gmail.com). */ public class CheckinExecuteActivity extends Activity { public static final String TAG = "CheckinExecuteActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUE_ID = Foursquared.PACKAGE_NAME + ".CheckinExecuteActivity.INTENT_EXTRA_VENUE_ID"; public static final String INTENT_EXTRA_SHOUT = Foursquared.PACKAGE_NAME + ".CheckinExecuteActivity.INTENT_EXTRA_SHOUT"; public static final String INTENT_EXTRA_TELL_FRIENDS = Foursquared.PACKAGE_NAME + ".CheckinExecuteActivity.INTENT_EXTRA_TELL_FRIENDS"; public static final String INTENT_EXTRA_TELL_FOLLOWERS = Foursquared.PACKAGE_NAME + ".CheckinExecuteActivity.INTENT_EXTRA_TELL_FOLLOWERS"; public static final String INTENT_EXTRA_TELL_TWITTER = Foursquared.PACKAGE_NAME + ".CheckinExecuteActivity.INTENT_EXTRA_TELL_TWITTER"; public static final String INTENT_EXTRA_TELL_FACEBOOK = Foursquared.PACKAGE_NAME + ".CheckinExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK"; private static final int DIALOG_CHECKIN_RESULT = 1; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.checkin_execute_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); // We start the checkin immediately on creation. Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { mStateHolder = new StateHolder(); String venueId = null; if (getIntent().getExtras().containsKey(INTENT_EXTRA_VENUE_ID)) { venueId = getIntent().getExtras().getString(INTENT_EXTRA_VENUE_ID); } else { Log.e(TAG, "CheckinExecuteActivity requires intent extra 'INTENT_EXTRA_VENUE_ID'."); finish(); return; } Foursquared foursquared = (Foursquared) getApplication(); Location location = foursquared.getLastKnownLocation(); mStateHolder.startTask( CheckinExecuteActivity.this, venueId, location, getIntent().getExtras().getString(INTENT_EXTRA_SHOUT), getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FRIENDS, false), getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FOLLOWERS, false), getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_TWITTER, false), getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FACEBOOK, false) ); } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } @Override public void onResume() { super.onResume(); if (mStateHolder.getIsRunning()) { startProgressBar(getResources().getString(R.string.checkin_action_label), getResources().getString(R.string.checkin_execute_activity_progress_bar_message)); } } @Override public void onPause() { super.onPause(); stopProgressBar(); if (isFinishing()) { mStateHolder.cancelTasks(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } private void startProgressBar(String title, String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, title, message); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CHECKIN_RESULT: // When the user cancels the dialog (by hitting the 'back' key), we // finish this activity. We don't listen to onDismiss() for this // action, because a device rotation will fire onDismiss(), and our // dialog would not be re-displayed after the rotation is complete. CheckinResultDialog dlg = new CheckinResultDialog( this, mStateHolder.getCheckinResult(), ((Foursquared)getApplication())); dlg.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { removeDialog(DIALOG_CHECKIN_RESULT); setResult(Activity.RESULT_OK); finish(); } }); return dlg; } return null; } private void onCheckinComplete(CheckinResult result, Exception ex) { mStateHolder.setIsRunning(false); stopProgressBar(); if (result != null) { mStateHolder.setCheckinResult(result); showDialog(DIALOG_CHECKIN_RESULT); } else { NotificationsUtil.ToastReasonForFailure(this, ex); setResult(Activity.RESULT_CANCELED); finish(); } } private static class CheckinTask extends AsyncTask<Void, Void, CheckinResult> { private CheckinExecuteActivity mActivity; private String mVenueId; private Location mLocation; private String mShout; private boolean mTellFriends; private boolean mTellFollowers; private boolean mTellTwitter; private boolean mTellFacebook; private Exception mReason; public CheckinTask(CheckinExecuteActivity activity, String venueId, Location location, String shout, boolean tellFriends, boolean tellFollowers, boolean tellTwitter, boolean tellFacebook) { mActivity = activity; mVenueId = venueId; mLocation = location; mShout = shout; mTellFriends = tellFriends; mTellFollowers = tellFollowers; mTellTwitter = tellTwitter; mTellFacebook = tellFacebook; } public void setActivity(CheckinExecuteActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(mActivity.getResources().getString( R.string.checkin_action_label), mActivity.getResources().getString( R.string.checkin_execute_activity_progress_bar_message)); } @Override protected CheckinResult doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); CheckinResult result = foursquare.checkin( mVenueId, null, // passing in the real venue name causes a 400 response from the server. LocationUtils.createFoursquareLocation(mLocation), mShout, !mTellFriends, // (isPrivate) mTellFollowers, mTellTwitter, mTellFacebook); // Here we should really be downloading the mayor's photo serially, so that this // work is done in the background while the progress bar is already spinning. // When the checkin result dialog pops up, the photo would already be loaded. // We can at least start the request if necessary here in the background thread. if (result != null && result.getMayor() != null && result.getMayor().getUser() != null) { if (result.getMayor() != null && result.getMayor().getUser() != null) { Uri photoUri = Uri.parse(result.getMayor().getUser().getPhoto()); RemoteResourceManager rrm = foursquared.getRemoteResourceManager(); if (rrm.exists(photoUri) == false) { rrm.request(photoUri); } } } return result; } catch (Exception e) { if (DEBUG) Log.d(TAG, "CheckinTask: Exception checking in.", e); mReason = e; } return null; } @Override protected void onPostExecute(CheckinResult result) { if (DEBUG) Log.d(TAG, "CheckinTask: onPostExecute()"); if (mActivity != null) { mActivity.onCheckinComplete(result, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onCheckinComplete(null, new FoursquareException( "Check-in cancelled.")); } } } private static class StateHolder { private CheckinTask mTask; private CheckinResult mCheckinResult; private boolean mIsRunning; public StateHolder() { mCheckinResult = null; mIsRunning = false; } public void startTask(CheckinExecuteActivity activity, String venueId, Location location, String shout, boolean tellFriends, boolean tellFollowers, boolean tellTwitter, boolean tellFacebook) { mIsRunning = true; mTask = new CheckinTask( activity, venueId, location, shout, tellFriends, tellFollowers, tellTwitter, tellFacebook); mTask.execute(); } public void setActivity(CheckinExecuteActivity activity) { if (mTask != null) { mTask.setActivity(activity); } } public boolean getIsRunning() { return mIsRunning; } public void setIsRunning(boolean isRunning) { mIsRunning = isRunning; } public CheckinResult getCheckinResult() { return mCheckinResult; } public void setCheckinResult(CheckinResult result) { mCheckinResult = result; } public void cancelTasks() { if (mTask != null && mIsRunning) { mTask.setActivity(null); mTask.cancel(true); } } } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.joelapenna.foursquared.preferences; import android.content.Context; import android.content.res.TypedArray; import android.os.Parcelable; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; /** * This is an example of a custom preference type. The preference counts the number of clicks it has * received and stores/retrieves it from the storage. */ public class ClickPreference extends Preference { // This is the constructor called by the inflater public ClickPreference(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onBindView(View view) { super.onBindView(view); } @Override protected void onClick() { // Data has changed, notify so UI can be refreshed! notifyChanged(); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { // This preference type's value type is Integer, so we read the default // value from the attributes as an Integer. return a.getInteger(index, 0); } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { } @Override protected void onRestoreInstanceState(Parcelable state) { super.onRestoreInstanceState(state); notifyChanged(); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.preferences; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.City; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.StringFormatters; import com.joelapenna.foursquared.util.UserUtils; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Resources; import android.util.Log; import java.io.IOException; import java.util.UUID; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Preferences { private static final String TAG = "Preferences"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; // Visible Preferences (sync with preferences.xml) public static final String PREFERENCE_SHARE_CHECKIN = "share_checkin"; public static final String PREFERENCE_IMMEDIATE_CHECKIN = "immediate_checkin"; public static final String PREFERENCE_STARTUP_TAB = "startup_tab"; // Hacks for preference activity extra UI elements. public static final String PREFERENCE_ADVANCED_SETTINGS = "advanced_settings"; public static final String PREFERENCE_TWITTER_CHECKIN = "twitter_checkin"; public static final String PREFERENCE_FACEBOOK_CHECKIN = "facebook_checkin"; public static final String PREFERENCE_TWITTER_HANDLE = "twitter_handle"; public static final String PREFERENCE_FACEBOOK_HANDLE = "facebook_handle"; public static final String PREFERENCE_FRIEND_REQUESTS = "friend_requests"; public static final String PREFERENCE_FRIEND_ADD = "friend_add"; public static final String PREFERENCE_CHANGELOG = "changelog"; public static final String PREFERENCE_CITY_NAME = "city_name"; public static final String PREFERENCE_LOGOUT = "logout"; public static final String PREFERENCE_HELP = "help"; public static final String PREFERENCE_SEND_FEEDBACK = "send_feedback"; public static final String PREFERENCE_PINGS = "pings_on"; public static final String PREFERENCE_PINGS_INTERVAL = "pings_refresh_interval_in_minutes"; public static final String PREFERENCE_PINGS_VIBRATE = "pings_vibrate"; public static final String PREFERENCE_TOS_PRIVACY = "tos_privacy"; public static final String PREFERENCE_PROFILE_SETTINGS = "profile_settings"; // Credentials related preferences public static final String PREFERENCE_LOGIN = "phone"; public static final String PREFERENCE_PASSWORD = "password"; // Extra info for getUserCity private static final String PREFERENCE_CITY_ID = "city_id"; private static final String PREFERENCE_CITY_GEOLAT = "city_geolat"; private static final String PREFERENCE_CITY_GEOLONG = "city_geolong"; private static final String PREFERENCE_CITY_SHORTNAME = "city_shortname"; // Extra info for getUserId private static final String PREFERENCE_ID = "id"; // Extra for storing user's supplied email address. private static final String PREFERENCE_USER_EMAIL = "user_email"; // Extra for storing user's supplied first and last name. private static final String PREFERENCE_USER_NAME = "user_name"; // Extra info about the user, their gender, to control icon used for 'me' in the UI. private static final String PREFERENCE_GENDER = "gender"; // Extra info, can the user have followers or not. public static final String PREFERENCE_CAN_HAVE_FOLLOWERS = "can_have_followers"; // Not-in-XML preferences for dumpcatcher public static final String PREFERENCE_DUMPCATCHER_CLIENT = "dumpcatcher_client"; // Keeps track of the last changelog version shown to the user at startup. private static final String PREFERENCE_LAST_SEEN_CHANGELOG_VERSION = "last_seen_changelog_version"; // User can choose to clear geolocation on each search. public static final String PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES = "cache_geolocation_for_searches"; // If we're compiled to show the prelaunch activity, flag stating whether to skip // showing it on startup. public static final String PREFERENCE_SHOW_PRELAUNCH_ACTIVITY = "show_prelaunch_activity"; // Last time pings service ran. public static final String PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME = "pings_service_last_run_time"; // Broadcast an intent to show single full-screen images, or use our own poor image viewer. public static final String PREFERENCE_NATIVE_IMAGE_VIEWER = "native_full_size_image_viewer"; /** * Gives us a chance to set some default preferences if this is the first install * of the application. */ public static void setupDefaults(SharedPreferences preferences, Resources resources) { Editor editor = preferences.edit(); if (!preferences.contains(PREFERENCE_STARTUP_TAB)) { String[] startupTabValues = resources.getStringArray(R.array.startup_tabs_values); editor.putString(PREFERENCE_STARTUP_TAB, startupTabValues[0]); } if (!preferences.contains(PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES)) { editor.putBoolean(PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES, false); } if (!preferences.contains(PREFERENCE_SHOW_PRELAUNCH_ACTIVITY)) { editor.putBoolean(PREFERENCE_SHOW_PRELAUNCH_ACTIVITY, true); } if (!preferences.contains(PREFERENCE_PINGS_INTERVAL)) { editor.putString(PREFERENCE_PINGS_INTERVAL, "30"); } if (!preferences.contains(PREFERENCE_NATIVE_IMAGE_VIEWER)) { editor.putBoolean(PREFERENCE_NATIVE_IMAGE_VIEWER, true); } editor.commit(); } public static String createUniqueId(SharedPreferences preferences) { String uniqueId = preferences.getString(PREFERENCE_DUMPCATCHER_CLIENT, null); if (uniqueId == null) { uniqueId = UUID.randomUUID().toString(); Editor editor = preferences.edit(); editor.putString(PREFERENCE_DUMPCATCHER_CLIENT, uniqueId); editor.commit(); } return uniqueId; } public static boolean loginUser(Foursquare foursquare, String login, String password, Foursquare.Location location, Editor editor) throws FoursquareCredentialsException, FoursquareException, IOException { if (DEBUG) Log.d(Preferences.TAG, "Trying to log in."); foursquare.setCredentials(login, password); storeLoginAndPassword(editor, login, password); if (!editor.commit()) { if (DEBUG) Log.d(TAG, "storeLoginAndPassword commit failed"); return false; } User user = foursquare.user(null, false, false, false, location); storeUser(editor, user); if (!editor.commit()) { if (DEBUG) Log.d(TAG, "storeUser commit failed"); return false; } return true; } public static boolean logoutUser(Foursquare foursquare, Editor editor) { if (DEBUG) Log.d(Preferences.TAG, "Trying to log out."); // TODO: If we re-implement oAuth, we'll have to call clearAllCrendentials here. foursquare.setCredentials(null, null); return editor.clear().commit(); } public static City getUserCity(SharedPreferences prefs) { City city = new City(); city.setId(prefs.getString(Preferences.PREFERENCE_CITY_ID, null)); city.setName(prefs.getString(Preferences.PREFERENCE_CITY_NAME, null)); city.setShortname(prefs.getString(Preferences.PREFERENCE_CITY_SHORTNAME, null)); city.setGeolat(prefs.getString(Preferences.PREFERENCE_CITY_GEOLAT, null)); city.setGeolong(prefs.getString(Preferences.PREFERENCE_CITY_GEOLONG, null)); return city; } public static String getUserId(SharedPreferences prefs) { return prefs.getString(PREFERENCE_ID, null); } public static String getUserName(SharedPreferences prefs) { return prefs.getString(PREFERENCE_USER_NAME, null); } public static String getUserEmail(SharedPreferences prefs) { return prefs.getString(PREFERENCE_USER_EMAIL, null); } public static String getUserGender(SharedPreferences prefs) { return prefs.getString(PREFERENCE_GENDER, null); } public static String getLastSeenChangelogVersion(SharedPreferences prefs) { return prefs.getString(PREFERENCE_LAST_SEEN_CHANGELOG_VERSION, null); } public static void storeCity(final Editor editor, City city) { if (city != null) { editor.putString(PREFERENCE_CITY_ID, city.getId()); editor.putString(PREFERENCE_CITY_GEOLAT, city.getGeolat()); editor.putString(PREFERENCE_CITY_GEOLONG, city.getGeolong()); editor.putString(PREFERENCE_CITY_NAME, city.getName()); editor.putString(PREFERENCE_CITY_SHORTNAME, city.getShortname()); } } public static void storeLoginAndPassword(final Editor editor, String login, String password) { editor.putString(PREFERENCE_LOGIN, login); editor.putString(PREFERENCE_PASSWORD, password); } public static void storeUser(final Editor editor, User user) { if (user != null && user.getId() != null) { editor.putString(PREFERENCE_ID, user.getId()); editor.putString(PREFERENCE_USER_NAME, StringFormatters.getUserFullName(user)); editor.putString(PREFERENCE_USER_EMAIL, user.getEmail()); editor.putBoolean(PREFERENCE_TWITTER_CHECKIN, user.getSettings().sendtotwitter()); editor.putBoolean(PREFERENCE_FACEBOOK_CHECKIN, user.getSettings().sendtofacebook()); editor.putString(PREFERENCE_TWITTER_HANDLE, user.getTwitter() != null ? user.getTwitter() : ""); editor.putString(PREFERENCE_FACEBOOK_HANDLE, user.getFacebook() != null ? user.getFacebook() : ""); editor.putString(PREFERENCE_GENDER, user.getGender()); editor.putBoolean(PREFERENCE_CAN_HAVE_FOLLOWERS, UserUtils.getCanHaveFollowers(user)); if (DEBUG) Log.d(TAG, "Setting user info"); } else { if (Preferences.DEBUG) Log.d(Preferences.TAG, "Unable to lookup user."); } } public static void storeLastSeenChangelogVersion(final Editor editor, String version) { editor.putString(PREFERENCE_LAST_SEEN_CHANGELOG_VERSION, version); if (!editor.commit()) { Log.e(TAG, "storeLastSeenChangelogVersion commit failed"); } } public static boolean getUseNativeImageViewerForFullScreenImages(SharedPreferences prefs) { return prefs.getBoolean(PREFERENCE_NATIVE_IMAGE_VIEWER, true); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquared.error.LocationException; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class StatsActivity extends Activity { public static final String TAG = "StatsActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.stats_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); setTitle(getResources().getString(R.string.stats_activity_scoreboard)); WebView webView = (WebView) findViewById(R.id.webView); webView.setWebViewClient(new MyWebViewClient()); webView.setWebChromeClient(new MyWebChromeClient()); Foursquared foursquared = ((Foursquared) getApplication()); String userId = ((Foursquared) getApplication()).getUserId(); try { String url = Foursquare.createLeaderboardUrl(userId, LocationUtils .createFoursquareLocation(foursquared.getLastKnownLocationOrThrow())); Log.d(TAG, url); webView.loadUrl(url); } catch (LocationException e) { NotificationsUtil.ToastReasonForFailure(this, e); finish(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } private class MyWebChromeClient extends WebChromeClient { @Override public void onProgressChanged(WebView view, int newProgress) { setProgress(newProgress * 100); } } private class MyWebViewClient extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { setProgressBarVisibility(false); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { setProgressBarVisibility(true); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.FriendRequestsAdapter; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * Presents the user with a list of pending friend requests that they can * approve or deny. * * @date February 12, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class FriendRequestsActivity extends ListActivity { private static final String TAG = "FriendRequestsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int MENU_REFRESH = 0; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; private EditText mEditTextFilter; private FriendRequestsAdapter mListAdapter; private TextView mTextViewNoRequests; private Handler mHandler; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); setContentView(R.layout.friend_requests_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mHandler = new Handler(); mEditTextFilter = (EditText)findViewById(R.id.editTextFilter); mEditTextFilter.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { // Run the filter operation after a brief waiting period in case the user // is typing real fast. mHandler.removeCallbacks(mRunnableFilter); mHandler.postDelayed(mRunnableFilter, 700L); } }); mListAdapter = new FriendRequestsAdapter(this, mButtonRowClickHandler, ((Foursquared) getApplication()).getRemoteResourceManager()); getListView().setAdapter(mListAdapter); getListView().setItemsCanFocus(true); mTextViewNoRequests = (TextView)findViewById(R.id.textViewNoRequests); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTaskFriendRequests(this); mStateHolder.setActivityForTaskSendDecision(this); decideShowNoFriendRequestsTextView(); } else { mStateHolder = new StateHolder(); // Start searching for friend requests immediately on activity creation. startProgressBar(getResources().getString(R.string.friend_requests_activity_label), getResources().getString(R.string.friend_requests_progress_bar_find_requests)); mStateHolder.startTaskFriendRequests(FriendRequestsActivity.this); } } @Override public void onResume() { super.onResume(); if (mStateHolder.getIsRunningFriendRequest()) { startProgressBar(getResources().getString(R.string.friend_requests_activity_label), getResources().getString(R.string.friend_requests_progress_bar_find_requests)); } else if (mStateHolder.getIsRunningApproval()) { startProgressBar(getResources().getString(R.string.friend_requests_activity_label), getResources() .getString(R.string.friend_requests_progress_bar_approve_request)); } else if (mStateHolder.getIsRunningIgnore()) { startProgressBar(getResources().getString(R.string.friend_requests_activity_label), getResources() .getString(R.string.friend_requests_progress_bar_ignore_request)); } mListAdapter.setGroup(mStateHolder.getFoundFriendsFiltered()); mListAdapter.notifyDataSetChanged(); } @Override public void onPause() { super.onPause(); stopProgressBar(); if (isFinishing()) { mListAdapter.removeObserver(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTaskFriendRequests(null); mStateHolder.setActivityForTaskSendDecision(null); return mStateHolder; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh).setIcon( R.drawable.ic_menu_refresh); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: startProgressBar(getResources().getString(R.string.friend_requests_activity_label), getResources().getString(R.string.friend_requests_progress_bar_find_requests)); mStateHolder.setRanFetchOnce(false); mStateHolder.startTaskFriendRequests(FriendRequestsActivity.this); decideShowNoFriendRequestsTextView(); return true; } return super.onOptionsItemSelected(item); } private void startProgressBar(String title, String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, title, message); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } private void infoFriendRequest(User user) { Intent intent = new Intent(this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user); startActivity(intent); } private void approveFriendRequest(User user) { startProgressBar(getResources().getString(R.string.friend_requests_activity_label), getResources().getString(R.string.friend_requests_progress_bar_approve_request)); mStateHolder.startTaskSendDecision(FriendRequestsActivity.this, user.getId(), true); } private void denyFriendRequest(User user) { startProgressBar(getResources().getString(R.string.friend_requests_activity_label), getResources().getString(R.string.friend_requests_progress_bar_ignore_request)); mStateHolder.startTaskSendDecision(FriendRequestsActivity.this, user.getId(), false); } private void decideShowNoFriendRequestsTextView() { if (mStateHolder.getRanFetchOnce() && mStateHolder.getFoundFriendsCount() < 1) { mTextViewNoRequests.setVisibility(View.VISIBLE); } else { mTextViewNoRequests.setVisibility(View.GONE); } } private void onFriendRequestsTaskComplete(Group<User> users, HashMap<String, Group<User>> usersAlpha, Exception ex) { // Recreate the adapter, cleanup beforehand. mListAdapter.removeObserver(); mListAdapter = new FriendRequestsAdapter(this, mButtonRowClickHandler, ((Foursquared) getApplication()).getRemoteResourceManager()); try { // Populate the list control below now. if (users != null) { mStateHolder.setFoundFriends(users, usersAlpha); if (DEBUG) { Log.e(TAG, "Alpha-sorted requests map:"); for (Map.Entry<String, Group<User>> it : usersAlpha.entrySet()) { Log.e(TAG, it.getKey()); for (User jt : it.getValue()) { Log.e(TAG, " " + getUsersDisplayName(jt)); } } } } else { // If error, feed list adapter empty user group. mStateHolder.setFoundFriends(null, null); NotificationsUtil.ToastReasonForFailure(FriendRequestsActivity.this, ex); } mListAdapter.setGroup(mStateHolder.getFoundFriendsFiltered()); } finally { getListView().setAdapter(mListAdapter); mStateHolder.setIsRunningFriendRequest(false); mStateHolder.setRanFetchOnce(true); decideShowNoFriendRequestsTextView(); stopProgressBar(); } } private void onFriendRequestDecisionTaskComplete(User user, boolean isApproving, Exception ex) { try { // If sending the request was successful, then we need to remove // that user from the list adapter. We do a linear search to find the // matching row. if (user != null) { mStateHolder.removeUser(user); mListAdapter.setGroup(mStateHolder.getFoundFriendsFiltered()); mListAdapter.notifyDataSetChanged(); // This should generate the message: "You're now friends with [name]!" if // the user chose to approve the request, otherwise we show no toast, just // remove from the list. if (isApproving) { Toast.makeText(this, getResources().getString(R.string.friend_requests_approved) + " " + getUsersDisplayName(user) + "!", Toast.LENGTH_SHORT).show(); } } else { NotificationsUtil.ToastReasonForFailure(this, ex); } } finally { decideShowNoFriendRequestsTextView(); mStateHolder.setIsRunningApprval(false); mStateHolder.setIsRunningIgnore(false); stopProgressBar(); } } private static class GetFriendRequestsTask extends AsyncTask<Void, Void, Group<User>> { private FriendRequestsActivity mActivity; private Exception mReason; private HashMap<String, Group<User>> mRequestsAlpha; public GetFriendRequestsTask(FriendRequestsActivity activity) { mActivity = activity; mRequestsAlpha = new LinkedHashMap<String, Group<User>>(); } public void setActivity(FriendRequestsActivity activity) { mActivity = activity; } @Override protected Group<User> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); Group<User> requests = foursquare.friendRequests(); for (User it : requests) { String name = getUsersDisplayName(it).toUpperCase(); String first = name.substring(0, 1); Group<User> block = mRequestsAlpha.get(first); if (block == null) { block = new Group<User>(); mRequestsAlpha.put(first, block); } block.add(it); } return requests; } catch (Exception e) { if (DEBUG) Log.d(TAG, "FindFriendsTask: Exception doing add friends by name", e); mReason = e; } return null; } @Override protected void onPostExecute(Group<User> users) { if (DEBUG) Log.d(TAG, "FindFriendsTask: onPostExecute()"); if (mActivity != null) { mActivity.onFriendRequestsTaskComplete(users, mRequestsAlpha, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onFriendRequestsTaskComplete(null, null, new Exception( "Friend search cancelled.")); } } } private static class SendFriendRequestDecisionTask extends AsyncTask<Void, Void, User> { private FriendRequestsActivity mActivity; private boolean mIsApproving; private String mUserId; private Exception mReason; public SendFriendRequestDecisionTask(FriendRequestsActivity activity, String userId, boolean isApproving) { mActivity = activity; mUserId = userId; mIsApproving = isApproving; } public void setActivity(FriendRequestsActivity activity) { mActivity = activity; } @Override protected User doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); User user = null; if (mIsApproving) { user = foursquare.friendApprove(mUserId); } else { user = foursquare.friendDeny(mUserId); } return user; } catch (Exception e) { if (DEBUG) Log.d(TAG, "SendFriendRequestTask: Exception doing send friend request.", e); mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (DEBUG) Log.d(TAG, "SendFriendRequestTask: onPostExecute()"); if (mActivity != null) { mActivity.onFriendRequestDecisionTaskComplete(user, mIsApproving, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onFriendRequestDecisionTaskComplete(null, mIsApproving, new Exception("Friend request cancelled.")); } } } private static class StateHolder { GetFriendRequestsTask mTaskFriendRequests; SendFriendRequestDecisionTask mTaskSendDecision; boolean mIsRunningFriendRequests; boolean mIsRunningApproval; boolean mIsRunningIgnore; boolean mRanFetchOnce; private Group<User> mFoundFriends; private Group<User> mFoundFriendsFiltered; private HashMap<String, Group<User>> mFoundFriendsAlpha; public StateHolder() { mFoundFriends = new Group<User>(); mFoundFriendsFiltered = null; mFoundFriendsAlpha = null; mIsRunningFriendRequests = false; mIsRunningApproval = false; mIsRunningIgnore = false; mRanFetchOnce = false; } public void startTaskFriendRequests(FriendRequestsActivity activity) { mIsRunningFriendRequests = true; mTaskFriendRequests = new GetFriendRequestsTask(activity); mTaskFriendRequests.execute(); } public void startTaskSendDecision(FriendRequestsActivity activity, String userId, boolean approve) { mIsRunningApproval = approve; mIsRunningIgnore = !approve; mTaskSendDecision = new SendFriendRequestDecisionTask(activity, userId, approve); mTaskSendDecision.execute(); } public void setActivityForTaskFriendRequests(FriendRequestsActivity activity) { if (mTaskFriendRequests != null) { mTaskFriendRequests.setActivity(activity); } } public void setActivityForTaskSendDecision(FriendRequestsActivity activity) { if (mTaskSendDecision != null) { mTaskSendDecision.setActivity(activity); } } public void setIsRunningFriendRequest(boolean isRunning) { mIsRunningFriendRequests = isRunning; } public boolean getIsRunningFriendRequest() { return mIsRunningFriendRequests; } public boolean getIsRunningApproval() { return mIsRunningApproval; } public void setIsRunningApprval(boolean isRunning) { mIsRunningApproval = isRunning; } public boolean getIsRunningIgnore() { return mIsRunningIgnore; } public void setIsRunningIgnore(boolean isRunning) { mIsRunningIgnore = isRunning; } public boolean getRanFetchOnce() { return mRanFetchOnce; } public void setRanFetchOnce(boolean ranFetchOnce) { mRanFetchOnce = ranFetchOnce; } public int getFoundFriendsCount() { return mFoundFriends.size(); } public Group<User> getFoundFriendsFiltered() { if (mFoundFriendsFiltered == null) { return mFoundFriends; } return mFoundFriendsFiltered; } public void setFoundFriends(Group<User> requests, HashMap<String, Group<User>> alpha) { if (requests != null) { mFoundFriends = requests; mFoundFriendsFiltered = null; mFoundFriendsAlpha = alpha; } else { mFoundFriends = new Group<User>(); mFoundFriendsFiltered = null; mFoundFriendsAlpha = null; } } public void filterFriendRequests(String filterString) { // If no filter, just keep using the original found friends group. // If a filter is supplied, reconstruct the group using the alpha // map so we don't have to go through the entire list. mFoundFriendsFiltered = null; if (!TextUtils.isEmpty(filterString)) { filterString = filterString.toUpperCase(); Group<User> alpha = mFoundFriendsAlpha.get(filterString.substring(0, 1)); mFoundFriendsFiltered = new Group<User>(); if (alpha != null) { for (User it : alpha) { String name = getUsersDisplayName(it).toUpperCase(); if (name.startsWith(filterString)) { mFoundFriendsFiltered.add(it); } } } } } public void removeUser(User user) { for (User it : mFoundFriends) { if (it.getId().equals(user.getId())) { mFoundFriends.remove(it); break; } } if (mFoundFriendsFiltered != null) { for (User it : mFoundFriendsFiltered) { if (it.getId().equals(user.getId())) { mFoundFriendsFiltered.remove(it); break; } } } String name = getUsersDisplayName(user).toUpperCase(); String first = name.substring(0, 1); Group<User> alpha = mFoundFriendsAlpha.get(first); for (User it : alpha) { if (it.getId().equals(user.getId())) { alpha.remove(it); break; } } } } private static String getUsersDisplayName(User user) { StringBuilder sb = new StringBuilder(64); if (!TextUtils.isEmpty(user.getFirstname())) { sb.append(user.getFirstname()); sb.append(" "); } if (!TextUtils.isEmpty(user.getLastname())) { sb.append(user.getLastname()); } return sb.toString(); } private FriendRequestsAdapter.ButtonRowClickHandler mButtonRowClickHandler = new FriendRequestsAdapter.ButtonRowClickHandler() { @Override public void onBtnClickIgnore(User user) { denyFriendRequest(user); } @Override public void onBtnClickAdd(User user) { approveFriendRequest(user); } @Override public void onInfoAreaClick(User user) { infoFriendRequest(user); } }; private Runnable mRunnableFilter = new Runnable() { public void run() { mStateHolder.filterFriendRequests(mEditTextFilter.getText().toString()); mListAdapter.setGroup(mStateHolder.getFoundFriendsFiltered()); mListAdapter.notifyDataSetChanged(); } }; }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.FriendListAdapter; import com.joelapenna.foursquared.widget.SegmentedButton; import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; /** * To be used when a user has some friends in common. We show two lists, by default * the first list is 'friends in common'. The second list is all friends. This is * expected to be used with a fully-fetched user object, so the friends in common * group should already be fetched. The full 'all friends' list is fetched separately * within this activity. * * If the user has no friends in common, then just use UserDetailsFriendsActivity * directly. * * @date September 23, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserDetailsFriendsInCommonActivity extends LoadableListActivityWithViewAndHeader { static final String TAG = "UserDetailsFriendsInCommonActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME + ".UserDetailsFriendsInCommonActivity.EXTRA_USER_PARCEL"; private StateHolder mStateHolder; private FriendListAdapter mListAdapter; private ScrollView mLayoutEmpty; private static final int MENU_REFRESH = 0; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(EXTRA_USER_PARCEL)) { mStateHolder.setUser((User)getIntent().getParcelableExtra(EXTRA_USER_PARCEL)); if (mStateHolder.getUser().getFriendsInCommon() == null || mStateHolder.getUser().getFriendsInCommon().size() == 0) { Log.e(TAG, TAG + " requires user parcel have friends in common size > 0."); finish(); return; } } else { Log.e(TAG, TAG + " requires user parcel in intent extras."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mStateHolder.cancelTasks(); mListAdapter.removeObserver(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { LayoutInflater inflater = LayoutInflater.from(this); mLayoutEmpty = (ScrollView)inflater.inflate(R.layout.user_details_friends_activity_empty, null); mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); mListAdapter = new FriendListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); if (mStateHolder.getFriendsInCommonOnly()) { mListAdapter.setGroup(mStateHolder.getUser().getFriendsInCommon()); } else { mListAdapter.setGroup(mStateHolder.getAllFriends()); if (mStateHolder.getAllFriends().size() == 0) { if (mStateHolder.getRanOnce()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } SegmentedButton buttons = getHeaderButton(); buttons.clearButtons(); buttons.addButtons( getString(R.string.user_details_friends_in_common_common_friends), getString(R.string.user_details_friends_in_common_all_friends)); if (mStateHolder.getFriendsInCommonOnly()) { buttons.setPushedButtonIndex(0); } else { buttons.setPushedButtonIndex(1); } buttons.setOnClickListener(new OnClickListenerSegmentedButton() { @Override public void onClick(int index) { if (index == 0) { mStateHolder.setFriendsInCommonOnly(true); mListAdapter.setGroup(mStateHolder.getUser().getFriendsInCommon()); } else { mStateHolder.setFriendsInCommonOnly(false); mListAdapter.setGroup(mStateHolder.getAllFriends()); if (mStateHolder.getAllFriends().size() < 1) { if (mStateHolder.getRanOnce()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTaskAllFriends(UserDetailsFriendsInCommonActivity.this); } } } mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } }); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(false); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { User user = (User) parent.getAdapter().getItem(position); Intent intent = new Intent(UserDetailsFriendsInCommonActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user); intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true); startActivity(intent); } }); if (mStateHolder.getIsRunningTaskAllFriends()) { setProgressBarIndeterminateVisibility(true); } else { setProgressBarIndeterminateVisibility(false); } setTitle(getString(R.string.user_details_friends_in_common_title, mStateHolder.getUser().getFirstname())); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: if (!mStateHolder.getFriendsInCommonOnly()) { mStateHolder.startTaskAllFriends(this); } return true; } return super.onOptionsItemSelected(item); } private void onStartTaskAllFriends() { mStateHolder.setIsRunningTaskAllFriends(true); setProgressBarIndeterminateVisibility(true); setLoadingView(); } private void onTaskAllFriendsComplete(Group<User> allFriends, Exception ex) { setProgressBarIndeterminateVisibility(false); mStateHolder.setRanOnce(true); mStateHolder.setIsRunningTaskAllFriends(false); if (allFriends != null) { mStateHolder.setAllFriends(allFriends); } else { NotificationsUtil.ToastReasonForFailure(this, ex); } SegmentedButton buttons = getHeaderButton(); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getAllFriends()); if (mStateHolder.getAllFriends().size() == 0) { if (mStateHolder.getRanOnce()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } } /** * Gets friends of the current user we're working for. */ private static class TaskAllFriends extends AsyncTask<Void, Void, Group<User>> { private UserDetailsFriendsInCommonActivity mActivity; private String mUserId; private Exception mReason; public TaskAllFriends(UserDetailsFriendsInCommonActivity activity, String userId) { mActivity = activity; mUserId = userId; } @Override protected void onPreExecute() { mActivity.onStartTaskAllFriends(); } @Override protected Group<User> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.friends( mUserId, LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Group<User> allFriends) { if (mActivity != null) { mActivity.onTaskAllFriendsComplete(allFriends, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskAllFriendsComplete(null, mReason); } } public void setActivity(UserDetailsFriendsInCommonActivity activity) { mActivity = activity; } } private static class StateHolder { private User mUser; private Group<User> mAllFriends; private TaskAllFriends mTaskAllFriends; private boolean mIsRunningTaskAllFriends; private boolean mRanOnceTaskAllFriends; private boolean mFriendsInCommonOnly; public StateHolder() { mAllFriends = new Group<User>(); mIsRunningTaskAllFriends = false; mRanOnceTaskAllFriends = false; mFriendsInCommonOnly = true; } public User getUser() { return mUser; } public void setUser(User user) { mUser = user; } public Group<User> getAllFriends() { return mAllFriends; } public void setAllFriends(Group<User> allFriends) { mAllFriends = allFriends; } public void startTaskAllFriends(UserDetailsFriendsInCommonActivity activity) { if (!mIsRunningTaskAllFriends) { mIsRunningTaskAllFriends = true; mTaskAllFriends = new TaskAllFriends(activity, mUser.getId()); mTaskAllFriends.execute(); } } public void setActivity(UserDetailsFriendsInCommonActivity activity) { if (mTaskAllFriends != null) { mTaskAllFriends.setActivity(activity); } } public boolean getIsRunningTaskAllFriends() { return mIsRunningTaskAllFriends; } public void setIsRunningTaskAllFriends(boolean isRunning) { mIsRunningTaskAllFriends = isRunning; } public void cancelTasks() { if (mTaskAllFriends != null) { mTaskAllFriends.setActivity(null); mTaskAllFriends.cancel(true); } } public boolean getRanOnce() { return mRanOnceTaskAllFriends; } public void setRanOnce(boolean ranOnce) { mRanOnceTaskAllFriends = ranOnce; } public boolean getFriendsInCommonOnly() { return mFriendsInCommonOnly; } public void setFriendsInCommonOnly(boolean friendsInCommonOnly) { mFriendsInCommonOnly = friendsInCommonOnly; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.util.VenueUtils; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import java.util.TreeMap; /** * Queries the system for any apps that can be used for sharing data, * like sms or email. Package exploration is largely taken from Mark * Murphy's commonsware projects: * * http://github.com/commonsguy/cw-advandroid * * @date September 22, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class VenueShareActivity extends Activity { public static final String TAG = "VenueShareActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".VenueShareActivity.INTENT_EXTRA_VENUE"; private StateHolder mStateHolder; private ShareAdapter mListAdapter; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); setContentView(R.layout.venue_share_activity); setTitle(getString(R.string.venue_share_activity_title)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE)); } else { Log.e(TAG, "VenueShareActivity requires a venue parcel its intent extras."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } private void ensureUi() { mListAdapter = new ShareAdapter(this, getPackageManager(), findAppsForSharing()); ListView listView = (ListView)findViewById(R.id.listview); listView.setAdapter(mListAdapter); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { launchAppIntent(position); } }); } private void launchAppIntent(int position) { ResolveInfo launchable = mListAdapter.getItem(position); ActivityInfo activity = launchable.activityInfo; ComponentName componentName = new ComponentName( activity.applicationInfo.packageName, activity.name); Intent intent = new Intent(Intent.ACTION_SEND); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setComponent(componentName); intent.setType("text/plain"); intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Foursquare Venue Share"); intent.putExtra(android.content.Intent.EXTRA_TEXT, VenueUtils.toStringVenueShare(mStateHolder.getVenue())); startActivity(intent); finish(); } private List<ResolveInfo> findAppsForSharing() { Intent intent = new Intent(Intent.ACTION_SEND, null); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setType("text/plain"); List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0); TreeMap<String, ResolveInfo> alpha = new TreeMap<String, ResolveInfo>(); for (ResolveInfo it : activities) { alpha.put(it.loadLabel(getPackageManager()).toString(), it); } return new ArrayList<ResolveInfo>(alpha.values()); } private class ShareAdapter extends ArrayAdapter<ResolveInfo> { public ShareAdapter(Context context, PackageManager pm, List<ResolveInfo> apps) { super(context, R.layout.user_actions_list_item, apps); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = newView(parent); } bindView(position, convertView); return(convertView); } private View newView(ViewGroup parent) { return (getLayoutInflater().inflate(R.layout.user_actions_list_item, parent, false)); } private void bindView(int position, View view) { PackageManager packageManager = getPackageManager(); ImageView icon = (ImageView)view.findViewById(R.id.userActionsListItemIcon); icon.setImageDrawable(getItem(position).loadIcon(packageManager)); TextView label = (TextView)view.findViewById(R.id.userActionsListItemLabel); label.setText(getItem(position).loadLabel(packageManager)); } } private static class StateHolder { private Venue mVenue; public StateHolder() { } public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.app.LoadableListActivity; import com.joelapenna.foursquared.util.UserUtils; import com.joelapenna.foursquared.widget.CheckinListAdapter; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -refactored for display of straight checkins list (September 16, 2010). * */ public class VenueCheckinsActivity extends LoadableListActivity { public static final String TAG = "VenueCheckinsActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".VenueCheckinsActivity.INTENT_EXTRA_VENUE"; private SeparatedListAdapter mListAdapter; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder = new StateHolder( (Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE), ((Foursquared) getApplication()).getUserId()); } else { Log.e(TAG, "VenueCheckinsActivity requires a venue parcel its intent extras."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } private void ensureUi() { mListAdapter = new SeparatedListAdapter(this); if (mStateHolder.getCheckinsYou().size() > 0) { String title = getResources().getString(R.string.venue_activity_people_count_you); CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(mStateHolder.getCheckinsYou()); mListAdapter.addSection(title, adapter); } if (mStateHolder.getCheckinsFriends().size() > 0) { String title = getResources().getString( mStateHolder.getCheckinsOthers().size() == 1 ? R.string.venue_activity_checkins_count_friends_single : R.string.venue_activity_checkins_count_friends_plural, mStateHolder.getCheckinsFriends().size()); CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(mStateHolder.getCheckinsFriends()); mListAdapter.addSection(title, adapter); } if (mStateHolder.getCheckinsOthers().size() > 0) { boolean others = mStateHolder.getCheckinsYou().size() + mStateHolder.getCheckinsFriends().size() > 0; String title = getResources().getString( mStateHolder.getCheckinsOthers().size() == 1 ? (others ? R.string.venue_activity_checkins_count_others_single : R.string.venue_activity_checkins_count_others_alone_single) : (others ? R.string.venue_activity_checkins_count_others_plural : R.string.venue_activity_checkins_count_others_alone_plural), mStateHolder.getCheckinsOthers().size()); CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(mStateHolder.getCheckinsOthers()); mListAdapter.addSection(title, adapter); } ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(true); listView.setDividerHeight(0); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Checkin checkin = (Checkin) parent.getAdapter().getItem(position); Intent intent = new Intent(VenueCheckinsActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, checkin.getUser()); intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true); startActivity(intent); } }); setTitle(getString(R.string.venue_checkins_activity_title, mStateHolder.getVenueName())); } private static class StateHolder { private String mVenueName; private Group<Checkin> mYou; private Group<Checkin> mFriends; private Group<Checkin> mOthers; public StateHolder(Venue venue, String loggedInUserId) { mVenueName = venue.getName(); mYou = new Group<Checkin>(); mFriends = new Group<Checkin>(); mOthers = new Group<Checkin>(); mYou.clear(); mFriends.clear(); mOthers.clear(); for (Checkin it : venue.getCheckins()) { User user = it.getUser(); if (UserUtils.isFriend(user)) { mFriends.add(it); } else if (loggedInUserId.equals(user.getId())) { mYou.add(it); } else { mOthers.add(it); } } } public String getVenueName() { return mVenueName; } public Group<Checkin> getCheckinsYou() { return mYou; } public Group<Checkin> getCheckinsFriends() { return mFriends; } public Group<Checkin> getCheckinsOthers() { return mOthers; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquare.types.Todo; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.app.LoadableListActivity; import com.joelapenna.foursquared.util.VenueUtils; import com.joelapenna.foursquared.widget.TodosListAdapter; /** * @author Mark Wyszomierski (markww@gmail.com) */ public class VenueTodosActivity extends LoadableListActivity { public static final String TAG = "VenueTodosActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".VenueTodosActivity.INTENT_EXTRA_VENUE"; public static final String INTENT_EXTRA_RETURN_VENUE = Foursquared.PACKAGE_NAME + ".VenueTodosActivity.INTENT_EXTRA_RETURN_VENUE"; private static final int ACTIVITY_TIP = 500; private TodosListAdapter mListAdapter; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; setPreparedResultIntent(); } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE)); } else { Log.e(TAG, "VenueTodosActivity requires a venue parcel its intent extras."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } private void ensureUi() { Group<Todo> todos = mStateHolder.getVenue().getTodos(); mListAdapter = new TodosListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); mListAdapter.setGroup(todos); mListAdapter.setDisplayTodoVenueTitles(false); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(true); listView.setDividerHeight(0); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // The tip that was clicked won't have its venue member set, since we got // here by viewing the parent venue. In this case, we request that the tip // activity not let the user recursively start drilling down past here. // Create a dummy venue which has only the name and address filled in. Venue venue = new Venue(); venue.setName(mStateHolder.getVenue().getName()); venue.setAddress(mStateHolder.getVenue().getAddress()); venue.setCrossstreet(mStateHolder.getVenue().getCrossstreet()); Todo todo = (Todo) parent.getAdapter().getItem(position); if (todo.getTip() != null) { todo.getTip().setVenue(venue); Intent intent = new Intent(VenueTodosActivity.this, TipActivity.class); intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, todo.getTip()); intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false); startActivityForResult(intent, ACTIVITY_TIP); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) { Tip tip = (Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED); Todo todo = data.hasExtra(TipActivity.EXTRA_TODO_RETURNED) ? (Todo)data.getParcelableExtra(TipActivity.EXTRA_TODO_RETURNED) : null; updateTip(tip, todo); } } private void updateTip(Tip tip, Todo todo) { // Changes to a tip status can produce or remove a to-do from // the venue, update it now. VenueUtils.handleTipChange(mStateHolder.getVenue(), tip, todo); // If there are no more todos, there's nothing left to.. do. prepareResultIntent(); if (mStateHolder.getVenue().getHasTodo()) { mListAdapter.notifyDataSetInvalidated(); } else { finish(); } } private void prepareResultIntent() { Intent intent = new Intent(); intent.putExtra(INTENT_EXTRA_RETURN_VENUE, mStateHolder.getVenue()); mStateHolder.setPreparedResult(intent); setPreparedResultIntent(); } private void setPreparedResultIntent() { if (mStateHolder.getPreparedResult() != null) { setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult()); } } private static class StateHolder { private Venue mVenue; private Intent mPreparedResult; public StateHolder() { mPreparedResult = null; } public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; } public Intent getPreparedResult() { return mPreparedResult; } public void setPreparedResult(Intent intent) { mPreparedResult = intent; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Settings; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.app.PingsService; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.NotificationsUtil; import android.app.Activity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.Spinner; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; /** * @date June 2, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsSettingsActivity extends Activity { private static final String TAG = "PingsSettingsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private SharedPreferences mPrefs; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; private CheckBox mCheckBoxPings; private Spinner mSpinnerInterval; private CheckBox mCheckBoxVibrate; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pings_settings_activity); setTitle(getResources().getString(R.string.pings_settings_title)); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mPrefs = PreferenceManager.getDefaultSharedPreferences(this); ensureUi(); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); if (mStateHolder.getIsRunningTaskNotifications()) { startProgressBar( getResources().getString( R.string.pings_settings_progressbar_title_pings), getResources().getString( R.string.pings_settings_progressbar_message_pings)); } } else { // Get a fresh copy of the user object in an attempt to keep the notification // setting in sync. mStateHolder = new StateHolder(this); mStateHolder.startTaskUpdateUser(this); } } private void ensureUi() { mCheckBoxPings = (CheckBox)findViewById(R.id.pings_on); mCheckBoxPings.setChecked(mPrefs.getBoolean(Preferences.PREFERENCE_PINGS, false)); mCheckBoxPings.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mStateHolder.startTaskNotifications( PingsSettingsActivity.this, mCheckBoxPings.isChecked()); } }); mSpinnerInterval = (Spinner)findViewById(R.id.pings_interval); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.pings_refresh_interval_in_minutes, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpinnerInterval.setAdapter(adapter); mSpinnerInterval.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) { String[] values = PingsSettingsActivity.this.getResources().getStringArray( R.array.pings_refresh_interval_in_minutes_values); mPrefs.edit().putString( Preferences.PREFERENCE_PINGS_INTERVAL, values[position]).commit(); restartNotifications(); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); setIntervalSpinnerFromSettings(); mCheckBoxVibrate = (CheckBox)findViewById(R.id.pings_vibrate); mCheckBoxVibrate.setChecked(mPrefs.getBoolean(Preferences.PREFERENCE_PINGS_VIBRATE, false)); mCheckBoxVibrate.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mPrefs.edit().putBoolean( Preferences.PREFERENCE_PINGS_VIBRATE, mCheckBoxVibrate.isChecked()).commit(); } }); } private void setIntervalSpinnerFromSettings() { String selected = mPrefs.getString(Preferences.PREFERENCE_PINGS_INTERVAL, "30"); String[] values = getResources().getStringArray( R.array.pings_refresh_interval_in_minutes_values); for (int i = 0; i < values.length; i++) { if (values[i].equals(selected)) { mSpinnerInterval.setSelection(i); return; } } mSpinnerInterval.setSelection(1); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public void onResume() { super.onResume(); if (mStateHolder.getIsRunningTaskNotifications()) { startProgressBar( getResources().getString( R.string.pings_settings_progressbar_title_pings), getResources().getString( R.string.pings_settings_progressbar_message_pings)); } else if (mStateHolder.getIsRunningTaskUpdateUser()) { startProgressBar( getResources().getString( R.string.pings_settings_progressbar_title_updateuser), getResources().getString( R.string.pings_settings_progressbar_message_updateuser)); } } @Override public void onPause() { super.onPause(); if (isFinishing()) { stopProgressBar(); mStateHolder.cancelTasks(); } } private void startProgressBar(String title, String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, title, message); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } private void onPostTaskPings(Settings settings, boolean changeToState, Exception reason) { if (settings == null) { NotificationsUtil.ToastReasonForFailure(this, reason); // Reset the checkbox. mCheckBoxPings.setChecked(!changeToState); } else { Toast.makeText( this, getResources().getString(R.string.pings_settings_result, settings.getPings()), Toast.LENGTH_SHORT).show(); if (settings.getPings().equals("on")) { PingsService.setupPings(this); mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, true).commit(); } else { PingsService.cancelPings(this); mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit(); } restartNotifications(); } mStateHolder.setIsRunningTaskNotifications(false); stopProgressBar(); } private void onPostTaskUserUpdate(User user, Exception reason) { if (user == null) { NotificationsUtil.ToastReasonForFailure(this, reason); finish(); } else { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( PingsSettingsActivity.this); Editor editor = prefs.edit(); Preferences.storeUser(editor, user); if (!editor.commit()) { Log.e(TAG, "Error storing user object."); } if (user.getSettings().getPings().equals("on")) { mCheckBoxPings.setChecked(true); mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, true).commit(); } else { mCheckBoxPings.setChecked(false); mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit(); } restartNotifications(); } mStateHolder.setIsRunningTaskUpdateUser(false); stopProgressBar(); } private static class UpdatePingsTask extends AsyncTask<Void, Void, Settings> { private static final String TAG = "UpdatePingsTask"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private Exception mReason; private boolean mPingsOn; private PingsSettingsActivity mActivity; public UpdatePingsTask(PingsSettingsActivity activity, boolean on) { mActivity = activity; mPingsOn = on; } @Override protected void onPreExecute() { mActivity.startProgressBar( mActivity.getResources().getString( R.string.pings_settings_progressbar_title_pings), mActivity.getResources().getString( R.string.pings_settings_progressbar_message_pings)); } @Override protected Settings doInBackground(Void... params) { if (DEBUG) Log.d(TAG, "doInBackground()"); try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.setpings(mPingsOn); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Settings settings) { if (mActivity != null) { mActivity.onPostTaskPings(settings, mPingsOn, mReason); } } public void setActivity(PingsSettingsActivity activity) { mActivity = activity; } } private static class UpdateUserTask extends AsyncTask<Void, Void, User> { private PingsSettingsActivity mActivity; private Exception mReason; public UpdateUserTask(PingsSettingsActivity activity) { mActivity = activity; } @Override protected User doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); Location location = foursquared.getLastKnownLocation(); return foursquare.user( null, false, false, false, LocationUtils .createFoursquareLocation(location)); } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (mActivity != null) { mActivity.onPostTaskUserUpdate(user, mReason); } } public void setActivity(PingsSettingsActivity activity) { mActivity = activity; } } private void restartNotifications() { PingsService.cancelPings(this); PingsService.setupPings(this); } private static class StateHolder { private UpdatePingsTask mTaskNotifications; private UpdateUserTask mTaskUpdateUser; private boolean mIsRunningTaskNotifications; private boolean mIsRunningTaskUpdateUser; public StateHolder(Context context) { mTaskNotifications = null; mTaskUpdateUser = null; mIsRunningTaskNotifications = false; mIsRunningTaskUpdateUser = false; } public void startTaskNotifications(PingsSettingsActivity activity, boolean on) { mIsRunningTaskNotifications = true; mTaskNotifications = new UpdatePingsTask(activity, on); mTaskNotifications.execute(); } public void startTaskUpdateUser(PingsSettingsActivity activity) { mIsRunningTaskUpdateUser = true; mTaskUpdateUser = new UpdateUserTask(activity); mTaskUpdateUser.execute(); } public void setActivity(PingsSettingsActivity activity) { if (mTaskNotifications != null) { mTaskNotifications.setActivity(activity); } if (mTaskUpdateUser != null) { mTaskUpdateUser.setActivity(activity); } } public boolean getIsRunningTaskNotifications() { return mIsRunningTaskNotifications; } public boolean getIsRunningTaskUpdateUser() { return mIsRunningTaskUpdateUser; } public void setIsRunningTaskNotifications(boolean isRunningTaskNotifications) { mIsRunningTaskNotifications = isRunningTaskNotifications; } public void setIsRunningTaskUpdateUser(boolean isRunningTaskUpdateUser) { mIsRunningTaskUpdateUser = isRunningTaskUpdateUser; } public void cancelTasks() { if (mTaskNotifications != null && mIsRunningTaskNotifications) { mTaskNotifications.setActivity(null); mTaskNotifications.cancel(true); } if (mTaskUpdateUser != null && mIsRunningTaskUpdateUser) { mTaskUpdateUser.setActivity(null); mTaskUpdateUser.cancel(true); } } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Response; import com.joelapenna.foursquare.types.Venue; import android.app.Activity; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.Toast; /** * Gives the user the option to correct some info about a venue: * <ul> * <li>Edit venue info</li> * <li>Flag as closed</li> * <li>Mislocated (but don't know the right address)</li> * <li>Flag as duplicate</li> * </ul> * * @date June 7, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class EditVenueOptionsActivity extends Activity { public static final String EXTRA_VENUE_PARCELABLE = "com.joelapenna.foursquared.VenueParcelable"; private static final String TAG = "EditVenueOptionsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int REQUEST_CODE_ACTIVITY_ADD_VENUE = 15; private StateHolder mStateHolder; private ProgressDialog mDlgProgress; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.edit_venue_options_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); ensureUi(); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { if (getIntent().getExtras() != null) { if (getIntent().getExtras().containsKey(EXTRA_VENUE_PARCELABLE)) { Venue venue = (Venue)getIntent().getExtras().getParcelable(EXTRA_VENUE_PARCELABLE); if (venue != null) { mStateHolder = new StateHolder(venue); } else { Log.e(TAG, "EditVenueOptionsActivity supplied with null venue parcelable."); finish(); } } else { Log.e(TAG, "EditVenueOptionsActivity requires venue parcelable in extras."); finish(); } } else { Log.e(TAG, "EditVenueOptionsActivity requires venueid in extras."); finish(); } } } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(true); if (mStateHolder.getIsRunningTaskVenue()) { startProgressBar(); } } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(); stopProgressBar(); if (isFinishing()) { mStateHolder.cancelTasks(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { Button btnEditVenue = (Button)findViewById(R.id.btnEditVenue); btnEditVenue.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(EditVenueOptionsActivity.this, AddVenueActivity.class); intent.putExtra(AddVenueActivity.EXTRA_VENUE_TO_EDIT, mStateHolder.getVenue()); startActivityForResult(intent, REQUEST_CODE_ACTIVITY_ADD_VENUE); } }); Button btnFlagAsClosed = (Button)findViewById(R.id.btnFlagAsClosed); btnFlagAsClosed.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mStateHolder.startTaskVenue( EditVenueOptionsActivity.this, VenueTask.ACTION_FLAG_AS_CLOSED); } }); Button btnFlagAsMislocated = (Button)findViewById(R.id.btnFlagAsMislocated); btnFlagAsMislocated.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mStateHolder.startTaskVenue( EditVenueOptionsActivity.this, VenueTask.ACTION_FLAG_AS_MISLOCATED); } }); Button btnFlagAsDuplicate = (Button)findViewById(R.id.btnFlagAsDuplicate); btnFlagAsDuplicate.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mStateHolder.startTaskVenue( EditVenueOptionsActivity.this, VenueTask.ACTION_FLAG_AS_DUPLICATE); } }); } private void startProgressBar() { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, null, getResources().getString(R.string.edit_venue_options_progress_message)); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } private void onVenueTaskComplete(Response response, Exception ex) { stopProgressBar(); mStateHolder.setIsRunningTaskVenue(false); if (response != null) { if (!TextUtils.isEmpty(response.getValue()) && response.getValue().equals("ok")) { Toast.makeText(this, getResources().getString(R.string.edit_venue_options_thankyou), Toast.LENGTH_SHORT).show(); finish(); } else { Toast.makeText(this, getResources().getString(R.string.edit_venue_options_error), Toast.LENGTH_SHORT).show(); } } else { // The API is returning an incorrect response object here, it should look like: // { response: { "response": "ok" }} // Instead it's just returning: // { "response": "ok" } // So the parser framework will fail on it. This should be fixed with api v2, // just going to assume success here. //NotificationsUtil.ToastReasonForFailure(this, ex); Toast.makeText(this, getResources().getString(R.string.edit_venue_options_thankyou), Toast.LENGTH_SHORT).show(); } } private static class VenueTask extends AsyncTask<Void, Void, Response> { public static final int ACTION_FLAG_AS_CLOSED = 0; public static final int ACTION_FLAG_AS_MISLOCATED = 1; public static final int ACTION_FLAG_AS_DUPLICATE = 2; private EditVenueOptionsActivity mActivity; private Exception mReason; private int mAction; private String mVenueId; public VenueTask(EditVenueOptionsActivity activity, int action, String venueId) { mActivity = activity; mAction = action; mVenueId = venueId; } @Override protected void onPreExecute() { mActivity.startProgressBar(); } @Override protected Response doInBackground(Void... params) { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); try { switch (mAction) { case ACTION_FLAG_AS_CLOSED: return foursquare.flagclosed(mVenueId); case ACTION_FLAG_AS_MISLOCATED: return foursquare.flagmislocated(mVenueId); case ACTION_FLAG_AS_DUPLICATE: return foursquare.flagduplicate(mVenueId); } } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Response response) { if (mActivity != null) { mActivity.onVenueTaskComplete(response, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onVenueTaskComplete(null, mReason); } } public void setActivity(EditVenueOptionsActivity activity) { mActivity = activity; } } private static class StateHolder { private Venue mVenue; private VenueTask mTaskVenue; private boolean mIsRunningTaskVenue; public StateHolder(Venue venue) { mVenue = venue; mIsRunningTaskVenue = false; } public Venue getVenue() { return mVenue; } public void startTaskVenue(EditVenueOptionsActivity activity, int action) { mIsRunningTaskVenue = true; mTaskVenue = new VenueTask(activity, action, mVenue.getId()); mTaskVenue.execute(); } public void setActivity(EditVenueOptionsActivity activity) { if (mTaskVenue != null) { mTaskVenue.setActivity(activity); } } public boolean getIsRunningTaskVenue() { return mIsRunningTaskVenue; } public void setIsRunningTaskVenue(boolean isRunning) { mIsRunningTaskVenue = isRunning; } public void cancelTasks() { if (mTaskVenue != null) { mTaskVenue.setActivity(null); mTaskVenue.cancel(true); mIsRunningTaskVenue = false; } } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.maps; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.FoursquaredSettings; import android.graphics.drawable.Drawable; import android.util.Log; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueItemizedOverlay extends BaseGroupItemizedOverlay<Venue> { public static final String TAG = "VenueItemizedOverlay"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private boolean mPopulatedSpans = false; private SpanHolder mSpanHolder = new SpanHolder(); public VenueItemizedOverlay(Drawable defaultMarker) { super(defaultMarker); } @Override protected OverlayItem createItem(int i) { Venue venue = (Venue)group.get(i); if (DEBUG) Log.d(TAG, "creating venue overlayItem: " + venue.getName()); int lat = (int)(Double.parseDouble(venue.getGeolat()) * 1E6); int lng = (int)(Double.parseDouble(venue.getGeolong()) * 1E6); GeoPoint point = new GeoPoint(lat, lng); return new VenueOverlayItem(point, venue); } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (DEBUG) Log.d(TAG, "onTap: " + p); mapView.getController().animateTo(p); return super.onTap(p, mapView); } @Override public int getLatSpanE6() { if (!mPopulatedSpans) { populateSpans(); } return mSpanHolder.latSpanE6; } @Override public int getLonSpanE6() { if (!mPopulatedSpans) { populateSpans(); } return mSpanHolder.lonSpanE6; } private void populateSpans() { int maxLat = 0; int minLat = 0; int maxLon = 0; int minLon = 0; for (int i = 0; i < group.size(); i++) { Venue venue = (Venue)group.get(i); if (VenueUtils.hasValidLocation(venue)) { int lat = (int)(Double.parseDouble(venue.getGeolat()) * 1E6); int lon = (int)(Double.parseDouble(venue.getGeolong()) * 1E6); // LatSpan if (lat > maxLat || maxLat == 0) { maxLat = lat; } if (lat < minLat || minLat == 0) { minLat = lat; } // LonSpan if (lon < minLon || minLon == 0) { minLon = lon; } if (lon > maxLon || maxLon == 0) { maxLon = lon; } } } mSpanHolder.latSpanE6 = maxLat - minLat; mSpanHolder.lonSpanE6 = maxLon - minLon; } public static class VenueOverlayItem extends OverlayItem { private Venue mVenue; public VenueOverlayItem(GeoPoint point, Venue venue) { super(point, venue.getName(), venue.getAddress()); mVenue = venue; } public Venue getVenue() { return mVenue; } } public static final class SpanHolder { int latSpanE6 = 0; int lonSpanE6 = 0; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.maps; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.util.DumpcatcherHelper; import android.content.Context; import android.graphics.Canvas; import android.util.Log; /** * See: <a href="http://groups.google.com/group/android-developers/browse_thread/thread/43615742f462bbf1/8918ddfc92808c42?" * >MyLocationOverlay causing crash in 1.6 (Donut)</a> * * @author Joe LaPenna (joe@joelapenna.com) */ public class CrashFixMyLocationOverlay extends MyLocationOverlay { static final String TAG = "CrashFixMyLocationOverlay"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public CrashFixMyLocationOverlay(Context context, MapView mapView) { super(context, mapView); } @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { try { return super.draw(canvas, mapView, shadow, when); } catch (ClassCastException e) { if (DEBUG) Log.d(TAG, "Encountered overlay crash bug", e); DumpcatcherHelper.sendException(e); return false; } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.maps; import com.google.android.maps.GeoPoint; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.FoursquaredSettings; import android.graphics.drawable.Drawable; import android.util.Log; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract class BaseGroupItemizedOverlay<T extends FoursquareType> extends ItemizedOverlay<OverlayItem> { public static final String TAG = "BaseGroupItemizedOverlay"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; Group<T> group = null; public BaseGroupItemizedOverlay(Drawable defaultMarker) { super(boundCenterBottom(defaultMarker)); } @Override public int size() { if (group == null) { return 0; } return group.size(); } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (DEBUG) Log.d(TAG, "onTap: " + group.getType() + " " + p); return super.onTap(p, mapView); } @Override protected boolean onTap(int i) { if (DEBUG) Log.d(TAG, "onTap: " + group.getType() + " " + i); return super.onTap(i); } public void setGroup(Group<T> g) { assert g.getType() != null; group = g; super.populate(); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.maps; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.util.StringFormatters; /** * * @date June 18, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class CheckinGroup implements FoursquareType { private Venue mVenue; private String mDescription; private String mPhotoUrl; private String mGender; private int mCheckinCount; private int mLatE6; private int mLonE6; public CheckinGroup() { mVenue = null; mDescription = ""; mPhotoUrl = ""; mCheckinCount = 0; mGender = Foursquare.MALE; } public void appendCheckin(Checkin checkin) { User user = checkin.getUser(); if (mCheckinCount == 0) { mPhotoUrl = user.getPhoto(); mGender = user.getGender(); mDescription += StringFormatters.getUserAbbreviatedName(user); Venue venue = checkin.getVenue(); mVenue = venue; mLatE6 = (int)(Double.parseDouble(venue.getGeolat()) * 1E6); mLonE6 = (int)(Double.parseDouble(venue.getGeolong()) * 1E6); } else { mDescription += ", " + StringFormatters.getUserAbbreviatedName(user); } mCheckinCount++; } public Venue getVenue() { return mVenue; } public int getLatE6() { return mLatE6; } public int getLonE6() { return mLonE6; } public String getDescription() { return mDescription; } public String getPhotoUrl() { return mPhotoUrl; } public String getGender() { return mGender; } public int getCheckinCount() { return mCheckinCount; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.maps; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquared.FoursquaredSettings; import android.graphics.drawable.Drawable; import android.util.Log; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class CheckinItemizedOverlay extends BaseGroupItemizedOverlay<Checkin> { public static final String TAG = "CheckinItemizedOverlay"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public CheckinItemizedOverlay(Drawable defaultMarker) { super(defaultMarker); } @Override protected OverlayItem createItem(int i) { Checkin checkin = (Checkin)group.get(i); if (DEBUG) Log.d(TAG, "creating checkin overlayItem: " + checkin.getVenue().getName()); int lat = (int)(Double.parseDouble(checkin.getVenue().getGeolat()) * 1E6); int lng = (int)(Double.parseDouble(checkin.getVenue().getGeolong()) * 1E6); GeoPoint point = new GeoPoint(lat, lng); return new CheckinOverlayItem(point, checkin); } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (DEBUG) Log.d(TAG, "onTap: " + p); return super.onTap(p, mapView); } public static class CheckinOverlayItem extends OverlayItem { private Checkin mCheckin; public CheckinOverlayItem(GeoPoint point, Checkin checkin) { super(point, checkin.getVenue().getName(), checkin.getVenue().getAddress()); mCheckin = checkin; } public Checkin getCheckin() { return mCheckin; } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.maps; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.Tip; import com.joelapenna.foursquared.FoursquaredSettings; import android.graphics.drawable.Drawable; import android.util.Log; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class TipItemizedOverlay extends BaseGroupItemizedOverlay<Tip> { public static final String TAG = "TipItemizedOverlay"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public TipItemizedOverlay(Drawable defaultMarker) { super(defaultMarker); } @Override protected OverlayItem createItem(int i) { Tip tip = (Tip)group.get(i); if (DEBUG) Log.d(TAG, "creating tip overlayItem: " + tip.getVenue().getName()); int lat = (int)(Double.parseDouble(tip.getVenue().getGeolat()) * 1E6); int lng = (int)(Double.parseDouble(tip.getVenue().getGeolong()) * 1E6); GeoPoint point = new GeoPoint(lat, lng); return new TipOverlayItem(point, tip); } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (DEBUG) Log.d(TAG, "onTap: " + p); mapView.getController().animateTo(p); return super.onTap(p, mapView); } public static class TipOverlayItem extends OverlayItem { private Tip mTip; public TipOverlayItem(GeoPoint point, Tip tip) { super(point, tip.getVenue().getName(), tip.getVenue().getAddress()); mTip = tip; } public Tip getTip() { return mTip; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.maps; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.GeoUtils; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import java.io.IOException; /** * @date June 30, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class VenueItemizedOverlayWithIcons extends BaseGroupItemizedOverlay<Venue> { public static final String TAG = "VenueItemizedOverlay2"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private Context mContext; private RemoteResourceManager mRrm; private OverlayItem mLastSelected; private VenueItemizedOverlayTapListener mTapListener; public VenueItemizedOverlayWithIcons(Context context, RemoteResourceManager rrm, Drawable defaultMarker, VenueItemizedOverlayTapListener tapListener) { super(defaultMarker); mContext = context; mRrm = rrm; mTapListener = tapListener; mLastSelected = null; } @Override protected OverlayItem createItem(int i) { Venue venue = (Venue)group.get(i); GeoPoint point = GeoUtils.stringLocationToGeoPoint( venue.getGeolat(), venue.getGeolong()); return new VenueOverlayItem(point, venue, mContext, mRrm); } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (mTapListener != null) { mTapListener.onTap(p, mapView); } return super.onTap(p, mapView); } @Override public boolean onTap(int i) { if (mTapListener != null) { mTapListener.onTap(getItem(i), mLastSelected, group.get(i)); } mLastSelected = getItem(i); return true; } @Override public void draw(android.graphics.Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, false); } public static class VenueOverlayItem extends OverlayItem { private Venue mVenue; public VenueOverlayItem(GeoPoint point, Venue venue, Context context, RemoteResourceManager rrm) { super(point, venue.getName(), venue.getAddress()); mVenue = venue; constructPinDrawable(venue, context, rrm); } public Venue getVenue() { return mVenue; } private static int dddi(int dd, float screenDensity) { return (int)(dd * screenDensity + 0.5f); } private void constructPinDrawable(Venue venue, Context context, RemoteResourceManager rrm) { float screenDensity = context.getResources().getDisplayMetrics().density; int cx = dddi(32, screenDensity); int cy = dddi(32, screenDensity); Bitmap bmp = Bitmap.createBitmap(cx, cy, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); Paint paint = new Paint(); boolean laodedPin = false; if (venue.getCategory() != null) { Uri photoUri = Uri.parse(venue.getCategory().getIconUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(photoUri)); canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), new Rect(0, 0, cx, cy), paint); laodedPin = true; } catch (IOException e) { } } if (!laodedPin) { Drawable drw = context.getResources().getDrawable(R.drawable.category_none); drw.draw(canvas); } Drawable bd = new BitmapDrawable(bmp); bd.setBounds(-cx / 2, -cy, cx / 2, 0); setMarker(bd); } } public interface VenueItemizedOverlayTapListener { public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, Venue venue); public void onTap(GeoPoint p, MapView mapView); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.maps; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import java.io.IOException; /** * @date June 18, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class CheckinGroupItemizedOverlay extends BaseGroupItemizedOverlay<CheckinGroup> { public static final String TAG = "CheckinItemizedGroupOverlay"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private Context mContext; private RemoteResourceManager mRrm; private Bitmap mBmpPinSingle; private Bitmap mBmpPinMultiple; private OverlayItem mLastSelected; private CheckinGroupOverlayTapListener mTapListener; public CheckinGroupItemizedOverlay(Context context, RemoteResourceManager rrm, Drawable defaultMarker, CheckinGroupOverlayTapListener tapListener) { super(defaultMarker); mContext = context; mRrm = rrm; mTapListener = tapListener; mLastSelected = null; constructScaledPinBackgrounds(context); } @Override protected OverlayItem createItem(int i) { CheckinGroup cg = (CheckinGroup)group.get(i); GeoPoint point = new GeoPoint(cg.getLatE6(), cg.getLonE6()); return new CheckinGroupOverlayItem(point, cg, mContext, mRrm, mBmpPinSingle, mBmpPinMultiple); } @Override public boolean onTap(GeoPoint p, MapView mapView) { if (mTapListener != null) { mTapListener.onTap(p, mapView); } return super.onTap(p, mapView); } @Override public boolean onTap(int i) { if (mTapListener != null) { mTapListener.onTap(getItem(i), mLastSelected, group.get(i)); } mLastSelected = getItem(i); return true; } @Override public void draw(android.graphics.Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, false); } private void constructScaledPinBackgrounds(Context context) { Drawable drwSingle = context.getResources().getDrawable(R.drawable.pin_checkin_single); Drawable drwMultiple = context.getResources().getDrawable(R.drawable.pin_checkin_multiple); drwSingle.setBounds(0, 0, drwSingle.getIntrinsicWidth(), drwSingle.getIntrinsicHeight()); drwMultiple.setBounds(0, 0, drwMultiple.getIntrinsicWidth(), drwMultiple.getIntrinsicHeight()); mBmpPinSingle = drawableToBitmap(drwSingle); mBmpPinMultiple = drawableToBitmap(drwMultiple); } private Bitmap drawableToBitmap(Drawable drw) { Bitmap bmp = Bitmap.createBitmap( drw.getIntrinsicWidth(), drw.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); drw.draw(canvas); return bmp; } private static int dddi(int dd, float screenDensity) { return (int)(dd * screenDensity + 0.5f); } public static class CheckinGroupOverlayItem extends OverlayItem { private CheckinGroup mCheckinGroup; public CheckinGroupOverlayItem(GeoPoint point, CheckinGroup cg, Context context, RemoteResourceManager rrm, Bitmap bmpPinSingle, Bitmap bmpPinMultiple) { super(point, cg.getVenue().getName(), cg.getVenue().getAddress()); mCheckinGroup = cg; constructPinDrawable(cg, context, rrm, bmpPinSingle, bmpPinMultiple); } public CheckinGroup getCheckin() { return mCheckinGroup; } private void constructPinDrawable(CheckinGroup cg, Context context, RemoteResourceManager rrm, Bitmap bmpPinSingle, Bitmap bmpPinMultiple) { // The mdpi size of the photo background is 52 x 58. // The user's photo should begin at origin (9, 12). // The user's photo should be 34 x 34. float screenDensity = context.getResources().getDisplayMetrics().density; int cx = dddi(52, screenDensity); int cy = dddi(58, screenDensity); int pox = dddi(9, screenDensity); int poy = dddi(12, screenDensity); int pcx = cx - (pox * 2); int pcy = cy - (poy * 2); Bitmap bmp = Bitmap.createBitmap(cx, cy, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); Paint paint = new Paint(); // Draw the correct background pin image. if (cg.getCheckinCount() < 2) { canvas.drawBitmap(bmpPinSingle, new Rect(0, 0, bmpPinSingle.getWidth(), bmpPinSingle.getHeight()), new Rect(0, 0, cx, cy), paint); } else { canvas.drawBitmap(bmpPinMultiple, new Rect(0, 0, bmpPinMultiple.getWidth(), bmpPinMultiple.getHeight()), new Rect(0, 0, cx, cy), paint); } // Put the user's photo on top. Uri photoUri = Uri.parse(cg.getPhotoUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(photoUri)); canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()), new Rect(pox, poy, pox + pcx, poy + pcy), paint); } catch (IOException e) { // If the user's photo isn't already in the cache, don't try loading it, // use a default user pin. Drawable drw2 = null; if (Foursquare.MALE.equals(cg.getGender())) { drw2 = context.getResources().getDrawable(R.drawable.blank_boy); } else { drw2 = context.getResources().getDrawable(R.drawable.blank_girl); } drw2.draw(canvas); } Drawable bd = new BitmapDrawable(bmp); bd.setBounds(-cx / 2, -cy, cx / 2, 0); setMarker(bd); } } public interface CheckinGroupOverlayTapListener { public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, CheckinGroup cg); public void onTap(GeoPoint p, MapView mapView); } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquared.app.LoadableListActivity; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.widget.HistoryListAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * This only works for the currently authenticated user. * * @date March 9, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserHistoryActivity extends LoadableListActivity { static final String TAG = "UserHistoryActivity"; public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME + ".UserHistoryActivity.EXTRA_USER_NAME"; private StateHolder mStateHolder; private HistoryListAdapter mListAdapter; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTaskFriends(this); } else { if (getIntent().hasExtra(EXTRA_USER_NAME)) { mStateHolder = new StateHolder(getIntent().getStringExtra(EXTRA_USER_NAME)); mStateHolder.startTaskHistory(this); } else { Log.e(TAG, TAG + " requires username as intent extra."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mStateHolder.cancelTasks(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTaskFriends(null); return mStateHolder; } private void ensureUi() { mListAdapter = new HistoryListAdapter( this, ((Foursquared) getApplication()).getRemoteResourceManager()); mListAdapter.setGroup(mStateHolder.getHistory()); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(true); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) { Object obj = (Object)mListAdapter.getItem(position); if (obj != null) { startVenueActivity((Checkin)obj); } } }); if (mStateHolder.getIsRunningHistoryTask()) { setLoadingView(); } else if (mStateHolder.getFetchedOnce() && mStateHolder.getHistory().size() == 0) { setEmptyView(); } setTitle(getString(R.string.user_history_activity_title, mStateHolder.getUsername())); } @Override public int getNoSearchResultsStringId() { return R.string.user_history_activity_no_info; } private void onHistoryTaskComplete(Group<Checkin> group, Exception ex) { mListAdapter = new HistoryListAdapter( this, ((Foursquared) getApplication()).getRemoteResourceManager()); if (group != null) { mStateHolder.setHistory(group); mListAdapter.setGroup(mStateHolder.getHistory()); getListView().setAdapter(mListAdapter); } else { mStateHolder.setHistory(new Group<Checkin>()); mListAdapter.setGroup(mStateHolder.getHistory()); getListView().setAdapter(mListAdapter); NotificationsUtil.ToastReasonForFailure(this, ex); } mStateHolder.setIsRunningHistoryTask(false); mStateHolder.setFetchedOnce(true); // TODO: Can tighten this up by just calling ensureUI() probably. if (mStateHolder.getHistory().size() == 0) { setEmptyView(); } } private void startVenueActivity(Checkin checkin) { if (checkin != null) { if (checkin.getVenue() != null && !TextUtils.isEmpty(checkin.getVenue().getId())) { Venue venue = checkin.getVenue(); Intent intent = new Intent(this, VenueActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue); startActivity(intent); } else { Log.e(TAG, "Venue has no ID to start venue activity."); } } } /** * Gets friends of the current user we're working for. */ private static class HistoryTask extends AsyncTask<String, Void, Group<Checkin>> { private UserHistoryActivity mActivity; private Exception mReason; public HistoryTask(UserHistoryActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.setLoadingView(); } @Override protected Group<Checkin> doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); // Prune out shouts for now. Group<Checkin> history = foursquare.history("50", null); Group<Checkin> venuesOnly = new Group<Checkin>(); for (Checkin it : history) { if (it.getVenue() != null) { venuesOnly.add(it); } } return venuesOnly; } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Group<Checkin> checkins) { if (mActivity != null) { mActivity.onHistoryTaskComplete(checkins, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onHistoryTaskComplete(null, mReason); } } public void setActivity(UserHistoryActivity activity) { mActivity = activity; } } private static class StateHolder { private String mUsername; private Group<Checkin> mHistory; private HistoryTask mTaskHistory; private boolean mIsRunningHistoryTask; private boolean mFetchedOnce; public StateHolder(String username) { mUsername = username; mIsRunningHistoryTask = false; mFetchedOnce = false; mHistory = new Group<Checkin>(); } public String getUsername() { return mUsername; } public Group<Checkin> getHistory() { return mHistory; } public void setHistory(Group<Checkin> history) { mHistory = history; } public void startTaskHistory(UserHistoryActivity activity) { mIsRunningHistoryTask = true; mTaskHistory = new HistoryTask(activity); mTaskHistory.execute(); } public void setActivityForTaskFriends(UserHistoryActivity activity) { if (mTaskHistory != null) { mTaskHistory.setActivity(activity); } } public void setIsRunningHistoryTask(boolean isRunning) { mIsRunningHistoryTask = isRunning; } public boolean getIsRunningHistoryTask() { return mIsRunningHistoryTask; } public void setFetchedOnce(boolean fetchedOnce) { mFetchedOnce = fetchedOnce; } public boolean getFetchedOnce() { return mFetchedOnce; } public void cancelTasks() { if (mTaskHistory != null) { mTaskHistory.setActivity(null); mTaskHistory.cancel(true); } } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquared.preferences.Preferences; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; /** * Can be presented as a dialog theme, collects data from the user for a checkin or a * shout. The foursquare api is the same for checkins and shouts. A checkin should just * contain a venue id. * * After the user has entered their data, this activity will finish itself and call * either CheckinExecuteActivity or ShoutExecuteActivity. The only real difference * between them is what's displayed at the conclusion of the execution. * * If doing a checkin, the user can also skip this activity and do a 'quick' checkin * by launching CheckinExecuteActivity directly. This will just use their saved preferences * to checkin at the specified venue, no optional shout message will be attached to * the checkin. * * This dialog allows the user to supply the following information: * * <ul> * <li>Tell my Friends [yes|no]</li> * <li>Tell Twitter [yes|no]</li> * <li>Tell Facebook [yes|no]</li> * <li>EditField for freeform shout text.</li> * </ul> * * @date March 2, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class CheckinOrShoutGatherInfoActivity extends Activity { public static final String TAG = "CheckinOrShoutGatherInfoActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_IS_CHECKIN = Foursquared.PACKAGE_NAME + ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_CHECKIN"; public static final String INTENT_EXTRA_IS_SHOUT = Foursquared.PACKAGE_NAME + ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_SHOUT"; public static final String INTENT_EXTRA_VENUE_ID = Foursquared.PACKAGE_NAME + ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_ID"; public static final String INTENT_EXTRA_VENUE_NAME = Foursquared.PACKAGE_NAME + ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_NAME"; public static final String INTENT_EXTRA_TEXT_PREPOPULATE = Foursquared.PACKAGE_NAME + ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_TEXT_PREPOPULATE"; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); setContentView(R.layout.checkin_or_shout_gather_info_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { if (getIntent().getExtras() != null) { if (getIntent().getBooleanExtra(INTENT_EXTRA_IS_CHECKIN, false)) { // If a checkin, we require venue id and name. String venueId = null; if (getIntent().getExtras().containsKey(INTENT_EXTRA_VENUE_ID)) { venueId = getIntent().getExtras().getString(INTENT_EXTRA_VENUE_ID); } else { Log.e(TAG, "CheckinOrShoutGatherInfoActivity requires intent extra INTENT_EXTRA_VENUE_ID for action type checkin."); finish(); return; } String venueName = null; if (getIntent().getExtras().containsKey(INTENT_EXTRA_VENUE_NAME)) { venueName = getIntent().getExtras().getString(INTENT_EXTRA_VENUE_NAME); } else { Log.e(TAG, "CheckinOrShoutGatherInfoActivity requires intent extra INTENT_EXTRA_VENUE_NAME for action type checkin."); finish(); return; } mStateHolder = new StateHolder(true, venueId, venueName); } else if (getIntent().getBooleanExtra(INTENT_EXTRA_IS_SHOUT, false)) { // If a shout, we don't require anything at all. mStateHolder = new StateHolder(false, null, null); } else { Log.e(TAG, "CheckinOrShoutGatherInfoActivity requires intent extra parameter for action type."); finish(); return; } if (getIntent().hasExtra(INTENT_EXTRA_TEXT_PREPOPULATE)) { EditText editShout = (EditText)findViewById(R.id.editTextShout); editShout.setText(getIntent().getStringExtra(INTENT_EXTRA_TEXT_PREPOPULATE)); } } else { Log.e(TAG, "CheckinOrShoutGatherInfoActivity requires intent extras parameters, none found."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } private void ensureUi() { if (mStateHolder.getIsCheckin()) { setTitle(getResources().getString(R.string.checkin_title_checking_in, mStateHolder.getVenueName())); } else { setTitle(getResources().getString(R.string.shout_action_label)); } SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); CheckBox cbTellFriends = (CheckBox)findViewById(R.id.checkboxTellFriends); cbTellFriends.setChecked(settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, true)); CheckBox cbTellFollowers = (CheckBox)findViewById(R.id.checkboxTellFollowers); if (settings.getBoolean(Preferences.PREFERENCE_CAN_HAVE_FOLLOWERS, false)) { cbTellFollowers.setVisibility(View.VISIBLE); } CheckBox cbTellTwitter = (CheckBox)findViewById(R.id.checkboxTellTwitter); if (settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, false) && !TextUtils.isEmpty(settings.getString(Preferences.PREFERENCE_TWITTER_HANDLE, ""))) { cbTellTwitter.setChecked(true); } CheckBox cbTellFacebook = (CheckBox)findViewById(R.id.checkboxTellFacebook); if (settings.getBoolean(Preferences.PREFERENCE_FACEBOOK_CHECKIN, false) && !TextUtils.isEmpty(settings.getString(Preferences.PREFERENCE_FACEBOOK_HANDLE, ""))) { cbTellFacebook.setChecked(true); } Button btnCheckin = (Button)findViewById(R.id.btnCheckin); if (mStateHolder.getIsCheckin()) { btnCheckin.setText(getResources().getString(R.string.checkin_action_label)); } else { btnCheckin.setText(getResources().getString(R.string.shout_action_label)); } btnCheckin.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { checkin(); } }); } private void checkin() { CheckBox cbTellFriends = (CheckBox)findViewById(R.id.checkboxTellFriends); CheckBox cbTellFollowers = (CheckBox)findViewById(R.id.checkboxTellFollowers); CheckBox cbTellTwitter = (CheckBox)findViewById(R.id.checkboxTellTwitter); CheckBox cbTellFacebook = (CheckBox)findViewById(R.id.checkboxTellFacebook); EditText editShout = (EditText)findViewById(R.id.editTextShout); // After we start the activity, we don't have to stick around any longer. // We want to forward the resultCode of CheckinExecuteActivity to our // caller though, so add the FLAG_ACTIVITY_FORWARD_RESULT on the intent. Intent intent = new Intent(); if (mStateHolder.getIsCheckin()) { intent.setClass(this, CheckinExecuteActivity.class); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.getVenueId()); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_SHOUT, editShout.getText().toString()); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FRIENDS, cbTellFriends.isChecked()); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FOLLOWERS, cbTellFollowers.isChecked()); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_TWITTER, cbTellTwitter.isChecked()); intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK, cbTellFacebook.isChecked()); } else { intent.setClass(this, ShoutExecuteActivity.class); intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_SHOUT, editShout.getText().toString()); intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_TELL_FRIENDS, cbTellFriends.isChecked()); intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_TELL_FOLLOWERS, cbTellFollowers.isChecked()); intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_TELL_TWITTER, cbTellTwitter.isChecked()); intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK, cbTellFacebook.isChecked()); } intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT); startActivity(intent); finish(); } private static class StateHolder { private boolean mIsCheckin; // either a checkin, or a shout. private String mVenueId; private String mVenueName; public StateHolder(boolean isCheckin, String venueId, String venueName) { mIsCheckin = isCheckin; mVenueId = venueId; mVenueName = venueName; } public boolean getIsCheckin() { return mIsCheckin; } public String getVenueId() { return mVenueId; } public String getVenueName() { return mVenueName; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.ImageUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; /** * Takes a path to an image, then displays it by filling all available space while * retaining w/h ratio. This is meant to be a (poor) replacement to the native * image viewer intent on some devices. For example, the nexus-one gallery viewer * takes about 11 seconds to start up when using the following: * * Intent intent = new Intent(android.content.Intent.ACTION_VIEW); * intent.setDataAndType(uri, "image/" + extension); * startActivity(intent); * * other devices might have their own issues. * * We can support zooming/panning later on if it's important to users. * * No attempt is made to check the size of the input image, for now we're trusting * the foursquare api is keeping these images < 200kb. * * The INTENT_EXTRA_ALLOW_SET_NEW_PHOTO flag lets the user pick a new photo from * their phone for their user profile. * * @date July 28, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class FullSizeImageActivity extends Activity { private static final String TAG = "FullSizeImageActivity"; public static final String INTENT_EXTRA_IMAGE_PATH = Foursquared.PACKAGE_NAME + ".FullSizeImageActivity.INTENT_EXTRA_IMAGE_PATH"; public static final String INTENT_EXTRA_ALLOW_SET_NEW_PHOTO = Foursquared.PACKAGE_NAME + ".FullSizeImageActivity.INTENT_EXTRA_ALLOW_SET_NEW_PHOTO"; public static final String INTENT_RETURN_NEW_PHOTO_PATH_DISK = Foursquared.PACKAGE_NAME + ".FullSizeImageActivity.INTENT_RETURN_NEW_PHOTO_PATH_DISK"; public static final String INTENT_RETURN_NEW_PHOTO_URL = Foursquared.PACKAGE_NAME + ".FullSizeImageActivity.INTENT_RETURN_NEW_PHOTO_URL"; private static final int ACTIVITY_REQUEST_CODE_GALLERY = 500; private static final int DIALOG_SET_USER_PHOTO_YES_NO = 500; private StateHolder mStateHolder; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.full_size_image_activity); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); setPreparedResultIntent(); } else { String imagePath = getIntent().getStringExtra(INTENT_EXTRA_IMAGE_PATH); if (!TextUtils.isEmpty(imagePath)) { mStateHolder = new StateHolder(); mStateHolder.setImagePath(imagePath); mStateHolder.setAllowSetPhoto(getIntent().getBooleanExtra( INTENT_EXTRA_ALLOW_SET_NEW_PHOTO, false)); } else { Log.e(TAG, TAG + " requires input image path as an intent extra."); finish(); return; } } ensureUi(); } private void ensureUi() { ImageView iv = (ImageView)findViewById(R.id.imageView); try { Bitmap bmp = BitmapFactory.decodeFile(mStateHolder.getImagePath()); iv.setImageBitmap(bmp); } catch (Exception ex) { Log.e(TAG, "Couldn't load supplied image.", ex); finish(); return; } LinearLayout llSetPhoto = (LinearLayout)findViewById(R.id.setPhotoOption); Button btnSetPhoto = (Button)findViewById(R.id.setPhotoOptionBtn); if (mStateHolder.getAllowSetPhoto()) { llSetPhoto.setVisibility(View.VISIBLE); btnSetPhoto.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { startGalleryIntent(); } }); } else { llSetPhoto.setVisibility(View.GONE); } if (mStateHolder.getIsRunningTaskSetPhoto()) { setProgressBarIndeterminateVisibility(true); btnSetPhoto.setEnabled(false); } else { setProgressBarIndeterminateVisibility(false); btnSetPhoto.setEnabled(true); } } private void startGalleryIntent() { try { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, ACTIVITY_REQUEST_CODE_GALLERY); } catch (Exception ex) { Toast.makeText(this, getResources().getString(R.string.user_details_activity_error_no_photo_gallery), Toast.LENGTH_SHORT).show(); } } private void prepareResultIntent(String newPhotoUrl) { Intent intent = new Intent(); intent.putExtra(INTENT_RETURN_NEW_PHOTO_PATH_DISK, mStateHolder.getImagePath()); intent.putExtra(INTENT_RETURN_NEW_PHOTO_URL, newPhotoUrl); mStateHolder.setPreparedResult(intent); setPreparedResultIntent(); } private void setPreparedResultIntent() { if (mStateHolder.getPreparedResult() != null) { setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult()); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String pathInput = null; switch (requestCode) { case ACTIVITY_REQUEST_CODE_GALLERY: if (resultCode == Activity.RESULT_OK) { try { String [] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(data.getData(), proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); pathInput = cursor.getString(column_index); } catch (Exception ex) { Toast.makeText(this, getResources().getString(R.string.user_details_activity_error_set_photo_load), Toast.LENGTH_SHORT).show(); } // If everything worked ok, ask the user if they're sure they want to upload? try { String pathOutput = Environment.getExternalStorageDirectory() + "/tmp_fsquare.jpg"; ImageUtils.resampleImageAndSaveToNewLocation(pathInput, pathOutput); mStateHolder.setImagePath(pathOutput); ensureUi(); showDialog(DIALOG_SET_USER_PHOTO_YES_NO); } catch (Exception ex) { Toast.makeText(this, getResources().getString(R.string.user_details_activity_error_set_photo_resample), Toast.LENGTH_SHORT).show(); } } else { return; } break; } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_SET_USER_PHOTO_YES_NO: return new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.user_details_activity_set_photo_confirm_title)) .setMessage(getResources().getString(R.string.user_details_activity_set_photo_confirm_message)) .setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(FullSizeImageActivity.this); String username = sp.getString(Preferences.PREFERENCE_LOGIN, ""); String password = sp.getString(Preferences.PREFERENCE_PASSWORD, ""); mStateHolder.startTaskSetPhoto( FullSizeImageActivity.this, mStateHolder.getImagePath(), username, password); } }) .setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { } }) .create(); default: return null; } } private void onTaskSetPhotoCompleteStart() { ensureUi(); } private void onTaskSetPhotoComplete(User user, Exception ex) { mStateHolder.setIsRunningTaskSetPhoto(false); if (user != null) { Toast.makeText(this, "Photo set ok!", Toast.LENGTH_SHORT).show(); prepareResultIntent(user.getPhoto()); } else { NotificationsUtil.ToastReasonForFailure(this, ex); } ensureUi(); } private static class TaskSetPhoto extends AsyncTask<String, Void, User> { private FullSizeImageActivity mActivity; private Exception mReason; public TaskSetPhoto(FullSizeImageActivity activity) { mActivity = activity; } public void setActivity(FullSizeImageActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.onTaskSetPhotoCompleteStart(); } /** Params should be image path, username, password. */ @Override protected User doInBackground(String... params) { try { return ((Foursquared) mActivity.getApplication()).getFoursquare().userUpdate( params[0], params[1], params[2]); } catch (Exception ex) { Log.e(TAG, "Error submitting new profile photo.", ex); mReason = ex; } return null; } @Override protected void onPostExecute(User user) { if (mActivity != null) { mActivity.onTaskSetPhotoComplete(user, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskSetPhotoComplete(null, new FoursquareException( mActivity.getResources().getString(R.string.user_details_activity_set_photo_cancel))); } } } private static class StateHolder { private String mImagePath; private boolean mAllowSetPhoto; private boolean mIsRunningTaskSetPhoto; private TaskSetPhoto mTaskSetPhoto; private Intent mPreparedResult; public StateHolder() { mAllowSetPhoto = false; mIsRunningTaskSetPhoto = false; } public String getImagePath() { return mImagePath; } public void setImagePath(String imagePath) { mImagePath = imagePath; } public boolean getAllowSetPhoto() { return mAllowSetPhoto; } public void setAllowSetPhoto(boolean allowSetPhoto) { mAllowSetPhoto = allowSetPhoto; } public boolean getIsRunningTaskSetPhoto() { return mIsRunningTaskSetPhoto; } public void setIsRunningTaskSetPhoto(boolean isRunning) { mIsRunningTaskSetPhoto = isRunning; } public void setActivity(FullSizeImageActivity activity) { if (mTaskSetPhoto != null) { mTaskSetPhoto.setActivity(activity); } } public void startTaskSetPhoto(FullSizeImageActivity activity, String pathImage, String username, String password) { if (!mIsRunningTaskSetPhoto) { mIsRunningTaskSetPhoto = true; mTaskSetPhoto = new TaskSetPhoto(activity); mTaskSetPhoto.execute(pathImage, username, password); } } public Intent getPreparedResult() { return mPreparedResult; } public void setPreparedResult(Intent intent) { mPreparedResult = intent; } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.TabsUtil; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.util.UserUtils; import android.app.Activity; import android.app.TabActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Window; import android.widget.FrameLayout; import android.widget.TabHost; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class MainActivity extends TabActivity { public static final String TAG = "MainActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; private TabHost mTabHost; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); // Don't start the main activity if we don't have credentials if (!((Foursquared) getApplication()).isReady()) { if (DEBUG) Log.d(TAG, "Not ready for user."); redirectToLoginActivity(); } if (DEBUG) Log.d(TAG, "Setting up main activity layout."); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.main_activity); initTabHost(); } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } private void initTabHost() { if (mTabHost != null) { throw new IllegalStateException("Trying to intialize already initializd TabHost"); } mTabHost = getTabHost(); // We may want to show the friends tab first, or the places tab first, depending on // the user preferences. SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); // We can add more tabs here eventually, but if "Friends" isn't the startup tab, then // we are left with "Places" being the startup tab instead. String[] startupTabValues = getResources().getStringArray(R.array.startup_tabs_values); String startupTab = settings.getString( Preferences.PREFERENCE_STARTUP_TAB, startupTabValues[0]); Intent intent = new Intent(this, NearbyVenuesActivity.class); if (startupTab.equals(startupTabValues[0])) { TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_friends), R.drawable.tab_main_nav_friends_selector, 1, new Intent(this, FriendsActivity.class)); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_nearby), R.drawable.tab_main_nav_nearby_selector, 2, intent); } else { intent.putExtra(NearbyVenuesActivity.INTENT_EXTRA_STARTUP_GEOLOC_DELAY, 4000L); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_nearby), R.drawable.tab_main_nav_nearby_selector, 1, intent); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_friends), R.drawable.tab_main_nav_friends_selector, 2, new Intent(this, FriendsActivity.class)); } TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_tips), R.drawable.tab_main_nav_tips_selector, 3, new Intent(this, TipsActivity.class)); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_todos), R.drawable.tab_main_nav_todos_selector, 4, new Intent(this, TodosActivity.class)); // 'Me' tab, just shows our own info. At this point we should have a // stored user id, and a user gender to control the image which is // displayed on the tab. String userId = ((Foursquared) getApplication()).getUserId(); String userGender = ((Foursquared) getApplication()).getUserGender(); Intent intentTabMe = new Intent(this, UserDetailsActivity.class); intentTabMe.putExtra(UserDetailsActivity.EXTRA_USER_ID, userId == null ? "unknown" : userId); TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_me), UserUtils.getDrawableForMeTabByGender(userGender), 5, intentTabMe); // Fix layout for 1.5. if (UiUtil.sdkVersion() < 4) { FrameLayout flTabContent = (FrameLayout)findViewById(android.R.id.tabcontent); flTabContent.setPadding(0, 0, 0, 0); } } private void redirectToLoginActivity() { setVisible(false); Intent intent = new Intent(this, LoginActivity.class); intent.setAction(Intent.ACTION_MAIN); intent.setFlags( Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class LocationException extends FoursquaredException { public LocationException() { super("Unable to determine your location."); } public LocationException(String message) { super(message); } private static final long serialVersionUID = 1L; }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ class FoursquaredException extends Exception { private static final long serialVersionUID = 1L; public FoursquaredException(String message) { super(message); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.protocol.ClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import java.io.IOException; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class HttpApiWithBasicAuth extends AbstractHttpApi { private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider)context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; public HttpApiWithBasicAuth(DefaultHttpClient httpClient, String clientVersion) { super(httpClient, clientVersion); httpClient.addRequestInterceptor(preemptiveAuth, 0); } public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { return executeHttpRequest(httpRequest, parser); } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import org.apache.http.NameValuePair; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; /** * @author Joe LaPenna (joe@joelapenna.com) */ public interface HttpApi { abstract public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException; abstract public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException; abstract public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs); abstract public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs); abstract public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary) throws IOException; }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.util.JSONUtils; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.params.HttpClientParams; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract public class AbstractHttpApi implements HttpApi { protected static final Logger LOG = Logger.getLogger(AbstractHttpApi.class.getCanonicalName()); protected static final boolean DEBUG = Foursquare.DEBUG; private static final String DEFAULT_CLIENT_VERSION = "com.joelapenna.foursquare"; private static final String CLIENT_VERSION_HEADER = "User-Agent"; private static final int TIMEOUT = 60; private final DefaultHttpClient mHttpClient; private final String mClientVersion; public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) { mHttpClient = httpClient; if (clientVersion != null) { mClientVersion = clientVersion; } else { mClientVersion = DEFAULT_CLIENT_VERSION; } } public FoursquareType executeHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI()); HttpResponse response = executeHttpRequest(httpRequest); if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: " + httpRequest.getURI().toString()); int statusCode = response.getStatusLine().getStatusCode(); switch (statusCode) { case 200: String content = EntityUtils.toString(response.getEntity()); return JSONUtils.consume(parser, content); case 400: if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 400"); throw new FoursquareException( response.getStatusLine().toString(), EntityUtils.toString(response.getEntity())); case 401: response.getEntity().consumeContent(); if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 401"); throw new FoursquareCredentialsException(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 404"); throw new FoursquareException(response.getStatusLine().toString()); case 500: response.getEntity().consumeContent(); if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 500"); throw new FoursquareException("Foursquare is down. Try again later."); default: if (DEBUG) LOG.log(Level.FINE, "Default case for status code reached: " + response.getStatusLine().toString()); response.getEntity().consumeContent(); throw new FoursquareException("Error connecting to Foursquare: " + statusCode + ". Try again later."); } } public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) LOG.log(Level.FINE, "doHttpPost: " + url); HttpPost httpPost = createHttpPost(url, nameValuePairs); HttpResponse response = executeHttpRequest(httpPost); if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: " + httpPost.getURI().toString()); switch (response.getStatusLine().getStatusCode()) { case 200: try { return EntityUtils.toString(response.getEntity()); } catch (ParseException e) { throw new FoursquareParseException(e.getMessage()); } case 401: response.getEntity().consumeContent(); throw new FoursquareCredentialsException(response.getStatusLine().toString()); case 404: response.getEntity().consumeContent(); throw new FoursquareException(response.getStatusLine().toString()); default: response.getEntity().consumeContent(); throw new FoursquareException(response.getStatusLine().toString()); } } /** * execute() an httpRequest catching exceptions and returning null instead. * * @param httpRequest * @return * @throws IOException */ public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException { if (DEBUG) LOG.log(Level.FINE, "executing HttpRequest for: " + httpRequest.getURI().toString()); try { mHttpClient.getConnectionManager().closeExpiredConnections(); return mHttpClient.execute(httpRequest); } catch (IOException e) { httpRequest.abort(); throw e; } } public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) { if (DEBUG) LOG.log(Level.FINE, "creating HttpGet for: " + url); String query = URLEncodedUtils.format(stripNulls(nameValuePairs), HTTP.UTF_8); HttpGet httpGet = new HttpGet(url + "?" + query); httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion); if (DEBUG) LOG.log(Level.FINE, "Created: " + httpGet.getURI()); return httpGet; } public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs) { if (DEBUG) LOG.log(Level.FINE, "creating HttpPost for: " + url); HttpPost httpPost = new HttpPost(url); httpPost.addHeader(CLIENT_VERSION_HEADER, mClientVersion); try { httpPost.setEntity(new UrlEncodedFormEntity(stripNulls(nameValuePairs), HTTP.UTF_8)); } catch (UnsupportedEncodingException e1) { throw new IllegalArgumentException("Unable to encode http parameters."); } if (DEBUG) LOG.log(Level.FINE, "Created: " + httpPost); return httpPost; } public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(TIMEOUT * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty(CLIENT_VERSION_HEADER, mClientVersion); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); return conn; } private List<NameValuePair> stripNulls(NameValuePair... nameValuePairs) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (int i = 0; i < nameValuePairs.length; i++) { NameValuePair param = nameValuePairs[i]; if (param.getValue() != null) { if (DEBUG) LOG.log(Level.FINE, "Param: " + param); params.add(param); } } return params; } /** * Create a thread-safe client. This client does not do redirecting, to allow us to capture * correct "error" codes. * * @return HttpClient */ public static final DefaultHttpClient createHttpClient() { // Sets up the http part of the service. final SchemeRegistry supportedSchemes = new SchemeRegistry(); // Register the "http" protocol scheme, it is required // by the default operator to look up socket factories. final SocketFactory sf = PlainSocketFactory.getSocketFactory(); supportedSchemes.register(new Scheme("http", sf, 80)); supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // Set some client http client parameter defaults. final HttpParams httpParams = createHttpParams(); HttpClientParams.setRedirecting(httpParams, false); final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams, supportedSchemes); return new DefaultHttpClient(ccm, httpParams); } /** * Create the default HTTP protocol parameters. */ private static final HttpParams createHttpParams() { final HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000); HttpConnectionParams.setSocketBufferSize(params, 8192); return params; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.http; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import oauth.signpost.OAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.signature.SignatureMethod; import org.apache.http.NameValuePair; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class HttpApiWithOAuth extends AbstractHttpApi { protected static final Logger LOG = Logger.getLogger(HttpApiWithOAuth.class.getCanonicalName()); protected static final boolean DEBUG = Foursquare.DEBUG; private OAuthConsumer mConsumer; public HttpApiWithOAuth(DefaultHttpClient httpClient, String clientVersion) { super(httpClient, clientVersion); } public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI()); try { if (DEBUG) LOG.log(Level.FINE, "Signing request: " + httpRequest.getURI()); if (DEBUG) LOG.log(Level.FINE, "Consumer: " + mConsumer.getConsumerKey() + ", " + mConsumer.getConsumerSecret()); if (DEBUG) LOG.log(Level.FINE, "Token: " + mConsumer.getToken() + ", " + mConsumer.getTokenSecret()); mConsumer.sign(httpRequest); } catch (OAuthMessageSignerException e) { if (DEBUG) LOG.log(Level.FINE, "OAuthMessageSignerException", e); throw new RuntimeException(e); } catch (OAuthExpectationFailedException e) { if (DEBUG) LOG.log(Level.FINE, "OAuthExpectationFailedException", e); throw new RuntimeException(e); } return executeHttpRequest(httpRequest, parser); } public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareError, FoursquareParseException, IOException, FoursquareCredentialsException { throw new RuntimeException("Haven't written this method yet."); } public void setOAuthConsumerCredentials(String key, String secret) { mConsumer = new CommonsHttpOAuthConsumer(key, secret, SignatureMethod.HMAC_SHA1); } public void setOAuthTokenWithSecret(String token, String tokenSecret) { verifyConsumer(); if (token == null && tokenSecret == null) { if (DEBUG) LOG.log(Level.FINE, "Resetting consumer due to null token/secret."); String consumerKey = mConsumer.getConsumerKey(); String consumerSecret = mConsumer.getConsumerSecret(); mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret, SignatureMethod.HMAC_SHA1); } else { mConsumer.setTokenWithSecret(token, tokenSecret); } } public boolean hasOAuthTokenWithSecret() { verifyConsumer(); return (mConsumer.getToken() != null) && (mConsumer.getTokenSecret() != null); } private void verifyConsumer() { if (mConsumer == null) { throw new IllegalStateException( "Cannot call method without setting consumer credentials."); } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.util; /** * This is not ideal. * * @date July 1, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class IconUtils { private static IconUtils mInstance; private boolean mRequestHighDensityIcons; private IconUtils() { mRequestHighDensityIcons = false; } public static IconUtils get() { if (mInstance == null) { mInstance = new IconUtils(); } return mInstance; } public boolean getRequestHighDensityIcons() { return mRequestHighDensityIcons; } public void setRequestHighDensityIcons(boolean requestHighDensityIcons) { mRequestHighDensityIcons = requestHighDensityIcons; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.util; import com.joelapenna.foursquare.types.Venue; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueUtils { public static final boolean isValid(Venue venue) { return !(venue == null || venue.getId() == null || venue.getId().length() == 0); } public static final boolean hasValidLocation(Venue venue) { boolean valid = false; if (venue != null) { String geoLat = venue.getGeolat(); String geoLong = venue.getGeolong(); if (!(geoLat == null || geoLat.length() == 0 || geoLong == null || geoLong.length() == 0)) { if (geoLat != "0" || geoLong != "0") { valid = true; } } } return valid; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.util; import android.os.Parcel; /** * @date March 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ParcelUtils { public static void writeStringToParcel(Parcel out, String str) { if (str != null) { out.writeInt(1); out.writeString(str); } else { out.writeInt(0); } } public static String readStringFromParcel(Parcel in) { int flag = in.readInt(); if (flag == 1) { return in.readString(); } else { return null; } } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.util; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareCredentialsException; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.parsers.json.TipParser; import com.joelapenna.foursquare.types.FoursquareType; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; public class JSONUtils { private static final boolean DEBUG = Foursquare.DEBUG; private static final Logger LOG = Logger.getLogger(TipParser.class.getCanonicalName()); /** * Takes a parser, a json string, and returns a foursquare type. */ public static FoursquareType consume(Parser<? extends FoursquareType> parser, String content) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException { if (DEBUG) { LOG.log(Level.FINE, "http response: " + content); } try { // The v1 API returns the response raw with no wrapper. Depending on the // type of API call, the content might be a JSONObject or a JSONArray. // Since JSONArray does not derive from JSONObject, we need to check for // either of these cases to parse correctly. JSONObject json = new JSONObject(content); Iterator<String> it = (Iterator<String>)json.keys(); if (it.hasNext()) { String key = (String)it.next(); if (key.equals("error")) { throw new FoursquareException(json.getString(key)); } else { Object obj = json.get(key); if (obj instanceof JSONArray) { return parser.parse((JSONArray)obj); } else { return parser.parse((JSONObject)obj); } } } else { throw new FoursquareException("Error parsing JSON response, object had no single child key."); } } catch (JSONException ex) { throw new FoursquareException("Error parsing JSON response: " + ex.getMessage()); } } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.util; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class MayorUtils { public static final String TYPE_NOCHANGE = "nochange"; public static final String TYPE_NEW = "new"; public static final String TYPE_STOLEN = "stolen"; }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; /** * @author Joe LaPenna (joe@joelapenna.com) */ public interface FoursquareType { }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; /** * @date April 28, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Response implements FoursquareType { private String mValue; public Response() { } public String getValue() { return mValue; } public void setValue(String value) { mValue = value; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; import com.joelapenna.foursquare.util.ParcelUtils; import android.os.Parcel; import android.os.Parcelable; /** * @date March 6, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Category implements FoursquareType, Parcelable { /** The category's id. */ private String mId; /** Full category path name, like Nightlife:Bars. */ private String mFullPathName; /** Simple name of the category. */ private String mNodeName; /** Url of the icon associated with this category. */ private String mIconUrl; /** Categories can be nested within one another too. */ private Group<Category> mChildCategories; public Category() { mChildCategories = new Group<Category>(); } private Category(Parcel in) { mChildCategories = new Group<Category>(); mId = ParcelUtils.readStringFromParcel(in); mFullPathName = ParcelUtils.readStringFromParcel(in); mNodeName = ParcelUtils.readStringFromParcel(in); mIconUrl = ParcelUtils.readStringFromParcel(in); int numCategories = in.readInt(); for (int i = 0; i < numCategories; i++) { Category category = in.readParcelable(Category.class.getClassLoader()); mChildCategories.add(category); } } public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() { public Category createFromParcel(Parcel in) { return new Category(in); } @Override public Category[] newArray(int size) { return new Category[size]; } }; public String getId() { return mId; } public void setId(String id) { mId = id; } public String getFullPathName() { return mFullPathName; } public void setFullPathName(String fullPathName) { mFullPathName = fullPathName; } public String getNodeName() { return mNodeName; } public void setNodeName(String nodeName) { mNodeName = nodeName; } public String getIconUrl() { return mIconUrl; } public void setIconUrl(String iconUrl) { mIconUrl = iconUrl; } public Group<Category> getChildCategories() { return mChildCategories; } public void setChildCategories(Group<Category> categories) { mChildCategories = categories; } @Override public void writeToParcel(Parcel out, int flags) { ParcelUtils.writeStringToParcel(out, mId); ParcelUtils.writeStringToParcel(out, mFullPathName); ParcelUtils.writeStringToParcel(out, mNodeName); ParcelUtils.writeStringToParcel(out, mIconUrl); out.writeInt(mChildCategories.size()); for (Category it : mChildCategories) { out.writeParcelable(it, flags); } } @Override public int describeContents() { return 0; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; /** * @date 2010-05-05 * @author Mark Wyszomierski (markww@gmail.com) */ public class FriendInvitesResult implements FoursquareType { /** * Users that are in our contact book by email or phone, are already on foursquare, * but are not our friends. */ private Group<User> mContactsOnFoursquare; /** * Users not on foursquare, but in our contact book by email or phone. These are * users we have not already sent an email invite to. */ private Emails mContactEmailsNotOnFoursquare; /** * A list of email addresses we've already sent email invites to. */ private Emails mContactEmailsNotOnFoursquareAlreadyInvited; public FriendInvitesResult() { mContactsOnFoursquare = new Group<User>(); mContactEmailsNotOnFoursquare = new Emails(); mContactEmailsNotOnFoursquareAlreadyInvited = new Emails(); } public Group<User> getContactsOnFoursquare() { return mContactsOnFoursquare; } public void setContactsOnFoursquare(Group<User> contactsOnFoursquare) { mContactsOnFoursquare = contactsOnFoursquare; } public Emails getContactEmailsNotOnFoursquare() { return mContactEmailsNotOnFoursquare; } public void setContactEmailsOnNotOnFoursquare(Emails emails) { mContactEmailsNotOnFoursquare = emails; } public Emails getContactEmailsNotOnFoursquareAlreadyInvited() { return mContactEmailsNotOnFoursquareAlreadyInvited; } public void setContactEmailsOnNotOnFoursquareAlreadyInvited(Emails emails) { mContactEmailsNotOnFoursquareAlreadyInvited = emails; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; import com.joelapenna.foursquare.util.ParcelUtils; import android.os.Parcel; import android.os.Parcelable; /** * @date September 2, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Todo implements FoursquareType, Parcelable { private String mCreated; private String mId; private Tip mTip; public Todo() { } private Todo(Parcel in) { mCreated = ParcelUtils.readStringFromParcel(in); mId = ParcelUtils.readStringFromParcel(in); if (in.readInt() == 1) { mTip = in.readParcelable(Tip.class.getClassLoader()); } } public static final Parcelable.Creator<Todo> CREATOR = new Parcelable.Creator<Todo>() { public Todo createFromParcel(Parcel in) { return new Todo(in); } @Override public Todo[] newArray(int size) { return new Todo[size]; } }; public String getCreated() { return mCreated; } public void setCreated(String created) { mCreated = created; } public String getId() { return mId; } public void setId(String id) { mId = id; } public Tip getTip() { return mTip; } public void setTip(Tip tip) { mTip = tip; } @Override public void writeToParcel(Parcel out, int flags) { ParcelUtils.writeStringToParcel(out, mCreated); ParcelUtils.writeStringToParcel(out, mId); if (mTip != null) { out.writeInt(1); out.writeParcelable(mTip, flags); } else { out.writeInt(0); } } @Override public int describeContents() { return 0; } }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import java.util.ArrayList; /** * @date April 14, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class Types extends ArrayList<String> implements FoursquareType { private static final long serialVersionUID = 1L; }
Java
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import java.util.ArrayList; import java.util.Collection; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Group<T extends FoursquareType> extends ArrayList<T> implements FoursquareType { private static final long serialVersionUID = 1L; private String mType; public Group() { super(); } public Group(Collection<T> collection) { super(collection); } public void setType(String type) { mType = type; } public String getType() { return mType; } }
Java
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.types; import java.util.ArrayList; /** * @date 2010-05-05 * @author Mark Wyszomierski (markww@gmail.com) */ public class Emails extends ArrayList<String> implements FoursquareType { private static final long serialVersionUID = 1L; }
Java