code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/CheckinListAdapter.java
Java
asf20
6,576
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(); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/PhotoStrip.java
Java
asf20
7,388
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/MayorListAdapter.java
Java
asf20
4,478
/** * 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(); }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/ObservableAdapter.java
Java
asf20
699
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/BadgeListAdapter.java
Java
asf20
2,607
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/FriendRequestsAdapter.java
Java
asf20
7,353
/** * 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(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/BaseGroupAdapter.java
Java
asf20
1,044
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/UserContactAdapter.java
Java
asf20
4,648
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/FriendListAdapter.java
Java
asf20
4,539
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/BaseTipAdapter.java
Java
asf20
360
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/VenueListAdapter.java
Java
asf20
8,251
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/TodosListAdapter.java
Java
asf20
8,960
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/BaseCheckinAdapter.java
Java
asf20
376
/** * 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(); } }); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/BadgeWithIconListAdapter.java
Java
asf20
3,213
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/BaseUserAdapter.java
Java
asf20
364
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/TipsListAdapter.java
Java
asf20
10,108
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/BaseMayorAdapter.java
Java
asf20
368
/* 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(); } }; }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/SeparatedListAdapter.java
Java
asf20
4,873
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/SegmentedButton.java
Java
asf20
12,614
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/FriendSearchInviteNonFoursquareUserAdapter.java
Java
asf20
5,236
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/SpecialListAdapter.java
Java
asf20
2,215
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/BaseBadgeAdapter.java
Java
asf20
368
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(); } }); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/ScoreListAdapter.java
Java
asf20
4,551
/* * 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(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/SendLogActivity.java
Java
asf20
11,130
/** * 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); } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/CheckinExecuteActivity.java
Java
asf20
13,494
/* * 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(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/preferences/ClickPreference.java
Java
asf20
1,990
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/preferences/Preferences.java
Java
asf20
10,991
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/StatsActivity.java
Java
asf20
3,129
/** * 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(); } }; }
1084solid-exp
main/src/com/joelapenna/foursquared/FriendRequestsActivity.java
Java
asf20
21,973
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/UserDetailsFriendsInCommonActivity.java
Java
asf20
13,532
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/VenueShareActivity.java
Java
asf20
6,536
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/VenueCheckinsActivity.java
Java
asf20
7,339
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/VenueTodosActivity.java
Java
asf20
6,697
/** * 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); } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/PingsSettingsActivity.java
Java
asf20
14,897
/** * 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; } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/EditVenueOptionsActivity.java
Java
asf20
10,715
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/maps/VenueItemizedOverlay.java
Java
asf20
3,324
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/maps/CrashFixMyLocationOverlay.java
Java
asf20
1,289
/** * 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(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/maps/BaseGroupItemizedOverlay.java
Java
asf20
1,525
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/maps/CheckinGroup.java
Java
asf20
2,037
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/maps/CheckinItemizedOverlay.java
Java
asf20
1,772
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/maps/TipItemizedOverlay.java
Java
asf20
1,711
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/maps/VenueItemizedOverlayWithIcons.java
Java
asf20
4,682
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/maps/CheckinGroupItemizedOverlay.java
Java
asf20
6,902
/** * 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); } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/UserHistoryActivity.java
Java
asf20
9,170
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/CheckinOrShoutGatherInfoActivity.java
Java
asf20
11,009
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/FullSizeImageActivity.java
Java
asf20
13,648
/** * 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(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/MainActivity.java
Java
asf20
5,576
/** * 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; }
1084solid-exp
main/src/com/joelapenna/foursquared/error/LocationException.java
Java
asf20
424
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/error/FoursquaredException.java
Java
asf20
318
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquare/http/HttpApiWithBasicAuth.java
Java
asf20
2,833
/** * 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; }
1084solid-exp
main/src/com/joelapenna/foursquare/http/HttpApi.java
Java
asf20
1,501
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquare/http/AbstractHttpApi.java
Java
asf20
10,639
/** * 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."); } } }
1084solid-exp
main/src/com/joelapenna/foursquare/http/HttpApiWithOAuth.java
Java
asf20
4,071
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquare/util/IconUtils.java
Java
asf20
791
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquare/util/VenueUtils.java
Java
asf20
843
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquare/util/ParcelUtils.java
Java
asf20
659
/** * 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()); } } }
1084solid-exp
main/src/com/joelapenna/foursquare/util/JSONUtils.java
Java
asf20
2,556
/** * 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"; }
1084solid-exp
main/src/com/joelapenna/foursquare/util/MayorUtils.java
Java
asf20
325
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; /** * @author Joe LaPenna (joe@joelapenna.com) */ public interface FoursquareType { }
1084solid-exp
main/src/com/joelapenna/foursquare/types/FoursquareType.java
Java
asf20
169
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquare/types/Response.java
Java
asf20
411
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquare/types/Category.java
Java
asf20
3,059
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquare/types/FriendInvitesResult.java
Java
asf20
1,757
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquare/types/Todo.java
Java
asf20
1,818
/** * 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; }
1084solid-exp
main/src/com/joelapenna/foursquare/types/Types.java
Java
asf20
319
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquare/types/Group.java
Java
asf20
627
/** * 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; }
1084solid-exp
main/src/com/joelapenna/foursquare/types/Emails.java
Java
asf20
322
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.types; import java.util.ArrayList; import java.util.List; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Tags extends ArrayList<String> implements FoursquareType { private static final long serialVersionUID = 1L; public Tags() { super(); } public Tags(List<String> values) { super(); addAll(values); } }
1084solid-exp
main/src/com/joelapenna/foursquare/types/Tags.java
Java
asf20
452
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.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.types.Category; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.Credentials; import com.joelapenna.foursquare.types.FriendInvitesResult; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Response; import com.joelapenna.foursquare.types.Settings; 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 android.net.Uri; import android.text.TextUtils; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class Foursquare { private static final Logger LOG = Logger.getLogger("com.joelapenna.foursquare"); public static final boolean DEBUG = false; public static final boolean PARSER_DEBUG = false; public static final String FOURSQUARE_API_DOMAIN = "api.foursquare.com"; public static final String FOURSQUARE_MOBILE_ADDFRIENDS = "http://m.foursquare.com/addfriends"; public static final String FOURSQUARE_MOBILE_FRIENDS = "http://m.foursquare.com/friends"; public static final String FOURSQUARE_MOBILE_SIGNUP = "http://m.foursquare.com/signup"; public static final String FOURSQUARE_PREFERENCES = "http://foursquare.com/settings"; public static final String MALE = "male"; public static final String FEMALE = "female"; private String mPhone; private String mPassword; private FoursquareHttpApiV1 mFoursquareV1; @V1 public Foursquare(FoursquareHttpApiV1 httpApi) { mFoursquareV1 = httpApi; } public void setCredentials(String phone, String password) { mPhone = phone; mPassword = password; mFoursquareV1.setCredentials(phone, password); } @V1 public void setOAuthToken(String token, String secret) { mFoursquareV1.setOAuthTokenWithSecret(token, secret); } @V1 public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) { mFoursquareV1.setOAuthConsumerCredentials(oAuthConsumerKey, oAuthConsumerSecret); } public void clearAllCredentials() { setCredentials(null, null); setOAuthToken(null, null); } @V1 public boolean hasCredentials() { return mFoursquareV1.hasCredentials() && mFoursquareV1.hasOAuthTokenWithSecret(); } @V1 public boolean hasLoginAndPassword() { return mFoursquareV1.hasCredentials(); } @V1 public Credentials authExchange() throws FoursquareException, FoursquareError, FoursquareCredentialsException, IOException { if (mFoursquareV1 == null) { throw new NoSuchMethodError( "authExchange is unavailable without a consumer key/secret."); } return mFoursquareV1.authExchange(mPhone, mPassword); } @V1 public Tip addTip(String vid, String text, String type, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.addtip(vid, text, type, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Tip tipDetail(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.tipDetail(tid); } @V1 @LocationRequired public Venue addVenue(String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.addvenue(name, address, crossstreet, city, state, zip, phone, categoryId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public CheckinResult checkin(String venueId, String venueName, Location location, String shout, boolean isPrivate, boolean tellFollowers, boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.checkin(venueId, venueName, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, shout, isPrivate, tellFollowers, twitter, facebook); } @V1 public Group<Checkin> checkins(Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.checkins(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Group<User> friends(String userId, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.friends(userId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.friendRequests(); } @V1 public User friendApprove(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendApprove(userId); } @V1 public User friendDeny(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendDeny(userId); } @V1 public User friendSendrequest(String userId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.friendSendrequest(userId); } @V1 public Group<Tip> tips(Location location, String uid, String filter, String sort, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.tips(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, uid, filter, sort, limit); } @V1 public Group<Todo> todos(Location location, String uid, boolean recent, boolean nearby, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.todos(uid, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, recent, nearby, limit); } @V1 public User user(String user, boolean mayor, boolean badges, boolean stats, Location location) throws FoursquareException, FoursquareError, IOException { if (location != null) { return mFoursquareV1.user(user, mayor, badges, stats, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } else { return mFoursquareV1.user(user, mayor, badges, stats, null, null, null, null, null); } } @V1 public Venue venue(String id, Location location) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.venue(id, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 @LocationRequired public Group<Group<Venue>> venues(Location location, String query, int limit) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.venues(location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt, query, limit); } @V1 public Group<User> findFriendsByName(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByName(text); } @V1 public Group<User> findFriendsByPhone(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByPhone(text); } @V1 public Group<User> findFriendsByFacebook(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByFacebook(text); } @V1 public Group<User> findFriendsByTwitter(String text) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.findFriendsByTwitter(text); } @V1 public Group<Category> categories() throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.categories(); } @V1 public Group<Checkin> history(String limit, String sinceid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.history(limit, sinceid); } @V1 public Todo markTodo(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markTodo(tid); } @V1 public Todo markTodoVenue(String vid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markTodoVenue(vid); } @V1 public Tip markIgnore(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markIgnore(tid); } @V1 public Tip markDone(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.markDone(tid); } @V1 public Tip unmarkTodo(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.unmarkTodo(tid); } @V1 public Tip unmarkDone(String tid) throws FoursquareException, FoursquareError, IOException { return mFoursquareV1.unmarkDone(tid); } @V1 public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.findFriendsByPhoneOrEmail(phones, emails); } @V1 public Response inviteByEmail(String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.inviteByEmail(emails); } @V1 public Settings setpings(boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.setpings(on); } @V1 public Settings setpings(String userid, boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.setpings(userid, on); } @V1 public Response flagclosed(String venueid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.flagclosed(venueid); } @V1 public Response flagmislocated(String venueid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.flagmislocated(venueid); } @V1 public Response flagduplicate(String venueid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.flagduplicate(venueid); } @V1 public Response proposeedit(String venueId, String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, Location location) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { return mFoursquareV1.proposeedit(venueId, name, address, crossstreet, city, state, zip, phone, categoryId, location.geolat, location.geolong, location.geohacc, location.geovacc, location.geoalt); } @V1 public User userUpdate(String imagePathToJpg, String username, String password) throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException { return mFoursquareV1.userUpdate(imagePathToJpg, username, password); } public static final FoursquareHttpApiV1 createHttpApi(String domain, String clientVersion, boolean useOAuth) { LOG.log(Level.INFO, "Using foursquare.com for requests."); return new FoursquareHttpApiV1(domain, clientVersion, useOAuth); } public static final FoursquareHttpApiV1 createHttpApi(String clientVersion, boolean useOAuth) { return createHttpApi(FOURSQUARE_API_DOMAIN, clientVersion, useOAuth); } public static final String createLeaderboardUrl(String userId, Location location) { Uri.Builder builder = new Uri.Builder() // .scheme("http") // .authority("foursquare.com") // .appendEncodedPath("/iphone/me") // .appendQueryParameter("view", "all") // .appendQueryParameter("scope", "friends") // .appendQueryParameter("uid", userId); if (!TextUtils.isEmpty(location.geolat)) { builder.appendQueryParameter("geolat", location.geolat); } if (!TextUtils.isEmpty(location.geolong)) { builder.appendQueryParameter("geolong", location.geolong); } if (!TextUtils.isEmpty(location.geohacc)) { builder.appendQueryParameter("geohacc", location.geohacc); } if (!TextUtils.isEmpty(location.geovacc)) { builder.appendQueryParameter("geovacc", location.geovacc); } return builder.build().toString(); } /** * This api is supported in the V1 API documented at: * http://groups.google.com/group/foursquare-api/web/api-documentation */ @interface V1 { } /** * This api call requires a location. */ @interface LocationRequired { } public static class Location { String geolat = null; String geolong = null; String geohacc = null; String geovacc = null; String geoalt = null; public Location() { } public Location(final String geolat, final String geolong, final String geohacc, final String geovacc, final String geoalt) { this.geolat = geolat; this.geolong = geolong; this.geohacc = geohacc; this.geovacc = geovacc; this.geoalt = geovacc; } public Location(final String geolat, final String geolong) { this(geolat, geolong, null, null, null); } } }
1084solid-exp
main/src/com/joelapenna/foursquare/Foursquare.java
Java
asf20
15,243
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Checkin; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CheckinParser extends AbstractParser<Checkin> { @Override public Checkin parse(JSONObject json) throws JSONException { Checkin obj = new Checkin(); if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("display")) { obj.setDisplay(json.getString("display")); } if (json.has("distance")) { obj.setDistance(json.getString("distance")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("ismayor")) { obj.setIsmayor(json.getBoolean("ismayor")); } if (json.has("ping")) { obj.setPing(json.getBoolean("ping")); } if (json.has("shout")) { obj.setShout(json.getString("shout")); } if (json.has("user")) { obj.setUser(new UserParser().parse(json.getJSONObject("user"))); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/CheckinParser.java
Java
asf20
1,432
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Special; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class SpecialParser extends AbstractParser<Special> { @Override public Special parse(JSONObject json) throws JSONException { Special obj = new Special(); if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("type")) { obj.setType(json.getString("type")); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/SpecialParser.java
Java
asf20
910
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Emails; import com.joelapenna.foursquare.types.FriendInvitesResult; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class FriendInvitesResultParser extends AbstractParser<FriendInvitesResult> { @Override public FriendInvitesResult parse(JSONObject json) throws JSONException { FriendInvitesResult obj = new FriendInvitesResult(); if (json.has("users")) { obj.setContactsOnFoursquare( new GroupParser( new UserParser()).parse(json.getJSONArray("users"))); } if (json.has("emails")) { Emails emails = new Emails(); if (json.optJSONObject("emails") != null) { JSONObject emailsAsObject = json.getJSONObject("emails"); emails.add(emailsAsObject.getString("email")); } else if (json.optJSONArray("emails") != null) { JSONArray emailsAsArray = json.getJSONArray("emails"); for (int i = 0; i < emailsAsArray.length(); i++) { emails.add(emailsAsArray.getString(i)); } } obj.setContactEmailsOnNotOnFoursquare(emails); } if (json.has("invited")) { Emails emails = new Emails(); JSONArray array = json.getJSONArray("invited"); for (int i = 0; i < array.length(); i++) { emails.add(array.getString(i)); } obj.setContactEmailsOnNotOnFoursquareAlreadyInvited(emails); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/FriendInvitesResultParser.java
Java
asf20
1,808
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Todo; import org.json.JSONException; import org.json.JSONObject; /** * @date September 2, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TodoParser extends AbstractParser<Todo> { @Override public Todo parse(JSONObject json) throws JSONException { Todo obj = new Todo(); if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("tip")) { obj.setTip(new TipParser().parse(json.getJSONObject("tip"))); } if (json.has("todoid")) { obj.setId(json.getString("todoid")); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/TodoParser.java
Java
asf20
796
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public interface Parser<T extends FoursquareType> { public abstract T parse(JSONObject json) throws JSONException; public Group parse(JSONArray array) throws JSONException; }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/Parser.java
Java
asf20
546
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import org.json.JSONArray; import org.json.JSONException; import java.util.ArrayList; import java.util.List; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class StringArrayParser { public static List<String> parse(JSONArray json) throws JSONException { List<String> array = new ArrayList<String>(); for (int i = 0, m = json.length(); i < m; i++) { array.add(json.getString(i)); } return array; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/StringArrayParser.java
Java
asf20
599
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Stats; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class StatsParser extends AbstractParser<Stats> { @Override public Stats parse(JSONObject json) throws JSONException { Stats obj = new Stats(); if (json.has("beenhere")) { obj.setBeenhere(new BeenhereParser().parse(json.getJSONObject("beenhere"))); } if (json.has("checkins")) { obj.setCheckins(json.getString("checkins")); } if (json.has("herenow")) { obj.setHereNow(json.getString("herenow")); } if (json.has("mayor")) { obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor"))); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/StatsParser.java
Java
asf20
956
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Settings; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class SettingsParser extends AbstractParser<Settings> { @Override public Settings parse(JSONObject json) throws JSONException { Settings obj = new Settings(); if (json.has("feeds_key")) { obj.setFeedsKey(json.getString("feeds_key")); } if (json.has("get_pings")) { obj.setGetPings(json.getBoolean("get_pings")); } if (json.has("pings")) { obj.setPings(json.getString("pings")); } if (json.has("sendtofacebook")) { obj.setSendtofacebook(json.getBoolean("sendtofacebook")); } if (json.has("sendtotwitter")) { obj.setSendtotwitter(json.getBoolean("sendtotwitter")); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/SettingsParser.java
Java
asf20
1,059
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Badge; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class BadgeParser extends AbstractParser<Badge> { @Override public Badge parse(JSONObject json) throws JSONException { Badge obj = new Badge(); if (json.has("description")) { obj.setDescription(json.getString("description")); } if (json.has("icon")) { obj.setIcon(json.getString("icon")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("name")) { obj.setName(json.getString("name")); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/BadgeParser.java
Java
asf20
878
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Beenhere; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class BeenhereParser extends AbstractParser<Beenhere> { @Override public Beenhere parse(JSONObject json) throws JSONException { Beenhere obj = new Beenhere(); if (json.has("friends")) { obj.setFriends(json.getBoolean("friends")); } if (json.has("me")) { obj.setMe(json.getBoolean("me")); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/BeenhereParser.java
Java
asf20
697
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Response; import org.json.JSONException; import org.json.JSONObject; /** * @date April 28, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ResponseParser extends AbstractParser<Response> { @Override public Response parse(JSONObject json) throws JSONException { Response response = new Response(); response.setValue(json.getString("response")); return response; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/ResponseParser.java
Java
asf20
559
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.parsers.json.Parser; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public abstract class AbstractParser<T extends FoursquareType> implements Parser<T> { /** * All derived parsers must implement parsing a JSONObject instance of themselves. */ public abstract T parse(JSONObject json) throws JSONException; /** * Only the GroupParser needs to implement this. */ public Group parse(JSONArray array) throws JSONException { throw new JSONException("Unexpected JSONArray parse type encountered."); } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/AbstractParser.java
Java
asf20
903
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Tip; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TipParser extends AbstractParser<Tip> { @Override public Tip parse(JSONObject json) throws JSONException { Tip obj = new Tip(); if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("distance")) { obj.setDistance(json.getString("distance")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("stats")) { obj.setStats(new TipParser.StatsParser().parse(json.getJSONObject("stats"))); } if (json.has("status")) { obj.setStatus(json.getString("status")); } if (json.has("text")) { obj.setText(json.getString("text")); } if (json.has("user")) { obj.setUser(new UserParser().parse(json.getJSONObject("user"))); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } public static class StatsParser extends AbstractParser<Tip.Stats> { @Override public Tip.Stats parse(JSONObject json) throws JSONException { Tip.Stats stats = new Tip.Stats(); if (json.has("donecount")) { stats.setDoneCount(json.getInt("donecount")); } if (json.has("todocount")) { stats.setTodoCount(json.getInt("todocount")); } return stats; } } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/TipParser.java
Java
asf20
1,857
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Credentials; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CredentialsParser extends AbstractParser<Credentials> { @Override public Credentials parse(JSONObject json) throws JSONException { Credentials obj = new Credentials(); if (json.has("oauth_token")) { obj.setOauthToken(json.getString("oauth_token")); } if (json.has("oauth_token_secret")) { obj.setOauthTokenSecret(json.getString("oauth_token_secret")); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/CredentialsParser.java
Java
asf20
771
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Data; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class DataParser extends AbstractParser<Data> { @Override public Data parse(JSONObject json) throws JSONException { Data obj = new Data(); if (json.has("cityid")) { obj.setCityid(json.getString("cityid")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("status")) { obj.setStatus("1".equals(json.getString("status"))); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/DataParser.java
Java
asf20
793
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.City; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CityParser extends AbstractParser<City> { @Override public City parse(JSONObject json) throws JSONException { City obj = new City(); if (json.has("geolat")) { obj.setGeolat(json.getString("geolat")); } if (json.has("geolong")) { obj.setGeolong(json.getString("geolong")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("name")) { obj.setName(json.getString("name")); } if (json.has("shortname")) { obj.setShortname(json.getString("shortname")); } if (json.has("timezone")) { obj.setTimezone(json.getString("timezone")); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/CityParser.java
Java
asf20
1,077
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Score; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class ScoreParser extends AbstractParser<Score> { @Override public Score parse(JSONObject json) throws JSONException { Score obj = new Score(); if (json.has("icon")) { obj.setIcon(json.getString("icon")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("points")) { obj.setPoints(json.getString("points")); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/ScoreParser.java
Java
asf20
781
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.FoursquareType; import com.joelapenna.foursquare.types.Group; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.Iterator; import java.util.logging.Level; /** * Reference: * http://www.json.org/javadoc/org/json/JSONObject.html * http://www.json.org/javadoc/org/json/JSONArray.html * * @author Mark Wyszomierski (markww@gmail.com) * @param <T> */ public class GroupParser extends AbstractParser<Group> { private Parser<? extends FoursquareType> mSubParser; public GroupParser(Parser<? extends FoursquareType> subParser) { mSubParser = subParser; } /** * When we encounter a JSONObject in a GroupParser, we expect one attribute * named 'type', and then another JSONArray attribute. */ public Group<FoursquareType> parse(JSONObject json) throws JSONException { Group<FoursquareType> group = new Group<FoursquareType>(); Iterator<String> it = (Iterator<String>)json.keys(); while (it.hasNext()) { String key = it.next(); if (key.equals("type")) { group.setType(json.getString(key)); } else { Object obj = json.get(key); if (obj instanceof JSONArray) { parse(group, (JSONArray)obj); } else { throw new JSONException("Could not parse data."); } } } return group; } /** * Here we are getting a straight JSONArray and do not expect the 'type' attribute. */ @Override public Group parse(JSONArray array) throws JSONException { Group<FoursquareType> group = new Group<FoursquareType>(); parse(group, array); return group; } private void parse(Group group, JSONArray array) throws JSONException { for (int i = 0, m = array.length(); i < m; i++) { Object element = array.get(i); FoursquareType item = null; if (element instanceof JSONArray) { item = mSubParser.parse((JSONArray)element); } else { item = mSubParser.parse((JSONObject)element); } group.add(item); } } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/GroupParser.java
Java
asf20
2,439
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Types; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class TypesParser extends AbstractParser<Types> { @Override public Types parse(JSONObject json) throws JSONException { Types obj = new Types(); if (json.has("type")) { obj.add(json.getString("type")); } return obj; } public Types parseAsJSONArray(JSONArray array) throws JSONException { Types obj = new Types(); for (int i = 0, m = array.length(); i < m; i++) { obj.add(array.getString(i)); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/TypesParser.java
Java
asf20
858
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.User; import org.json.JSONException; import org.json.JSONObject; import java.util.logging.Level; import java.util.logging.Logger; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserParser extends AbstractParser<User> { @Override public User parse(JSONObject json) throws JSONException { User user = new User(); if (json.has("badges")) { user.setBadges( new GroupParser( new BadgeParser()).parse(json.getJSONArray("badges"))); } if (json.has("badgecount")) { user.setBadgeCount(json.getInt("badgecount")); } if (json.has("checkin")) { user.setCheckin(new CheckinParser().parse(json.getJSONObject("checkin"))); } if (json.has("checkincount")) { user.setCheckinCount(json.getInt("checkincount")); } if (json.has("created")) { user.setCreated(json.getString("created")); } if (json.has("email")) { user.setEmail(json.getString("email")); } if (json.has("facebook")) { user.setFacebook(json.getString("facebook")); } if (json.has("firstname")) { user.setFirstname(json.getString("firstname")); } if (json.has("followercount")) { user.setFollowerCount(json.getInt("followercount")); } if (json.has("friendcount")) { user.setFriendCount(json.getInt("friendcount")); } if (json.has("friendsincommon")) { user.setFriendsInCommon( new GroupParser( new UserParser()).parse(json.getJSONArray("friendsincommon"))); } if (json.has("friendstatus")) { user.setFriendstatus(json.getString("friendstatus")); } if (json.has("gender")) { user.setGender(json.getString("gender")); } if (json.has("hometown")) { user.setHometown(json.getString("hometown")); } if (json.has("id")) { user.setId(json.getString("id")); } if (json.has("lastname")) { user.setLastname(json.getString("lastname")); } if (json.has("mayor")) { user.setMayorships( new GroupParser( new VenueParser()).parse(json.getJSONArray("mayor"))); } if (json.has("mayorcount")) { user.setMayorCount(json.getInt("mayorcount")); } if (json.has("phone")) { user.setPhone(json.getString("phone")); } if (json.has("photo")) { user.setPhoto(json.getString("photo")); } if (json.has("settings")) { user.setSettings(new SettingsParser().parse(json.getJSONObject("settings"))); } if (json.has("tipcount")) { user.setTipCount(json.getInt("tipcount")); } if (json.has("todocount")) { user.setTodoCount(json.getInt("todocount")); } if (json.has("twitter")) { user.setTwitter(json.getString("twitter")); } if (json.has("types")) { user.setTypes(new TypesParser().parseAsJSONArray(json.getJSONArray("types"))); } return user; } //@Override //public String getObjectName() { // return "user"; //} }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/UserParser.java
Java
asf20
3,621
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Rank; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class RankParser extends AbstractParser<Rank> { @Override public Rank parse(JSONObject json) throws JSONException { Rank obj = new Rank(); if (json.has("city")) { obj.setCity(json.getString("city")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("position")) { obj.setPosition(json.getString("position")); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/RankParser.java
Java
asf20
790
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Mayor; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class MayorParser extends AbstractParser<Mayor> { @Override public Mayor parse(JSONObject json) throws JSONException { Mayor obj = new Mayor(); if (json.has("checkins")) { obj.setCheckins(json.getString("checkins")); } if (json.has("count")) { obj.setCount(json.getString("count")); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("type")) { obj.setType(json.getString("type")); } if (json.has("user")) { obj.setUser(new UserParser().parse(json.getJSONObject("user"))); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/MayorParser.java
Java
asf20
1,023
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.Tags; import com.joelapenna.foursquare.types.Venue; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class VenueParser extends AbstractParser<Venue> { @Override public Venue parse(JSONObject json) throws JSONException { Venue obj = new Venue(); if (json.has("address")) { obj.setAddress(json.getString("address")); } if (json.has("checkins")) { obj.setCheckins( new GroupParser( new CheckinParser()).parse(json.getJSONArray("checkins"))); } if (json.has("city")) { obj.setCity(json.getString("city")); } if (json.has("cityid")) { obj.setCityid(json.getString("cityid")); } if (json.has("crossstreet")) { obj.setCrossstreet(json.getString("crossstreet")); } if (json.has("distance")) { obj.setDistance(json.getString("distance")); } if (json.has("geolat")) { obj.setGeolat(json.getString("geolat")); } if (json.has("geolong")) { obj.setGeolong(json.getString("geolong")); } if (json.has("hasTodo")) { obj.setHasTodo(json.getBoolean("hasTodo")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("name")) { obj.setName(json.getString("name")); } if (json.has("phone")) { obj.setPhone(json.getString("phone")); } if (json.has("primarycategory")) { obj.setCategory(new CategoryParser().parse(json.getJSONObject("primarycategory"))); } if (json.has("specials")) { obj.setSpecials( new GroupParser( new SpecialParser()).parse(json.getJSONArray("specials"))); } if (json.has("state")) { obj.setState(json.getString("state")); } if (json.has("stats")) { obj.setStats(new StatsParser().parse(json.getJSONObject("stats"))); } if (json.has("tags")) { obj.setTags( new Tags(StringArrayParser.parse(json.getJSONArray("tags")))); } if (json.has("tips")) { obj.setTips( new GroupParser( new TipParser()).parse(json.getJSONArray("tips"))); } if (json.has("todos")) { obj.setTodos( new GroupParser( new TodoParser()).parse(json.getJSONArray("todos"))); } if (json.has("twitter")) { obj.setTwitter(json.getString("twitter")); } if (json.has("zip")) { obj.setZip(json.getString("zip")); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/VenueParser.java
Java
asf20
3,034
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.types.CheckinResult; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CheckinResultParser extends AbstractParser<CheckinResult> { @Override public CheckinResult parse(JSONObject json) throws JSONException { CheckinResult obj = new CheckinResult(); if (json.has("badges")) { obj.setBadges( new GroupParser( new BadgeParser()).parse(json.getJSONArray("badges"))); } if (json.has("created")) { obj.setCreated(json.getString("created")); } if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("markup")) { obj.setMarkup(json.getString("markup")); } if (json.has("mayor")) { obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor"))); } if (json.has("message")) { obj.setMessage(json.getString("message")); } if (json.has("scores")) { obj.setScoring( new GroupParser( new ScoreParser()).parse(json.getJSONArray("scores"))); } if (json.has("specials")) { obj.setSpecials( new GroupParser( new SpecialParser()).parse(json.getJSONArray("specials"))); } if (json.has("venue")) { obj.setVenue(new VenueParser().parse(json.getJSONObject("venue"))); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/CheckinResultParser.java
Java
asf20
1,728
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquare.parsers.json; import com.joelapenna.foursquare.parsers.json.CategoryParser; import com.joelapenna.foursquare.parsers.json.GroupParser; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.util.IconUtils; import org.json.JSONException; import org.json.JSONObject; /** * @date July 13, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class CategoryParser extends AbstractParser<Category> { @Override public Category parse(JSONObject json) throws JSONException { Category obj = new Category(); if (json.has("id")) { obj.setId(json.getString("id")); } if (json.has("fullpathname")) { obj.setFullPathName(json.getString("fullpathname")); } if (json.has("nodename")) { obj.setNodeName(json.getString("nodename")); } if (json.has("iconurl")) { // TODO: Remove this once api v2 allows icon request. String iconUrl = json.getString("iconurl"); if (IconUtils.get().getRequestHighDensityIcons()) { iconUrl = iconUrl.replace(".png", "_64.png"); } obj.setIconUrl(iconUrl); } if (json.has("categories")) { obj.setChildCategories( new GroupParser( new CategoryParser()).parse(json.getJSONArray("categories"))); } return obj; } }
1084solid-exp
main/src/com/joelapenna/foursquare/parsers/json/CategoryParser.java
Java
asf20
1,530
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.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.http.AbstractHttpApi; import com.joelapenna.foursquare.http.HttpApi; import com.joelapenna.foursquare.http.HttpApiWithBasicAuth; import com.joelapenna.foursquare.http.HttpApiWithOAuth; import com.joelapenna.foursquare.parsers.json.CategoryParser; import com.joelapenna.foursquare.parsers.json.CheckinParser; import com.joelapenna.foursquare.parsers.json.CheckinResultParser; import com.joelapenna.foursquare.parsers.json.CityParser; import com.joelapenna.foursquare.parsers.json.CredentialsParser; import com.joelapenna.foursquare.parsers.json.FriendInvitesResultParser; import com.joelapenna.foursquare.parsers.json.GroupParser; import com.joelapenna.foursquare.parsers.json.ResponseParser; import com.joelapenna.foursquare.parsers.json.SettingsParser; import com.joelapenna.foursquare.parsers.json.TipParser; import com.joelapenna.foursquare.parsers.json.TodoParser; import com.joelapenna.foursquare.parsers.json.UserParser; import com.joelapenna.foursquare.parsers.json.VenueParser; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.CheckinResult; import com.joelapenna.foursquare.types.City; import com.joelapenna.foursquare.types.Credentials; import com.joelapenna.foursquare.types.FriendInvitesResult; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Response; import com.joelapenna.foursquare.types.Settings; 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.foursquare.util.JSONUtils; import com.joelapenna.foursquared.util.Base64Coder; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Joe LaPenna (joe@joelapenna.com) */ class FoursquareHttpApiV1 { private static final Logger LOG = Logger .getLogger(FoursquareHttpApiV1.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.DEBUG; private static final String DATATYPE = ".json"; private static final String URL_API_AUTHEXCHANGE = "/authexchange"; private static final String URL_API_ADDVENUE = "/addvenue"; private static final String URL_API_ADDTIP = "/addtip"; private static final String URL_API_CITIES = "/cities"; private static final String URL_API_CHECKINS = "/checkins"; private static final String URL_API_CHECKIN = "/checkin"; private static final String URL_API_USER = "/user"; private static final String URL_API_VENUE = "/venue"; private static final String URL_API_VENUES = "/venues"; private static final String URL_API_TIPS = "/tips"; private static final String URL_API_TODOS = "/todos"; private static final String URL_API_FRIEND_REQUESTS = "/friend/requests"; private static final String URL_API_FRIEND_APPROVE = "/friend/approve"; private static final String URL_API_FRIEND_DENY = "/friend/deny"; private static final String URL_API_FRIEND_SENDREQUEST = "/friend/sendrequest"; private static final String URL_API_FRIENDS = "/friends"; private static final String URL_API_FIND_FRIENDS_BY_NAME = "/findfriends/byname"; private static final String URL_API_FIND_FRIENDS_BY_PHONE = "/findfriends/byphone"; private static final String URL_API_FIND_FRIENDS_BY_FACEBOOK = "/findfriends/byfacebook"; private static final String URL_API_FIND_FRIENDS_BY_TWITTER = "/findfriends/bytwitter"; private static final String URL_API_CATEGORIES = "/categories"; private static final String URL_API_HISTORY = "/history"; private static final String URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL = "/findfriends/byphoneoremail"; private static final String URL_API_INVITE_BY_EMAIL = "/invite/byemail"; private static final String URL_API_SETPINGS = "/settings/setpings"; private static final String URL_API_VENUE_FLAG_CLOSED = "/venue/flagclosed"; private static final String URL_API_VENUE_FLAG_MISLOCATED = "/venue/flagmislocated"; private static final String URL_API_VENUE_FLAG_DUPLICATE = "/venue/flagduplicate"; private static final String URL_API_VENUE_PROPOSE_EDIT = "/venue/proposeedit"; private static final String URL_API_USER_UPDATE = "/user/update"; private static final String URL_API_MARK_TODO = "/mark/todo"; private static final String URL_API_MARK_IGNORE = "/mark/ignore"; private static final String URL_API_MARK_DONE = "/mark/done"; private static final String URL_API_UNMARK_TODO = "/unmark/todo"; private static final String URL_API_UNMARK_DONE = "/unmark/done"; private static final String URL_API_TIP_DETAIL = "/tip/detail"; private final DefaultHttpClient mHttpClient = AbstractHttpApi.createHttpClient(); private HttpApi mHttpApi; private final String mApiBaseUrl; private final AuthScope mAuthScope; public FoursquareHttpApiV1(String domain, String clientVersion, boolean useOAuth) { mApiBaseUrl = "https://" + domain + "/v1"; mAuthScope = new AuthScope(domain, 80); if (useOAuth) { mHttpApi = new HttpApiWithOAuth(mHttpClient, clientVersion); } else { mHttpApi = new HttpApiWithBasicAuth(mHttpClient, clientVersion); } } void setCredentials(String phone, String password) { if (phone == null || phone.length() == 0 || password == null || password.length() == 0) { if (DEBUG) LOG.log(Level.FINE, "Clearing Credentials"); mHttpClient.getCredentialsProvider().clear(); } else { if (DEBUG) LOG.log(Level.FINE, "Setting Phone/Password: " + phone + "/******"); mHttpClient.getCredentialsProvider().setCredentials(mAuthScope, new UsernamePasswordCredentials(phone, password)); } } public boolean hasCredentials() { return mHttpClient.getCredentialsProvider().getCredentials(mAuthScope) != null; } public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) { if (DEBUG) { LOG.log(Level.FINE, "Setting consumer key/secret: " + oAuthConsumerKey + " " + oAuthConsumerSecret); } ((HttpApiWithOAuth) mHttpApi).setOAuthConsumerCredentials(oAuthConsumerKey, oAuthConsumerSecret); } public void setOAuthTokenWithSecret(String token, String secret) { if (DEBUG) LOG.log(Level.FINE, "Setting oauth token/secret: " + token + " " + secret); ((HttpApiWithOAuth) mHttpApi).setOAuthTokenWithSecret(token, secret); } public boolean hasOAuthTokenWithSecret() { return ((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret(); } /* * /authexchange?oauth_consumer_key=d123...a1bffb5&oauth_consumer_secret=fec... * 18 */ public Credentials authExchange(String phone, String password) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { if (((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret()) { throw new IllegalStateException("Cannot do authExchange with OAuthToken already set"); } HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_AUTHEXCHANGE), // new BasicNameValuePair("fs_username", phone), // new BasicNameValuePair("fs_password", password)); return (Credentials) mHttpApi.doHttpRequest(httpPost, new CredentialsParser()); } /* * /addtip?vid=1234&text=I%20added%20a%20tip&type=todo (type defaults "tip") */ Tip addtip(String vid, String text, String type, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDTIP), // new BasicNameValuePair("vid", vid), // new BasicNameValuePair("text", text), // new BasicNameValuePair("type", type), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * @param name the name of the venue * @param address the address of the venue (e.g., "202 1st Avenue") * @param crossstreet the cross streets (e.g., "btw Grand & Broome") * @param city the city name where this venue is * @param state the state where the city is * @param zip (optional) the ZIP code for the venue * @param phone (optional) the phone number for the venue * @return * @throws FoursquareException * @throws FoursquareCredentialsException * @throws FoursquareError * @throws IOException */ Venue addvenue(String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDVENUE), // new BasicNameValuePair("name", name), // new BasicNameValuePair("address", address), // new BasicNameValuePair("crossstreet", crossstreet), // new BasicNameValuePair("city", city), // new BasicNameValuePair("state", state), // new BasicNameValuePair("zip", zip), // new BasicNameValuePair("phone", phone), // new BasicNameValuePair("primarycategoryid", categoryId), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Venue) mHttpApi.doHttpRequest(httpPost, new VenueParser()); } /* * /cities */ @SuppressWarnings("unchecked") Group<City> cities() throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CITIES)); return (Group<City>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CityParser())); } /* * /checkins? */ @SuppressWarnings("unchecked") Group<Checkin> checkins(String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CHECKINS), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt)); return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CheckinParser())); } /* * /checkin?vid=1234&venue=Noc%20Noc&shout=Come%20here&private=0&twitter=1 */ CheckinResult checkin(String vid, String venue, String geolat, String geolong, String geohacc, String geovacc, String geoalt, String shout, boolean isPrivate, boolean tellFollowers, boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_CHECKIN), // new BasicNameValuePair("vid", vid), // new BasicNameValuePair("venue", venue), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("shout", shout), // new BasicNameValuePair("private", (isPrivate) ? "1" : "0"), // new BasicNameValuePair("followers", (tellFollowers) ? "1" : "0"), // new BasicNameValuePair("twitter", (twitter) ? "1" : "0"), // new BasicNameValuePair("facebook", (facebook) ? "1" : "0"), // new BasicNameValuePair("markup", "android")); // used only by android for checkin result 'extras'. return (CheckinResult) mHttpApi.doHttpRequest(httpPost, new CheckinResultParser()); } /** * /user?uid=9937 */ User user(String uid, boolean mayor, boolean badges, boolean stats, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_USER), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("mayor", (mayor) ? "1" : "0"), // new BasicNameValuePair("badges", (badges) ? "1" : "0"), // new BasicNameValuePair("stats", (stats) ? "1" : "0"), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (User) mHttpApi.doHttpRequest(httpGet, new UserParser()); } /** * /venues?geolat=37.770900&geolong=-122.43698 */ @SuppressWarnings("unchecked") Group<Group<Venue>> venues(String geolat, String geolong, String geohacc, String geovacc, String geoalt, String query, int limit) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUES), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("q", query), // new BasicNameValuePair("l", String.valueOf(limit))); return (Group<Group<Venue>>) mHttpApi.doHttpRequest(httpGet, new GroupParser( new GroupParser(new VenueParser()))); } /** * /venue?vid=1234 */ Venue venue(String vid, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUE), // new BasicNameValuePair("vid", vid), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Venue) mHttpApi.doHttpRequest(httpGet, new VenueParser()); } /** * /tips?geolat=37.770900&geolong=-122.436987&l=1 */ @SuppressWarnings("unchecked") Group<Tip> tips(String geolat, String geolong, String geohacc, String geovacc, String geoalt, String uid, String filter, String sort, int limit) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIPS), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("filter", filter), // new BasicNameValuePair("sort", sort), // new BasicNameValuePair("l", String.valueOf(limit)) // ); return (Group<Tip>) mHttpApi.doHttpRequest(httpGet, new GroupParser( new TipParser())); } /** * /todos?geolat=37.770900&geolong=-122.436987&l=1&sort=[recent|nearby] */ @SuppressWarnings("unchecked") Group<Todo> todos(String uid, String geolat, String geolong, String geohacc, String geovacc, String geoalt, boolean recent, boolean nearby, int limit) throws FoursquareException, FoursquareError, IOException { String sort = null; if (recent) { sort = "recent"; } else if (nearby) { sort = "nearby"; } HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TODOS), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt), // new BasicNameValuePair("sort", sort), // new BasicNameValuePair("l", String.valueOf(limit)) // ); return (Group<Todo>) mHttpApi.doHttpRequest(httpGet, new GroupParser( new TodoParser())); } /* * /friends?uid=9937 */ @SuppressWarnings("unchecked") Group<User> friends(String uid, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIENDS), // new BasicNameValuePair("uid", uid), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /* * /friend/requests */ @SuppressWarnings("unchecked") Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIEND_REQUESTS)); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /* * /friend/approve?uid=9937 */ User friendApprove(String uid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_APPROVE), // new BasicNameValuePair("uid", uid)); return (User) mHttpApi.doHttpRequest(httpPost, new UserParser()); } /* * /friend/deny?uid=9937 */ User friendDeny(String uid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_DENY), // new BasicNameValuePair("uid", uid)); return (User) mHttpApi.doHttpRequest(httpPost, new UserParser()); } /* * /friend/sendrequest?uid=9937 */ User friendSendrequest(String uid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_SENDREQUEST), // new BasicNameValuePair("uid", uid)); return (User) mHttpApi.doHttpRequest(httpPost, new UserParser()); } /** * /findfriends/byname?q=john doe, mary smith */ @SuppressWarnings("unchecked") public Group<User> findFriendsByName(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_NAME), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /** * /findfriends/byphone?q=555-5555,555-5556 */ @SuppressWarnings("unchecked") public Group<User> findFriendsByPhone(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser())); } /** * /findfriends/byfacebook?q=friendid,friendid,friendid */ @SuppressWarnings("unchecked") public Group<User> findFriendsByFacebook(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_FACEBOOK), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser())); } /** * /findfriends/bytwitter?q=yourtwittername */ @SuppressWarnings("unchecked") public Group<User> findFriendsByTwitter(String text) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_TWITTER), // new BasicNameValuePair("q", text)); return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser())); } /** * /categories */ @SuppressWarnings("unchecked") public Group<Category> categories() throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CATEGORIES)); return (Group<Category>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CategoryParser())); } /** * /history */ @SuppressWarnings("unchecked") public Group<Checkin> history(String limit, String sinceid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_HISTORY), new BasicNameValuePair("l", limit), new BasicNameValuePair("sinceid", sinceid)); return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CheckinParser())); } /** * /mark/todo */ public Todo markTodo(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), // new BasicNameValuePair("tid", tid)); return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser()); } /** * This is a hacky special case, hopefully the api will be updated in v2 for this. * /mark/todo */ public Todo markTodoVenue(String vid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), // new BasicNameValuePair("vid", vid)); return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser()); } /** * /mark/ignore */ public Tip markIgnore(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_IGNORE), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /mark/done */ public Tip markDone(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_DONE), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /unmark/todo */ public Tip unmarkTodo(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_TODO), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /unmark/done */ public Tip unmarkDone(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_DONE), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser()); } /** * /tip/detail?tid=1234 */ public Tip tipDetail(String tid) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIP_DETAIL), // new BasicNameValuePair("tid", tid)); return (Tip) mHttpApi.doHttpRequest(httpGet, new TipParser()); } /** * /findfriends/byphoneoremail?p=comma-sep-list-of-phones&e=comma-sep-list-of-emails */ public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL), // new BasicNameValuePair("p", phones), new BasicNameValuePair("e", emails)); return (FriendInvitesResult) mHttpApi.doHttpRequest(httpPost, new FriendInvitesResultParser()); } /** * /invite/byemail?q=comma-sep-list-of-emails */ public Response inviteByEmail(String emails) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_INVITE_BY_EMAIL), // new BasicNameValuePair("q", emails)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /settings/setpings?self=[on|off] */ public Settings setpings(boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), // new BasicNameValuePair("self", on ? "on" : "off")); return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser()); } /** * /settings/setpings?uid=userid */ public Settings setpings(String userid, boolean on) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), // new BasicNameValuePair(userid, on ? "on" : "off")); return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser()); } /** * /venue/flagclosed?vid=venueid */ public Response flagclosed(String venueId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_CLOSED), // new BasicNameValuePair("vid", venueId)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /venue/flagmislocated?vid=venueid */ public Response flagmislocated(String venueId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_MISLOCATED), // new BasicNameValuePair("vid", venueId)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /venue/flagduplicate?vid=venueid */ public Response flagduplicate(String venueId) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_DUPLICATE), // new BasicNameValuePair("vid", venueId)); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } /** * /venue/prposeedit?vid=venueid&name=... */ public Response proposeedit(String venueId, String name, String address, String crossstreet, String city, String state, String zip, String phone, String categoryId, String geolat, String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException { HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_PROPOSE_EDIT), // new BasicNameValuePair("vid", venueId), // new BasicNameValuePair("name", name), // new BasicNameValuePair("address", address), // new BasicNameValuePair("crossstreet", crossstreet), // new BasicNameValuePair("city", city), // new BasicNameValuePair("state", state), // new BasicNameValuePair("zip", zip), // new BasicNameValuePair("phone", phone), // new BasicNameValuePair("primarycategoryid", categoryId), // new BasicNameValuePair("geolat", geolat), // new BasicNameValuePair("geolong", geolong), // new BasicNameValuePair("geohacc", geohacc), // new BasicNameValuePair("geovacc", geovacc), // new BasicNameValuePair("geoalt", geoalt) // ); return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser()); } private String fullUrl(String url) { return mApiBaseUrl + url + DATATYPE; } /** * /user/update * Need to bring this method under control like the rest of the api methods. Leaving it * in this state as authorization will probably switch from basic auth in the near future * anyway, will have to be updated. Also unlike the other methods, we're sending up data * which aren't basic name/value pairs. */ public User userUpdate(String imagePathToJpg, String username, String password) throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException { String BOUNDARY = "------------------319831265358979362846"; String lineEnd = "\r\n"; String twoHyphens = "--"; int maxBufferSize = 8192; File file = new File(imagePathToJpg); FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(fullUrl(URL_API_USER_UPDATE)); HttpURLConnection conn = mHttpApi.createHttpURLConnectionPost(url, BOUNDARY); conn.setRequestProperty("Authorization", "Basic " + Base64Coder.encodeString(username + ":" + password)); // We are always saving the image to a jpg so we can use .jpg as the extension below. DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + BOUNDARY + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"image,jpeg\";filename=\"" + "image.jpeg" +"\"" + lineEnd); dos.writeBytes("Content-Type: " + "image/jpeg" + lineEnd); dos.writeBytes(lineEnd); int bytesAvailable = fileInputStream.available(); int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; int bytesRead = fileInputStream.read(buffer, 0, bufferSize); int totalBytesRead = bytesRead; while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); totalBytesRead = totalBytesRead + bytesRead; } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + BOUNDARY + twoHyphens + lineEnd); fileInputStream.close(); dos.flush(); dos.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder response = new StringBuilder(); String responseLine = ""; while ((responseLine = in.readLine()) != null) { response.append(responseLine); } in.close(); try { return (User)JSONUtils.consume(new UserParser(), response.toString()); } catch (Exception ex) { throw new FoursquareParseException( "Error parsing user photo upload response, invalid json."); } } }
1084solid-exp
main/src/com/joelapenna/foursquare/FoursquareHttpApiV1.java
Java
asf20
35,320
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareParseException extends FoursquareException { private static final long serialVersionUID = 1L; public FoursquareParseException(String message) { super(message); } }
1084solid-exp
main/src/com/joelapenna/foursquare/error/FoursquareParseException.java
Java
asf20
341
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareError extends FoursquareException { private static final long serialVersionUID = 1L; public FoursquareError(String message) { super(message); } }
1084solid-exp
main/src/com/joelapenna/foursquare/error/FoursquareError.java
Java
asf20
324
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareCredentialsException extends FoursquareException { private static final long serialVersionUID = 1L; public FoursquareCredentialsException(String message) { super(message); } }
1084solid-exp
main/src/com/joelapenna/foursquare/error/FoursquareCredentialsException.java
Java
asf20
354
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.error; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquareException extends Exception { private static final long serialVersionUID = 1L; private String mExtra; public FoursquareException(String message) { super(message); } public FoursquareException(String message, String extra) { super(message); mExtra = extra; } public String getExtra() { return mExtra; } }
1084solid-exp
main/src/com/joelapenna/foursquare/error/FoursquareException.java
Java
asf20
536
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.test; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.VenueActivity; import android.content.Intent; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.SmallTest; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueActivityInstrumentationTestCase extends ActivityInstrumentationTestCase2<VenueActivity> { public VenueActivityInstrumentationTestCase() { super("com.joelapenna.foursquared", VenueActivity.class); } @SmallTest public void testOnCreate() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.putExtra(Foursquared.EXTRA_VENUE_ID, "40450"); setActivityIntent(intent); VenueActivity activity = getActivity(); activity.openOptionsMenu(); activity.closeOptionsMenu(); } }
1084solid-exp
tests/src/com/joelapenna/foursquared/test/VenueActivityInstrumentationTestCase.java
Java
asf20
944
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.test; import com.joelapenna.foursquared.Foursquared; import android.test.ApplicationTestCase; import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> { public FoursquaredAppTestCase() { super(Foursquared.class); } @MediumTest public void testLocationMethods() { createApplication(); getApplication().getLastKnownLocation(); getApplication().getLocationListener(); } @SmallTest public void testPreferences() { createApplication(); } }
1084solid-exp
tests/src/com/joelapenna/foursquared/test/FoursquaredAppTestCase.java
Java
asf20
770