code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/**
* Copyright 2008 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.Checkin;
import android.content.Context;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public abstract class BaseCheckinAdapter extends BaseGroupAdapter<Checkin> {
public BaseCheckinAdapter(Context context) {
super(context);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.Badge;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class BadgeWithIconListAdapter extends BadgeListAdapter
implements ObservableAdapter {
private static final String TAG = "BadgeWithIconListAdapter";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private RemoteResourceManager mRrm;
private Handler mHandler = new Handler();
private RemoteResourceManagerObserver mResourcesObserver;
/**
* @param context
* @param venues
*/
public BadgeWithIconListAdapter(Context context, RemoteResourceManager rrm) {
super(context);
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mRrm.addObserver(mResourcesObserver);
}
public BadgeWithIconListAdapter(Context context, RemoteResourceManager rrm, int layoutResource) {
super(context, layoutResource);
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mRrm.addObserver(mResourcesObserver);
}
public void removeObserver() {
mRrm.deleteObserver(mResourcesObserver);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
Badge badge = (Badge)getItem(position);
ImageView icon = ((BadgeWithIconListAdapter.ViewHolder)view.getTag()).icon;
try {
Bitmap bitmap = BitmapFactory.decodeStream(//
mRrm.getInputStream(Uri.parse(badge.getIcon())));
icon.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "Could not load bitmap. We don't have it yet.");
icon.setImageResource(R.drawable.default_on);
}
return view;
}
@Override
public void setGroup(Group<Badge> g) {
super.setGroup(g);
for (int i = 0; i < group.size(); i++) {
Uri photoUri = Uri.parse((group.get(i)).getIcon());
if (!mRrm.exists(photoUri)) {
mRrm.request(photoUri);
}
}
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Fetcher got: " + data);
mHandler.post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquared.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
/**
* A multi-button control which can only have one pressed button at
* any given time. Its functionality is quite similar to a tab control.
* Tabs can't be skinned in android 1.5, and our main frame is a tab
* host - which causes some different android problems, thus this control
* was created.
*
* @date September 15, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class SegmentedButton extends LinearLayout {
private StateListDrawable mBgLeftOn;
private StateListDrawable mBgRightOn;
private StateListDrawable mBgCenterOn;
private StateListDrawable mBgLeftOff;
private StateListDrawable mBgRightOff;
private StateListDrawable mBgCenterOff;
private int mSelectedButtonIndex = 0;
private List<String> mButtonTitles = new ArrayList<String>();
private int mColorOnStart;
private int mColorOnEnd;
private int mColorOffStart;
private int mColorOffEnd;
private int mColorSelectedStart;
private int mColorSelectedEnd;
private int mColorStroke;
private int mStrokeWidth;
private int mCornerRadius;
private int mTextStyle;
private int mBtnPaddingTop;
private int mBtnPaddingBottom;
private OnClickListenerSegmentedButton mOnClickListenerExternal;
public SegmentedButton(Context context) {
super(context);
}
public SegmentedButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SegmentedButton, 0, 0);
CharSequence btnText1 = a.getString(R.styleable.SegmentedButton_btnText1);
CharSequence btnText2 = a.getString(R.styleable.SegmentedButton_btnText2);
if (btnText1 != null) {
mButtonTitles.add(btnText1.toString());
}
if (btnText2 != null) {
mButtonTitles.add(btnText2.toString());
}
mColorOnStart = a.getColor(R.styleable.SegmentedButton_gradientColorOnStart, 0xFF0000);
mColorOnEnd = a.getColor(R.styleable.SegmentedButton_gradientColorOnEnd, 0xFF0000);
mColorOffStart = a.getColor(R.styleable.SegmentedButton_gradientColorOffStart, 0xFF0000);
mColorOffEnd = a.getColor(R.styleable.SegmentedButton_gradientColorOffEnd, 0xFF0000);
mColorStroke = a.getColor(R.styleable.SegmentedButton_strokeColor, 0xFF0000);
mColorSelectedEnd = a.getColor(R.styleable.SegmentedButton_gradientColorSelectedEnd, 0xFF0000);
mColorSelectedStart = a.getColor(R.styleable.SegmentedButton_gradientColorSelectedStart, 0xFF0000);
mStrokeWidth = a.getDimensionPixelSize(R.styleable.SegmentedButton_strokeWidth, 1);
mCornerRadius = a.getDimensionPixelSize(R.styleable.SegmentedButton_cornerRadius, 4);
mTextStyle = a.getResourceId(R.styleable.SegmentedButton_textStyle, -1);
mBtnPaddingTop = a.getDimensionPixelSize(R.styleable.SegmentedButton_btnPaddingTop, 0);
mBtnPaddingBottom = a.getDimensionPixelSize(R.styleable.SegmentedButton_btnPaddingBottom, 0);
a.recycle();
buildDrawables(mColorOnStart, mColorOnEnd, mColorOffStart, mColorOffEnd,
mColorSelectedStart, mColorSelectedEnd, mCornerRadius, mColorStroke,
mStrokeWidth);
if (mButtonTitles.size() > 0) {
_addButtons(new String[mButtonTitles.size()]);
}
}
public void clearButtons() {
removeAllViews();
}
public void addButtons(String ... titles) {
_addButtons(titles);
}
private void _addButtons(String[] titles) {
for (int i = 0; i < titles.length; i++) {
Button button = new Button(getContext());
button.setText(titles[i]);
button.setTag(new Integer(i));
button.setOnClickListener(mOnClickListener);
if (mTextStyle != -1) {
button.setTextAppearance(getContext(), mTextStyle);
}
if (titles.length == 1) {
// Don't use a segmented button with one button.
return;
} else if (titles.length == 2) {
if (i == 0) {
button.setBackgroundDrawable(mBgLeftOff);
} else {
button.setBackgroundDrawable(mBgRightOn);
}
} else {
if (i == 0) {
button.setBackgroundDrawable(mBgLeftOff);
} else if (i == titles.length-1) {
button.setBackgroundDrawable(mBgRightOn);
} else {
button.setBackgroundDrawable(mBgCenterOn);
}
}
LinearLayout.LayoutParams llp =
new LinearLayout.LayoutParams(
0,
LinearLayout.LayoutParams.WRAP_CONTENT,
1);
addView(button, llp);
button.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom);
}
}
private void buildDrawables(int colorOnStart,
int colorOnEnd,
int colorOffStart,
int colorOffEnd,
int colorSelectedStart,
int colorSelectedEnd,
float crad,
int strokeColor,
int strokeWidth)
{
// top-left, top-right, bottom-right, bottom-left
float[] radiiLeft = new float[] {
crad, crad, 0, 0, 0, 0, crad, crad
};
float[] radiiRight = new float[] {
0, 0, crad, crad, crad, crad, 0, 0
};
float[] radiiCenter = new float[] {
0, 0, 0, 0, 0, 0, 0, 0
};
GradientDrawable leftOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor);
leftOn.setCornerRadii(radiiLeft);
GradientDrawable leftOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor);
leftOff.setCornerRadii(radiiLeft);
GradientDrawable leftSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor);
leftSelected.setCornerRadii(radiiLeft);
GradientDrawable rightOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor);
rightOn.setCornerRadii(radiiRight);
GradientDrawable rightOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor);
rightOff.setCornerRadii(radiiRight);
GradientDrawable rightSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor);
rightSelected.setCornerRadii(radiiRight);
GradientDrawable centerOn = buildGradientDrawable(colorOnStart, colorOnEnd, strokeWidth, strokeColor);
centerOn.setCornerRadii(radiiCenter);
GradientDrawable centerOff = buildGradientDrawable(colorOffStart, colorOffEnd, strokeWidth, strokeColor);
centerOff.setCornerRadii(radiiCenter);
GradientDrawable centerSelected = buildGradientDrawable(colorSelectedStart, colorSelectedEnd, strokeWidth, strokeColor);
centerSelected.setCornerRadii(radiiCenter);
List<int[]> onStates = buildOnStates();
List<int[]> offStates = buildOffStates();
mBgLeftOn = new StateListDrawable();
mBgRightOn = new StateListDrawable();
mBgCenterOn = new StateListDrawable();
mBgLeftOff = new StateListDrawable();
mBgRightOff = new StateListDrawable();
mBgCenterOff = new StateListDrawable();
for (int[] it : onStates) {
mBgLeftOn.addState(it, leftSelected);
mBgRightOn.addState(it, rightSelected);
mBgCenterOn.addState(it, centerSelected);
mBgLeftOff.addState(it, leftSelected);
mBgRightOff.addState(it, rightSelected);
mBgCenterOff.addState(it, centerSelected);
}
for (int[] it : offStates) {
mBgLeftOn.addState(it, leftOn);
mBgRightOn.addState(it, rightOn);
mBgCenterOn.addState(it, centerOn);
mBgLeftOff.addState(it, leftOff);
mBgRightOff.addState(it, rightOff);
mBgCenterOff.addState(it, centerOff);
}
}
private List<int[]> buildOnStates() {
List<int[]> res = new ArrayList<int[]>();
res.add(new int[] {
android.R.attr.state_focused, android.R.attr.state_enabled});
res.add(new int[] {
android.R.attr.state_focused, android.R.attr.state_selected, android.R.attr.state_enabled});
res.add(new int[] {
android.R.attr.state_pressed});
return res;
}
private List<int[]> buildOffStates() {
List<int[]> res = new ArrayList<int[]>();
res.add(new int[] {
android.R.attr.state_enabled});
res.add(new int[] {
android.R.attr.state_selected, android.R.attr.state_enabled});
return res;
}
private GradientDrawable buildGradientDrawable(int colorStart, int colorEnd, int strokeWidth, int strokeColor) {
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
new int[] { colorStart, colorEnd });
gd.setShape(GradientDrawable.RECTANGLE);
gd.setStroke(strokeWidth, strokeColor);
return gd;
}
private OnClickListener mOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
Button btnNext = (Button)v;
int btnNextIndex = ((Integer)btnNext.getTag()).intValue();
if (btnNextIndex == mSelectedButtonIndex) {
return;
}
handleStateChange(mSelectedButtonIndex, btnNextIndex);
if (mOnClickListenerExternal != null) {
mOnClickListenerExternal.onClick(mSelectedButtonIndex);
}
}
};
private void handleStateChange(int btnLastIndex, int btnNextIndex) {
int count = getChildCount();
Button btnLast = (Button)getChildAt(btnLastIndex);
Button btnNext = (Button)getChildAt(btnNextIndex);
if (count < 3) {
if (btnLastIndex == 0) {
btnLast.setBackgroundDrawable(mBgLeftOn);
} else {
btnLast.setBackgroundDrawable(mBgRightOn);
}
if (btnNextIndex == 0) {
btnNext.setBackgroundDrawable(mBgLeftOff);
} else {
btnNext.setBackgroundDrawable(mBgRightOff);
}
} else {
if (btnLastIndex == 0) {
btnLast.setBackgroundDrawable(mBgLeftOn);
} else if (btnLastIndex == count-1) {
btnLast.setBackgroundDrawable(mBgRightOn);
} else {
btnLast.setBackgroundDrawable(mBgCenterOn);
}
if (btnNextIndex == 0) {
btnNext.setBackgroundDrawable(mBgLeftOff);
} else if (btnNextIndex == count-1) {
btnNext.setBackgroundDrawable(mBgRightOff);
} else {
btnNext.setBackgroundDrawable(mBgCenterOff);
}
}
btnLast.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom);
btnNext.setPadding(0, mBtnPaddingTop, 0, mBtnPaddingBottom);
mSelectedButtonIndex = btnNextIndex;
}
public int getSelectedButtonIndex() {
return mSelectedButtonIndex;
}
public void setPushedButtonIndex(int index) {
handleStateChange(mSelectedButtonIndex, index);
}
public void setOnClickListener(OnClickListenerSegmentedButton listener) {
mOnClickListenerExternal = listener;
}
public interface OnClickListenerSegmentedButton {
public void onClick(int index);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.TipUtils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
/**
* @date August 31, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class TipsListAdapter extends BaseGroupAdapter<Tip>
implements ObservableAdapter {
private LayoutInflater mInflater;
private int mLayoutToInflate;
private Resources mResources;
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
private Handler mHandler = new Handler();
private int mLoadedPhotoIndex;
private boolean mDisplayTipVenueTitles;
private Map<String, String> mCachedTimestamps;
public TipsListAdapter(Context context, RemoteResourceManager rrm, int layout) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = layout;
mResources = context.getResources();
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mLoadedPhotoIndex = 0;
mDisplayTipVenueTitles = true;
mCachedTimestamps = new HashMap<String, String>();
mRrm.addObserver(mResourcesObserver);
}
public void removeObserver() {
mHandler.removeCallbacks(mUpdatePhotos);
mHandler.removeCallbacks(mRunnableLoadPhotos);
mRrm.deleteObserver(mResourcesObserver);
}
public TipsListAdapter(Context context, int layoutResource) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = layoutResource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary
// calls to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no
// need to re-inflate it. We only inflate a new View when the
// convertView supplied by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(mLayoutToInflate, null);
// Creates a ViewHolder and store references to the two children
// views we want to bind data to.
holder = new ViewHolder();
holder.photo = (ImageView) convertView.findViewById(R.id.icon);
holder.title = (TextView) convertView.findViewById(R.id.tvTitle);
holder.body = (TextView) convertView.findViewById(R.id.tvBody);
holder.dateAndAuthor = (TextView) convertView.findViewById(R.id.tvDateAndAuthor);
//holder.friendCountTodoImg = (ImageView) convertView.findViewById(R.id.ivFriendCountAsTodo);
//holder.friendCountTodo = (TextView) convertView.findViewById(R.id.tvFriendCountAsTodo);
holder.friendCountCompletedImg = (ImageView) convertView.findViewById(R.id.ivFriendCountCompleted);
holder.friendCountCompleted = (TextView) convertView.findViewById(R.id.tvFriendCountCompleted);
holder.corner = (ImageView) convertView.findViewById(R.id.ivTipCorner);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
Tip tip = (Tip) getItem(position);
User user = tip.getUser();
if (user != null) {
Uri photoUri = Uri.parse(user.getPhoto());
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri));
holder.photo.setImageBitmap(bitmap);
} catch (IOException e) {
if (Foursquare.MALE.equals(user.getGender())) {
holder.photo.setImageResource(R.drawable.blank_boy);
} else {
holder.photo.setImageResource(R.drawable.blank_girl);
}
}
} else {
Venue venue = tip.getVenue();
Category category = venue.getCategory();
if (category != null) {
holder.photo.setBackgroundDrawable(null);
Uri photoUri = Uri.parse(category.getIconUrl());
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri));
holder.photo.setImageBitmap(bitmap);
} catch (IOException e) {
holder.photo.setImageResource(R.drawable.category_none);
}
} else {
// If there is no category for this venue, fall back to the original
// method of the
// blue/grey pin depending on if the user has been there or not.
holder.photo.setImageResource(R.drawable.category_none);
}
}
if (mDisplayTipVenueTitles && tip.getVenue() != null) {
holder.title.setText("@ " + tip.getVenue().getName());
holder.title.setVisibility(View.VISIBLE);
} else {
holder.title.setVisibility(View.GONE);
holder.body.setPadding(
holder.body.getPaddingLeft(), holder.title.getPaddingTop(),
holder.body.getPaddingRight(), holder.title.getPaddingBottom());
}
holder.body.setText(tip.getText());
holder.dateAndAuthor.setText(mCachedTimestamps.get(tip.getId()));
if (user != null) {
holder.dateAndAuthor.setText(
holder.dateAndAuthor.getText() +
mResources.getString(
R.string.tip_age_via,
StringFormatters.getUserFullName(user)));
}
/*
if (tip.getStats().getTodoCount() > 0) {
holder.friendCountTodoImg.setVisibility(View.VISIBLE);
holder.friendCountTodo.setVisibility(View.VISIBLE);
holder.friendCountTodo.setText(String.valueOf(tip.getStats().getTodoCount()));
} else {
holder.friendCountTodoImg.setVisibility(View.GONE);
holder.friendCountTodo.setVisibility(View.GONE);
}
*/
if (tip.getStats().getDoneCount() > 0) {
holder.friendCountCompletedImg.setVisibility(View.VISIBLE);
holder.friendCountCompleted.setVisibility(View.VISIBLE);
holder.friendCountCompleted.setText(String.valueOf(tip.getStats().getDoneCount()));
} else {
holder.friendCountCompletedImg.setVisibility(View.GONE);
holder.friendCountCompleted.setVisibility(View.GONE);
}
if (TipUtils.isDone(tip)) {
holder.corner.setVisibility(View.VISIBLE);
holder.corner.setImageResource(R.drawable.tip_list_item_corner_done);
} else if (TipUtils.isTodo(tip)) {
holder.corner.setVisibility(View.VISIBLE);
holder.corner.setImageResource(R.drawable.tip_list_item_corner_todo);
} else {
holder.corner.setVisibility(View.GONE);
}
return convertView;
}
public void removeItem(int position) throws IndexOutOfBoundsException {
group.remove(position);
notifyDataSetInvalidated();
}
@Override
public void setGroup(Group<Tip> g) {
super.setGroup(g);
mLoadedPhotoIndex = 0;
mHandler.postDelayed(mRunnableLoadPhotos, 10L);
mCachedTimestamps.clear();
for (Tip it : g) {
String formatted = StringFormatters.getTipAge(mResources, it.getCreated());
mCachedTimestamps.put(it.getId(), formatted);
}
}
public void setDisplayTipVenueTitles(boolean displayTipVenueTitles) {
mDisplayTipVenueTitles = displayTipVenueTitles;
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
mHandler.post(mUpdatePhotos);
}
}
private Runnable mUpdatePhotos = new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
};
private Runnable mRunnableLoadPhotos = new Runnable() {
@Override
public void run() {
if (mLoadedPhotoIndex < getCount()) {
Tip tip = (Tip)getItem(mLoadedPhotoIndex++);
if (tip.getUser() != null) {
Uri photoUri = Uri.parse(tip.getUser().getPhoto());
if (!mRrm.exists(photoUri)) {
mRrm.request(photoUri);
}
mHandler.postDelayed(mRunnableLoadPhotos, 200L);
}
}
}
};
static class ViewHolder {
ImageView photo;
TextView title;
TextView body;
TextView dateAndAuthor;
//ImageView friendCountTodoImg;
//TextView friendCountTodo;
ImageView friendCountCompletedImg;
TextView friendCountCompleted;
ImageView corner;
}
}
| Java |
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.UserUtils;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.util.AttributeSet;
import android.view.View;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
/**
* A single horizontal strip of user photo views. Expected to be used from
* xml resource, needs more work to make this a robust and generic control.
*
* @date September 15, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class PhotoStrip extends View
implements ObservableAdapter {
private int mPhotoSize;
private int mPhotoSpacing;
private int mPhotoBorder;
private int mPhotoBorderStroke;
private int mPhotoBorderColor;
private int mPhotoBorderStrokeColor;
private Group<User> mTypes;
private Map<String, Bitmap> mCachedBitmaps = new HashMap<String, Bitmap>();
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
public PhotoStrip(Context context) {
super(context);
}
public PhotoStrip(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PhotoStrip, 0, 0);
mPhotoSize = a.getDimensionPixelSize(R.styleable.PhotoStrip_photoSize, 44);
mPhotoSpacing = a.getDimensionPixelSize(R.styleable.PhotoStrip_photoSpacing, 10);
mPhotoBorder = a.getDimensionPixelSize(R.styleable.PhotoStrip_photoBorder, 2);
mPhotoBorderStroke = a.getDimensionPixelSize(R.styleable.PhotoStrip_photoBorderStroke, 0);
mPhotoBorderColor = a.getColor(R.styleable.PhotoStrip_photoBorderColor, 0xFFFFFFFF);
mPhotoBorderStrokeColor = a.getColor(R.styleable.PhotoStrip_photoBorderStrokeColor, 0xFFD0D0D);
a.recycle();
}
public void setUsersAndRemoteResourcesManager(Group<User> users, RemoteResourceManager rrm) {
mTypes = users;
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mRrm.addObserver(mResourcesObserver);
invalidate();
}
public void setCheckinsAndRemoteResourcesManager(Group<Checkin> checkins, RemoteResourceManager rrm) {
Group<User> users = new Group<User>();
for (Checkin it : checkins) {
if (it.getUser() != null) {
users.add(it.getUser());
}
}
setUsersAndRemoteResourcesManager(users, rrm);
}
public void removeObserver() {
mRrm.deleteObserver(mResourcesObserver);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mRrm != null && mResourcesObserver != null) {
mRrm.deleteObserver(mResourcesObserver);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
paint.setAntiAlias(true);
int width = getWidth();
int sum = mPhotoSize + mPhotoSpacing;
int index = 0;
while (sum < width) {
if (mTypes == null || index >= mTypes.size()) {
break;
}
Rect rcDst = new Rect(
index * (mPhotoSize + mPhotoSpacing),
0,
index * (mPhotoSize + mPhotoSpacing) + mPhotoSize,
mPhotoSize);
paint.setColor(mPhotoBorderStrokeColor);
canvas.drawRect(rcDst, paint);
rcDst.inset(mPhotoBorderStroke, mPhotoBorderStroke);
paint.setColor(mPhotoBorderColor);
canvas.drawRect(rcDst, paint);
rcDst.inset(mPhotoBorder, mPhotoBorder);
FoursquareType type = mTypes.get(index);
Bitmap bmp = fetchBitmapForUser(type);
if (bmp != null) {
Rect rcSrc = new Rect(0, 0, bmp.getWidth(), bmp.getHeight());
canvas.drawBitmap(bmp, rcSrc, rcDst, paint);
}
sum += (mPhotoSize + mPhotoSpacing);
index++;
}
}
private Bitmap fetchBitmapForUser(FoursquareType type) {
User user = null;
if (type instanceof User) {
user = (User)type;
} else if (type instanceof Checkin) {
Checkin checkin = (Checkin)type;
user = checkin.getUser();
if (user == null) {
return null;
}
} else {
throw new RuntimeException("PhotoStrip can only accept Users or Checkins.");
}
String photoUrl = user.getPhoto();
if (mCachedBitmaps.containsKey(photoUrl)) {
return mCachedBitmaps.get(photoUrl);
}
Uri uriPhoto = Uri.parse(photoUrl);
if (mRrm.exists(uriPhoto)) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(photoUrl)));
mCachedBitmaps.put(photoUrl, bitmap);
return bitmap;
} catch (IOException e) {
}
} else {
mRrm.request(uriPhoto);
}
return BitmapFactory.decodeResource(getResources(), UserUtils.getDrawableByGenderForUserThumbnail(user));
}
/**
* @see android.view.View#measure(int, int)
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(
measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}
/**
* Determines the width of this view
* @param measureSpec A measureSpec packed into an int
* @return The width of the view, honoring constraints from measureSpec
*/
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be.
result = specSize;
}
else {
if (specMode == MeasureSpec.AT_MOST) {
// Use result.
}
else {
// Use result.
}
}
return result;
}
private int measureHeight(int measureSpec) {
// We should be exactly as high as the specified photo size.
// An exception would be if we have zero photos to display,
// we're not dealing with that at the moment.
return mPhotoSize + getPaddingTop() + getPaddingBottom();
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
postInvalidate();
}
}
}
| Java |
/**
* Copyright 2008 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.Venue;
import android.content.Context;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
abstract public class BaseVenueAdapter extends BaseGroupAdapter<Venue> {
public BaseVenueAdapter(Context context) {
super(context);
}
}
| Java |
/**
* Copyright 2008 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.Badge;
import com.joelapenna.foursquared.R;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* @author jlapenna
*/
public class BadgeListAdapter extends BaseBadgeAdapter {
private LayoutInflater mInflater;
private int mLayoutToInflate;
public BadgeListAdapter(Context context) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = R.layout.badge_item;
}
public BadgeListAdapter(Context context, int layoutResource) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = layoutResource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary
// calls to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no
// need to re-inflate it. We only inflate a new View when the
// convertView supplied by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(mLayoutToInflate, null);
// Creates a ViewHolder and store references to the two children
// views we want to bind data to.
holder = new ViewHolder();
holder.icon = (ImageView)convertView.findViewById(R.id.icon);
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.description = (TextView)convertView.findViewById(R.id.description);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder)convertView.getTag();
}
Badge badge = (Badge)getItem(position);
holder.name.setText(badge.getName());
if (holder.description != null) {
if (!TextUtils.isEmpty(badge.getDescription())) {
holder.description.setText(badge.getDescription());
} else {
holder.description.setText("");
}
}
return convertView;
}
static class ViewHolder {
ImageView icon;
TextView name;
TextView description;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
/**
* Interface that our adapters can implement to release any observers they
* may have registered with remote resources manager. Most of the adapters
* register an observer in their constructor, but there is was no appropriate
* place to release them. Parent activities can call this method in their
* onPause(isFinishing()) block to properly release the observers.
*
* If the observers are not released, it will cause a memory leak.
*
* @date March 8, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public interface ObservableAdapter {
public void removeObserver();
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* @date February 15, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class FriendRequestsAdapter extends BaseGroupAdapter<User>
implements ObservableAdapter {
private static final String TAG = "FriendRequestsAdapter";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private LayoutInflater mInflater;
private int mLayoutToInflate;
private ButtonRowClickHandler mClickListener;
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
private Handler mHandler = new Handler();
private int mLoadedPhotoIndex;
public FriendRequestsAdapter(Context context, ButtonRowClickHandler clickListener,
RemoteResourceManager rrm) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = R.layout.friend_request_list_item;
mClickListener = clickListener;
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mLoadedPhotoIndex = 0;
mRrm.addObserver(mResourcesObserver);
}
public FriendRequestsAdapter(Context context, int layoutResource) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = layoutResource;
}
public void removeObserver() {
mHandler.removeCallbacks(mRunnableLoadPhotos);
mRrm.deleteObserver(mResourcesObserver);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary
// calls to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no
// need to re-inflate it. We only inflate a new View when the
// convertView supplied by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(mLayoutToInflate, null);
// Creates a ViewHolder and store references to the two children
// views we want to bind data to.
holder = new ViewHolder();
holder.photo = (ImageView) convertView.findViewById(R.id.friendRequestListItemPhoto);
holder.name = (TextView) convertView.findViewById(R.id.friendRequestListItemName);
holder.add = (Button) convertView.findViewById(R.id.friendRequestApproveButton);
holder.ignore = (Button) convertView.findViewById(R.id.friendRequestDenyButton);
holder.clickable = (LinearLayout) convertView.findViewById(R.id.friendRequestListItemClickableArea);
convertView.setTag(holder);
holder.clickable.setOnClickListener(mOnClickListenerInfo);
holder.add.setOnClickListener(mOnClickListenerApprove);
holder.ignore.setOnClickListener(mOnClickListenerDeny);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
User user = (User) getItem(position);
final Uri photoUri = Uri.parse(user.getPhoto());
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri));
holder.photo.setImageBitmap(bitmap);
} catch (IOException e) {
if (Foursquare.MALE.equals(user.getGender())) {
holder.photo.setImageResource(R.drawable.blank_boy);
} else {
holder.photo.setImageResource(R.drawable.blank_girl);
}
}
holder.name.setText(user.getFirstname() + " "
+ (user.getLastname() != null ? user.getLastname() : ""));
holder.clickable.setTag(new Integer(position));
holder.add.setTag(new Integer(position));
holder.ignore.setTag(new Integer(position));
return convertView;
}
private OnClickListener mOnClickListenerInfo = new OnClickListener() {
@Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
mClickListener.onInfoAreaClick((User) getItem(position));
}
};
private OnClickListener mOnClickListenerApprove = new OnClickListener() {
@Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
mClickListener.onBtnClickAdd((User) getItem(position));
}
};
private OnClickListener mOnClickListenerDeny = new OnClickListener() {
@Override
public void onClick(View v) {
if (mClickListener != null) {
Integer position = (Integer) v.getTag();
mClickListener.onBtnClickIgnore((User) getItem(position));
}
}
};
public void removeItem(int position) throws IndexOutOfBoundsException {
group.remove(position);
notifyDataSetInvalidated();
}
@Override
public void setGroup(Group<User> g) {
super.setGroup(g);
mLoadedPhotoIndex = 0;
mHandler.postDelayed(mRunnableLoadPhotos, 10L);
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Fetcher got: " + data);
mHandler.post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
}
private Runnable mRunnableLoadPhotos = new Runnable() {
@Override
public void run() {
if (mLoadedPhotoIndex < getCount()) {
User user = (User)getItem(mLoadedPhotoIndex++);
Uri photoUri = Uri.parse(user.getPhoto());
if (!mRrm.exists(photoUri)) {
mRrm.request(photoUri);
}
mHandler.postDelayed(mRunnableLoadPhotos, 200L);
}
}
};
static class ViewHolder {
LinearLayout clickable;
ImageView photo;
TextView name;
Button add;
Button ignore;
}
public interface ButtonRowClickHandler {
public void onInfoAreaClick(User user);
public void onBtnClickAdd(User user);
public void onBtnClickIgnore(User user);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.Tip;
import android.content.Context;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
abstract public class BaseTipAdapter extends BaseGroupAdapter<Tip> {
public BaseTipAdapter(Context context) {
super(context);
}
}
| Java |
/**
* Copyright 2008 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.CheckinTimestampSort;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.UiUtil;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Added local hashmap of cached timestamps processed at setGroup()
* time to conform to the same timestamp conventions other foursquare
* apps are using.
*/
public class CheckinListAdapter extends BaseCheckinAdapter implements ObservableAdapter {
private LayoutInflater mInflater;
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
private Handler mHandler = new Handler();
private HashMap<String, String> mCachedTimestamps;
private boolean mIsSdk3;
public CheckinListAdapter(Context context, RemoteResourceManager rrm) {
super(context);
mInflater = LayoutInflater.from(context);
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mCachedTimestamps = new HashMap<String, String>();
mRrm.addObserver(mResourcesObserver);
mIsSdk3 = UiUtil.sdkVersion() == 3;
}
public void removeObserver() {
mHandler.removeCallbacks(mUpdatePhotos);
mRrm.deleteObserver(mResourcesObserver);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary
// calls to findViewById() on each row.
final ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no
// need to re-inflate it. We only inflate a new View when the
// convertView supplied by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.checkin_list_item, null);
// Creates a ViewHolder and store references to the two children
// views we want to bind data to.
holder = new ViewHolder();
holder.photo = (ImageView) convertView.findViewById(R.id.photo);
holder.firstLine = (TextView) convertView.findViewById(R.id.firstLine);
holder.secondLine = (TextView) convertView.findViewById(R.id.secondLine);
holder.timeTextView = (TextView) convertView.findViewById(R.id.timeTextView);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
Checkin checkin = (Checkin) getItem(position);
final User user = checkin.getUser();
final Uri photoUri = Uri.parse(user.getPhoto());
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri));
holder.photo.setImageBitmap(bitmap);
} catch (IOException e) {
if (Foursquare.MALE.equals(user.getGender())) {
holder.photo.setImageResource(R.drawable.blank_boy);
} else {
holder.photo.setImageResource(R.drawable.blank_girl);
}
}
String checkinMsgLine1 = StringFormatters.getCheckinMessageLine1(checkin, true);
String checkinMsgLine2 = StringFormatters.getCheckinMessageLine2(checkin);
String checkinMsgLine3 = mCachedTimestamps.get(checkin.getId());
holder.firstLine.setText(checkinMsgLine1);
if (!TextUtils.isEmpty(checkinMsgLine2)) {
holder.secondLine.setVisibility(View.VISIBLE);
holder.secondLine.setText(checkinMsgLine2);
} else {
if (!mIsSdk3) {
holder.secondLine.setVisibility(View.GONE);
} else {
holder.secondLine.setVisibility(View.INVISIBLE);
}
}
holder.timeTextView.setText(checkinMsgLine3);
return convertView;
}
@Override
public void setGroup(Group<Checkin> g) {
super.setGroup(g);
mCachedTimestamps.clear();
CheckinTimestampSort timestamps = new CheckinTimestampSort();
for (Checkin it : g) {
Uri photoUri = Uri.parse(it.getUser().getPhoto());
if (!mRrm.exists(photoUri)) {
mRrm.request(photoUri);
}
Date date = new Date(it.getCreated());
if (date.after(timestamps.getBoundaryRecent())) {
mCachedTimestamps.put(it.getId(),
StringFormatters.getRelativeTimeSpanString(it.getCreated()).toString());
} else if (date.after(timestamps.getBoundaryToday())) {
mCachedTimestamps.put(it.getId(), StringFormatters.getTodayTimeString(it.getCreated()));
} else if (date.after(timestamps.getBoundaryYesterday())) {
mCachedTimestamps.put(it.getId(), StringFormatters.getYesterdayTimeString(it.getCreated()));
} else {
mCachedTimestamps.put(it.getId(), StringFormatters.getOlderTimeString(it.getCreated()));
}
}
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
mHandler.post(mUpdatePhotos);
}
}
private Runnable mUpdatePhotos = new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
};
private static class ViewHolder {
ImageView photo;
TextView firstLine;
TextView secondLine;
TextView timeTextView;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.UserUtils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* @date September 25, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class FriendActionableListAdapter extends BaseGroupAdapter<User>
implements ObservableAdapter {
private LayoutInflater mInflater;
private int mLayoutToInflate;
private ButtonRowClickHandler mClickListener;
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
private Handler mHandler = new Handler();
private int mLoadedPhotoIndex;
public FriendActionableListAdapter(Context context, ButtonRowClickHandler clickListener,
RemoteResourceManager rrm) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = R.layout.friend_actionable_list_item;
mClickListener = clickListener;
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mLoadedPhotoIndex = 0;
mRrm.addObserver(mResourcesObserver);
}
public FriendActionableListAdapter(Context context, int layoutResource) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = layoutResource;
}
public void removeObserver() {
mHandler.removeCallbacks(mRunnableLoadPhotos);
mHandler.removeCallbacks(mUpdatePhotos);
mRrm.deleteObserver(mResourcesObserver);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(mLayoutToInflate, null);
holder = new ViewHolder();
holder.photo = (ImageView) convertView.findViewById(R.id.photo);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.btn1 = (Button) convertView.findViewById(R.id.btn1);
holder.btn2 = (Button) convertView.findViewById(R.id.btn2);
convertView.setTag(holder);
holder.btn1.setOnClickListener(mOnClickListenerBtn1);
holder.btn2.setOnClickListener(mOnClickListenerBtn2);
} else {
holder = (ViewHolder) convertView.getTag();
}
User user = (User) getItem(position);
final Uri photoUri = Uri.parse(user.getPhoto());
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri));
holder.photo.setImageBitmap(bitmap);
} catch (IOException e) {
if (Foursquare.MALE.equals(user.getGender())) {
holder.photo.setImageResource(R.drawable.blank_boy);
} else {
holder.photo.setImageResource(R.drawable.blank_girl);
}
}
holder.name.setText(user.getFirstname() + " "
+ (user.getLastname() != null ? user.getLastname() : ""));
if (UserUtils.isFollower(user)) {
holder.btn1.setVisibility(View.VISIBLE);
holder.btn2.setVisibility(View.VISIBLE);
holder.btn1.setTag(user);
holder.btn2.setTag(user);
} else {
// Eventually we may have items for this case, like 'delete friend'.
holder.btn1.setVisibility(View.GONE);
holder.btn2.setVisibility(View.GONE);
}
return convertView;
}
private OnClickListener mOnClickListenerBtn1 = new OnClickListener() {
@Override
public void onClick(View v) {
if (mClickListener != null) {
User user = (User) v.getTag();
mClickListener.onBtnClickBtn1(user);
}
}
};
private OnClickListener mOnClickListenerBtn2 = new OnClickListener() {
@Override
public void onClick(View v) {
if (mClickListener != null) {
User user = (User) v.getTag();
mClickListener.onBtnClickBtn2(user);
}
}
};
public void removeItem(int position) throws IndexOutOfBoundsException {
group.remove(position);
notifyDataSetInvalidated();
}
@Override
public void setGroup(Group<User> g) {
super.setGroup(g);
mLoadedPhotoIndex = 0;
mHandler.postDelayed(mRunnableLoadPhotos, 10L);
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
mHandler.post(mUpdatePhotos);
}
}
private Runnable mUpdatePhotos = new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
};
private Runnable mRunnableLoadPhotos = new Runnable() {
@Override
public void run() {
if (mLoadedPhotoIndex < getCount()) {
User user = (User)getItem(mLoadedPhotoIndex++);
Uri photoUri = Uri.parse(user.getPhoto());
if (!mRrm.exists(photoUri)) {
mRrm.request(photoUri);
}
mHandler.postDelayed(mRunnableLoadPhotos, 200L);
}
}
};
static class ViewHolder {
ImageView photo;
TextView name;
Button btn1;
Button btn2;
}
public interface ButtonRowClickHandler {
public void onBtnClickBtn1(User user);
public void onBtnClickBtn2(User user);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.UserUtils;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
/**
*
* @date September 23, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class UserContactAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private int mLayoutToInflate;
private User mUser;
private ArrayList<Action> mActions;
public UserContactAdapter(Context context, User user) {
super();
mInflater = LayoutInflater.from(context);
mLayoutToInflate = R.layout.user_actions_list_item;
mUser = user;
mActions = new ArrayList<Action>();
if (user != null) {
if (UserUtils.isFriend(user)) {
if (TextUtils.isEmpty(mUser.getPhone()) == false) {
mActions.add(new Action(context.getResources().getString(
R.string.user_actions_activity_action_sms),
R.drawable.user_action_text, Action.ACTION_ID_SMS, false));
}
if (TextUtils.isEmpty(mUser.getEmail()) == false) {
mActions.add(new Action(context.getResources().getString(
R.string.user_actions_activity_action_email),
R.drawable.user_action_email, Action.ACTION_ID_EMAIL, false));
}
if (TextUtils.isEmpty(mUser.getEmail()) == false) {
mActions.add(new Action(context.getResources().getString(
R.string.user_actions_activity_action_phone),
R.drawable.user_action_phone, Action.ACTION_ID_PHONE, false));
}
}
if (TextUtils.isEmpty(mUser.getTwitter()) == false) {
mActions.add(new Action(context.getResources().getString(
R.string.user_actions_activity_action_twitter),
R.drawable.user_action_twitter, Action.ACTION_ID_TWITTER, true));
}
if (TextUtils.isEmpty(mUser.getFacebook()) == false) {
mActions.add(new Action(context.getResources().getString(
R.string.user_actions_activity_action_facebook),
R.drawable.user_action_facebook, Action.ACTION_ID_FACEBOOK, true));
}
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(mLayoutToInflate, null);
}
ImageView iv = (ImageView) convertView.findViewById(R.id.userActionsListItemIcon);
TextView tv = (TextView) convertView.findViewById(R.id.userActionsListItemLabel);
Action action = (Action) getItem(position);
iv.setImageResource(action.getIconId());
tv.setText(action.getLabel());
return convertView;
}
@Override
public int getCount() {
return mActions.size();
}
@Override
public Object getItem(int position) {
return mActions.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public static class Action {
public static final int ACTION_ID_SMS = 0;
public static final int ACTION_ID_EMAIL = 1;
public static final int ACTION_ID_PHONE = 2;
public static final int ACTION_ID_TWITTER = 3;
public static final int ACTION_ID_FACEBOOK = 4;
private String mLabel;
private int mIconId;
private int mActionId;
private boolean mIsExternalAction;
public Action(String label, int iconId, int actionId, boolean isExternalAction) {
mLabel = label;
mIconId = iconId;
mActionId = actionId;
mIsExternalAction = isExternalAction;
}
public String getLabel() {
return mLabel;
}
public int getIconId() {
return mIconId;
}
public int getActionId() {
return mActionId;
}
public boolean getIsExternalAction() {
return mIsExternalAction;
}
}
} | Java |
/**
* Copyright 2008 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import android.content.Context;
import android.widget.BaseAdapter;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Group;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
abstract class BaseGroupAdapter<T extends FoursquareType> extends BaseAdapter {
Group<T> group = null;
public BaseGroupAdapter(Context context) {
}
@Override
public int getCount() {
return (group == null) ? 0 : group.size();
}
@Override
public Object getItem(int position) {
return group.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isEmpty() {
return (group == null) ? true : group.isEmpty();
}
public void setGroup(Group<T> g) {
group = g;
notifyDataSetInvalidated();
}
}
| Java |
package com.joelapenna.foursquared.widget;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Score;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.RemoteResourceManager;
public class ScoreListAdapter extends BaseGroupAdapter<Score> implements ObservableAdapter {
private static final String TAG = "ScoreListAdapter";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final String PLUS = " +";
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
private Handler mHandler = new Handler();
private LayoutInflater mInflater;
public ScoreListAdapter(Context context, RemoteResourceManager rrm) {
super(context);
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mInflater = LayoutInflater.from(context);
mRrm.addObserver(mResourcesObserver);
}
public void removeObserver() {
mRrm.deleteObserver(mResourcesObserver);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary
// calls to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no
// need to re-inflate it. We only inflate a new View when the
// convertView supplied by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.score_list_item, null);
// Creates a ViewHolder and store references to the two children
// views we want to bind data to.
holder = new ViewHolder();
holder.scoreIcon = (ImageView) convertView.findViewById(R.id.scoreIcon);
holder.scoreDesc = (TextView) convertView.findViewById(R.id.scoreDesc);
holder.scoreNum = (TextView) convertView.findViewById(R.id.scoreNum);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
Score score = (Score) getItem(position);
holder.scoreDesc.setText(score.getMessage());
String scoreIconUrl = score.getIcon();
if (!TextUtils.isEmpty(scoreIconUrl)) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(//
mRrm.getInputStream(Uri.parse(score.getIcon())));
holder.scoreIcon.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "Could not load bitmap. We don't have it yet.");
holder.scoreIcon.setImageResource(R.drawable.default_on);
}
holder.scoreIcon.setVisibility(View.VISIBLE);
holder.scoreNum.setText(PLUS + score.getPoints());
} else {
holder.scoreIcon.setVisibility(View.INVISIBLE);
holder.scoreNum.setText(score.getPoints());
}
return convertView;
}
static class ViewHolder {
ImageView scoreIcon;
TextView scoreDesc;
TextView scoreNum;
}
@Override
public void setGroup(Group<Score> g) {
super.setGroup(g);
for (int i = 0; i < group.size(); i++) {
Uri iconUri = Uri.parse((group.get(i)).getIcon());
if (!mRrm.exists(iconUri)) {
mRrm.request(iconUri);
}
}
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Fetcher got: " + data);
mHandler.post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
}
}
| Java |
/**
* Copyright 2008 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Mayor;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class MayorListAdapter extends BaseMayorAdapter implements ObservableAdapter {
private static final String TAG = "MayorListAdapter";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private LayoutInflater mInflater;
private RemoteResourceManager mRrm;
private Handler mHandler = new Handler();
private RemoteResourceManagerObserver mResourcesObserver;
public MayorListAdapter(Context context, RemoteResourceManager rrm) {
super(context);
mInflater = LayoutInflater.from(context);
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mRrm.addObserver(mResourcesObserver);
}
public void removeObserver() {
mRrm.deleteObserver(mResourcesObserver);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary
// calls to findViewById() on each row.
final ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no
// need to re-inflate it. We only inflate a new View when the
// convertView supplied by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mayor_list_item, null);
// Creates a ViewHolder and store references to the two children
// views we want to bind data to.
holder = new ViewHolder();
holder.photo = (ImageView)convertView.findViewById(R.id.photo);
holder.firstLine = (TextView)convertView.findViewById(R.id.firstLine);
holder.secondLine = (TextView)convertView.findViewById(R.id.mayorMessageTextView);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder)convertView.getTag();
}
Mayor mayor = (Mayor)getItem(position);
final User user = mayor.getUser();
final Uri photoUri = Uri.parse(user.getPhoto());
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri));
holder.photo.setImageBitmap(bitmap);
} catch (IOException e) {
if (Foursquare.MALE.equals(user.getGender())) {
holder.photo.setImageResource(R.drawable.blank_boy);
} else {
holder.photo.setImageResource(R.drawable.blank_girl);
}
}
holder.firstLine.setText(mayor.getUser().getFirstname());
holder.secondLine.setText(mayor.getMessage());
return convertView;
}
@Override
public void setGroup(Group<Mayor> g) {
super.setGroup(g);
for (int i = 0; i < g.size(); i++) {
Uri photoUri = Uri.parse((g.get(i)).getUser().getPhoto());
if (!mRrm.exists(photoUri)) {
mRrm.request(photoUri);
}
}
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Fetcher got: " + data);
mHandler.post(new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
});
}
}
private static class ViewHolder {
ImageView photo;
TextView firstLine;
TextView secondLine;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquared.R;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* @date June 24, 2010
* @author Mark Wyszomierski (mark@gmail.com)
*/
public class MapCalloutView extends LinearLayout {
private TextView mTextViewTitle;
private TextView mTextViewMessage;
public MapCalloutView(Context context) {
super(context);
}
public MapCalloutView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public void onFinishInflate() {
super.onFinishInflate();
((Activity)getContext()).getLayoutInflater().inflate(R.layout.map_callout_view, this);
mTextViewTitle = (TextView)findViewById(R.id.title);
mTextViewMessage = (TextView)findViewById(R.id.message);
}
public void setTitle(String title) {
mTextViewTitle.setText(title);
}
public void setMessage(String message) {
mTextViewMessage.setText(message);
}
}
| Java |
/* Copyright 2008 Jeff Sharkey
*
* From: http://www.jsharkey.org/blog/2008/08/18/separating-lists-with-headers-in-android-09/
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquared.R;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import java.util.LinkedHashMap;
import java.util.Map;
public class SeparatedListAdapter extends BaseAdapter implements ObservableAdapter {
public final Map<String, Adapter> sections = new LinkedHashMap<String, Adapter>();
public final ArrayAdapter<String> headers;
public final static int TYPE_SECTION_HEADER = 0;
public SeparatedListAdapter(Context context) {
super();
headers = new ArrayAdapter<String>(context, R.layout.list_header);
}
public SeparatedListAdapter(Context context, int layoutId) {
super();
headers = new ArrayAdapter<String>(context, layoutId);
}
public void addSection(String section, Adapter adapter) {
this.headers.add(section);
this.sections.put(section, adapter);
// Register an observer so we can call notifyDataSetChanged() when our
// children adapters are modified, otherwise no change will be visible.
adapter.registerDataSetObserver(mDataSetObserver);
}
public void removeObserver() {
// Notify all our children that they should release their observers too.
for (Map.Entry<String, Adapter> it : sections.entrySet()) {
if (it.getValue() instanceof ObservableAdapter) {
ObservableAdapter adapter = (ObservableAdapter)it.getValue();
adapter.removeObserver();
}
}
}
public void clear() {
headers.clear();
sections.clear();
notifyDataSetInvalidated();
}
@Override
public Object getItem(int position) {
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0) return section;
if (position < size) return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
@Override
public int getCount() {
// total together all sections, plus one for each section header
int total = 0;
for (Adapter adapter : this.sections.values())
total += adapter.getCount() + 1;
return total;
}
@Override
public int getViewTypeCount() {
// assume that headers count as one, then total all sections
int total = 1;
for (Adapter adapter : this.sections.values())
total += adapter.getViewTypeCount();
return total;
}
@Override
public int getItemViewType(int position) {
int type = 1;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if (position == 0) return TYPE_SECTION_HEADER;
if (position < size) return type + adapter.getItemViewType(position - 1);
// otherwise jump into next section
position -= size;
type += adapter.getViewTypeCount();
}
return -1;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public boolean isEnabled(int position) {
return (getItemViewType(position) != TYPE_SECTION_HEADER);
}
@Override
public boolean isEmpty() {
return getCount() == 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
int sectionnum = 0;
for (Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
if (position == 0) return headers.getView(sectionnum, convertView, parent);
if (position < size) return adapter.getView(position - 1, convertView, parent);
// otherwise jump into next section
position -= size;
sectionnum++;
}
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public boolean hasStableIds() {
return false;
}
private DataSetObserver mDataSetObserver = new DataSetObserver() {
@Override
public void onChanged() {
notifyDataSetChanged();
}
};
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.AddressBookEmailBuilder.ContactSimple;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* @date April 26, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class FriendSearchInviteNonFoursquareUserAdapter extends BaseAdapter
implements ObservableAdapter {
private LayoutInflater mInflater;
private int mLayoutToInflate;
private AdapterListener mAdapterListener;
private List<ContactSimple> mEmailsAndNames;
public FriendSearchInviteNonFoursquareUserAdapter(
Context context,
AdapterListener adapterListener) {
super();
mInflater = LayoutInflater.from(context);
mLayoutToInflate = R.layout.add_friends_invite_non_foursquare_user_list_item;
mAdapterListener = adapterListener;
mEmailsAndNames = new ArrayList<ContactSimple>();
}
public void removeObserver() {
}
public FriendSearchInviteNonFoursquareUserAdapter(Context context, int layoutResource) {
super();
mInflater = LayoutInflater.from(context);
mLayoutToInflate = layoutResource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == 0) {
ViewHolderInviteAll holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.add_friends_invite_non_foursquare_all_list_item, null);
holder = new ViewHolderInviteAll();
holder.addAll = (Button) convertView.findViewById(R.id.addFriendNonFoursquareAllListItemBtn);
convertView.setTag(holder);
} else {
holder = (ViewHolderInviteAll) convertView.getTag();
}
holder.addAll.setOnClickListener(mOnClickListenerInviteAll);
}
else {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(mLayoutToInflate, null);
// Creates a ViewHolder and store references to the two children
// views we want to bind data to.
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.addFriendNonFoursquareUserListItemName);
holder.email = (TextView) convertView.findViewById(R.id.addFriendNonFoursquareUserListItemEmail);
holder.add = (Button) convertView.findViewById(R.id.addFriendNonFoursquareUserListItemBtn);
convertView.setTag(holder);
holder.add.setOnClickListener(mOnClickListenerInvite);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(mEmailsAndNames.get(position - 1).mName);
holder.email.setText(mEmailsAndNames.get(position - 1).mEmail);
holder.add.setTag(new Integer(position));
}
return convertView;
}
private OnClickListener mOnClickListenerInvite = new OnClickListener() {
@Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
mAdapterListener.onBtnClickInvite((ContactSimple) getItem(position));
}
};
private OnClickListener mOnClickListenerInviteAll = new OnClickListener() {
@Override
public void onClick(View v) {
mAdapterListener.onInviteAll();
}
};
public void removeItem(int position) throws IndexOutOfBoundsException {
mEmailsAndNames.remove(position);
notifyDataSetInvalidated();
}
public void setContacts(List<ContactSimple> contacts) {
mEmailsAndNames = contacts;
}
static class ViewHolder {
TextView name;
TextView email;
Button add;
}
static class ViewHolderInviteAll {
Button addAll;
}
public interface AdapterListener {
public void onBtnClickInvite(ContactSimple contact);
public void onInfoAreaClick(ContactSimple contact);
public void onInviteAll();
}
@Override
public int getCount() {
if (mEmailsAndNames.size() > 0) {
return mEmailsAndNames.size() + 1;
}
return 0;
}
@Override
public Object getItem(int position) {
if (position == 0) {
return "";
}
return mEmailsAndNames.get(position - 1);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return 0;
}
return 1;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.TipUtils;
import com.joelapenna.foursquared.util.UiUtil;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
/**
* @date September 12, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TodosListAdapter extends BaseGroupAdapter<Todo>
implements ObservableAdapter {
private LayoutInflater mInflater;
private int mLayoutToInflate;
private Resources mResources;
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
private Handler mHandler = new Handler();
private int mLoadedPhotoIndex;
private Map<String, String> mCachedTimestamps;
private boolean mDisplayVenueTitles;
private int mSdk;
public TodosListAdapter(Context context, RemoteResourceManager rrm) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = R.layout.todo_list_item;
mResources = context.getResources();
mRrm = rrm;
mResourcesObserver = new RemoteResourceManagerObserver();
mLoadedPhotoIndex = 0;
mCachedTimestamps = new HashMap<String, String>();
mDisplayVenueTitles = true;
mSdk = UiUtil.sdkVersion();
mRrm.addObserver(mResourcesObserver);
}
public void removeObserver() {
mHandler.removeCallbacks(mUpdatePhotos);
mHandler.removeCallbacks(mRunnableLoadPhotos);
mRrm.deleteObserver(mResourcesObserver);
}
public TodosListAdapter(Context context, int layoutResource) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = layoutResource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary
// calls to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no
// need to re-inflate it. We only inflate a new View when the
// convertView supplied by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(mLayoutToInflate, null);
// Creates a ViewHolder and store references to the two children
// views we want to bind data to.
holder = new ViewHolder();
holder.photo = (ImageView) convertView.findViewById(R.id.ivVenueCategory);
holder.title = (TextView) convertView.findViewById(R.id.tvTitle);
holder.body = (TextView) convertView.findViewById(R.id.tvBody);
holder.dateAndAuthor = (TextView) convertView.findViewById(R.id.tvDateAndAuthor);
holder.corner = (ImageView) convertView.findViewById(R.id.ivTipCorner);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
Todo todo = (Todo)getItem(position);
Tip tip = todo.getTip();
if (tip != null) {
if (mDisplayVenueTitles && tip.getVenue() != null) {
holder.title.setText("@ " + tip.getVenue().getName());
holder.title.setVisibility(View.VISIBLE);
} else {
holder.title.setVisibility(View.GONE);
holder.body.setPadding(
holder.body.getPaddingLeft(), holder.title.getPaddingTop(),
holder.body.getPaddingRight(), holder.body.getPaddingBottom());
}
if (tip.getVenue() != null && tip.getVenue().getCategory() != null) {
Uri photoUri = Uri.parse(tip.getVenue().getCategory().getIconUrl());
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri));
holder.photo.setImageBitmap(bitmap);
} catch (IOException e) {
holder.photo.setImageResource(R.drawable.category_none);
}
} else {
holder.photo.setImageResource(R.drawable.category_none);
}
if (!TextUtils.isEmpty(tip.getText())) {
holder.body.setText(tip.getText());
holder.body.setVisibility(View.VISIBLE);
} else {
if (mSdk > 3) {
holder.body.setVisibility(View.GONE);
} else {
holder.body.setText("");
holder.body.setVisibility(View.INVISIBLE);
}
}
if (tip.getUser() != null) {
holder.dateAndAuthor.setText(
holder.dateAndAuthor.getText() +
mResources.getString(
R.string.tip_age_via,
StringFormatters.getUserFullName(tip.getUser())));
}
if (TipUtils.isDone(tip)) {
holder.corner.setVisibility(View.VISIBLE);
holder.corner.setImageResource(R.drawable.tip_list_item_corner_done);
} else if (TipUtils.isTodo(tip)) {
holder.corner.setVisibility(View.VISIBLE);
holder.corner.setImageResource(R.drawable.tip_list_item_corner_todo);
} else {
holder.corner.setVisibility(View.GONE);
}
} else {
holder.title.setText("");
holder.body.setText("");
holder.corner.setVisibility(View.VISIBLE);
holder.corner.setImageResource(R.drawable.tip_list_item_corner_todo);
holder.photo.setImageResource(R.drawable.category_none);
}
holder.dateAndAuthor.setText(mResources.getString(
R.string.todo_added_date,
mCachedTimestamps.get(todo.getId())));
return convertView;
}
public void removeItem(int position) throws IndexOutOfBoundsException {
group.remove(position);
notifyDataSetInvalidated();
}
@Override
public void setGroup(Group<Todo> g) {
super.setGroup(g);
mLoadedPhotoIndex = 0;
mHandler.postDelayed(mRunnableLoadPhotos, 10L);
mCachedTimestamps.clear();
for (Todo it : g) {
String formatted = StringFormatters.getTipAge(mResources, it.getCreated());
mCachedTimestamps.put(it.getId(), formatted);
}
}
public void setDisplayTodoVenueTitles(boolean displayTodoVenueTitles) {
mDisplayVenueTitles = displayTodoVenueTitles;
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
mHandler.post(mUpdatePhotos);
}
}
private Runnable mUpdatePhotos = new Runnable() {
@Override
public void run() {
notifyDataSetChanged();
}
};
private Runnable mRunnableLoadPhotos = new Runnable() {
@Override
public void run() {
if (mLoadedPhotoIndex < getCount()) {
Todo todo = (Todo)getItem(mLoadedPhotoIndex++);
if (todo.getTip() != null && todo.getTip().getVenue() != null) {
Venue venue = todo.getTip().getVenue();
if (venue.getCategory() != null) {
Uri photoUri = Uri.parse(venue.getCategory().getIconUrl());
if (!mRrm.exists(photoUri)) {
mRrm.request(photoUri);
}
mHandler.postDelayed(mRunnableLoadPhotos, 200L);
}
}
}
}
};
static class ViewHolder {
ImageView photo;
TextView title;
TextView body;
TextView dateAndAuthor;
ImageView corner;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.TabsUtil;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.util.UserUtils;
import android.app.Activity;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.TabHost;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class MainActivity extends TabActivity {
public static final String TAG = "MainActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private TabHost mTabHost;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
// Don't start the main activity if we don't have credentials
if (!((Foursquared) getApplication()).isReady()) {
if (DEBUG) Log.d(TAG, "Not ready for user.");
redirectToLoginActivity();
}
if (DEBUG) Log.d(TAG, "Setting up main activity layout.");
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.main_activity);
initTabHost();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
private void initTabHost() {
if (mTabHost != null) {
throw new IllegalStateException("Trying to intialize already initializd TabHost");
}
mTabHost = getTabHost();
// We may want to show the friends tab first, or the places tab first, depending on
// the user preferences.
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
// We can add more tabs here eventually, but if "Friends" isn't the startup tab, then
// we are left with "Places" being the startup tab instead.
String[] startupTabValues = getResources().getStringArray(R.array.startup_tabs_values);
String startupTab = settings.getString(
Preferences.PREFERENCE_STARTUP_TAB, startupTabValues[0]);
Intent intent = new Intent(this, NearbyVenuesActivity.class);
if (startupTab.equals(startupTabValues[0])) {
TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_friends), R.drawable.tab_main_nav_friends_selector,
1, new Intent(this, FriendsActivity.class));
TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_nearby), R.drawable.tab_main_nav_nearby_selector,
2, intent);
} else {
intent.putExtra(NearbyVenuesActivity.INTENT_EXTRA_STARTUP_GEOLOC_DELAY, 4000L);
TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_nearby), R.drawable.tab_main_nav_nearby_selector,
1, intent);
TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_friends), R.drawable.tab_main_nav_friends_selector,
2, new Intent(this, FriendsActivity.class));
}
TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_tips), R.drawable.tab_main_nav_tips_selector,
3, new Intent(this, TipsActivity.class));
TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_todos), R.drawable.tab_main_nav_todos_selector,
4, new Intent(this, TodosActivity.class));
// 'Me' tab, just shows our own info. At this point we should have a
// stored user id, and a user gender to control the image which is
// displayed on the tab.
String userId = ((Foursquared) getApplication()).getUserId();
String userGender = ((Foursquared) getApplication()).getUserGender();
Intent intentTabMe = new Intent(this, UserDetailsActivity.class);
intentTabMe.putExtra(UserDetailsActivity.EXTRA_USER_ID, userId == null ? "unknown"
: userId);
TabsUtil.addTab(mTabHost, getString(R.string.tab_main_nav_me),
UserUtils.getDrawableForMeTabByGender(userGender), 5, intentTabMe);
// Fix layout for 1.5.
if (UiUtil.sdkVersion() < 4) {
FrameLayout flTabContent = (FrameLayout)findViewById(android.R.id.tabcontent);
flTabContent.setPadding(0, 0, 0, 0);
}
}
private void redirectToLoginActivity() {
setVisible(false);
Intent intent = new Intent(this, LoginActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.setFlags(
Intent.FLAG_ACTIVITY_NO_HISTORY |
Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS |
Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.TipUtils;
/**
* Shows actions a user can perform on a tip, which includes marking a tip
* as a to-do, marking a tip as done, un-marking a tip. Marking a tip as
* a to-do will generate a to-do, which has the tip as a child object.
*
* The intent will return a Tip object and a Todo object (if the final state
* of the tip was marked as a Todo). In the case where a Todo is returned,
* the Tip will be the representation as found within the Todo object.
*
* If the user does not modify the tip, no intent data is returned. If the
* final state of the tip was not marked as a to-do, the Todo object is
* not returned.
*
* @date September 2, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class TipActivity extends Activity {
private static final String TAG = "TipActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_TIP_PARCEL = Foursquared.PACKAGE_NAME
+ ".TipActivity.EXTRA_TIP_PARCEL";
public static final String EXTRA_VENUE_CLICKABLE = Foursquared.PACKAGE_NAME
+ ".TipActivity.EXTRA_VENUE_CLICKABLE";
/**
* Always returned if the user modifies the tip in any way. Captures the
* new <status> attribute of the tip. It may not have been changed by the
* user.
*/
public static final String EXTRA_TIP_RETURNED = Foursquared.PACKAGE_NAME
+ ".TipActivity.EXTRA_TIP_RETURNED";
/**
* If the user marks the tip as to-do as the final state, then a to-do object
* will also be returned here. The to-do object has the same tip object as
* returned in EXTRA_TIP_PARCEL_RETURNED as a child member.
*/
public static final String EXTRA_TODO_RETURNED = Foursquared.PACKAGE_NAME
+ ".TipActivity.EXTRA_TODO_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tip_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivityForTipTask(this);
setPreparedResultIntent();
} else {
mStateHolder = new StateHolder();
if (getIntent().getExtras() != null) {
if (getIntent().hasExtra(EXTRA_TIP_PARCEL)) {
Tip tip = getIntent().getExtras().getParcelable(EXTRA_TIP_PARCEL);
mStateHolder.setTip(tip);
} else {
Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras.");
finish();
return;
}
if (getIntent().hasExtra(EXTRA_VENUE_CLICKABLE)) {
mStateHolder.setVenueClickable(
getIntent().getBooleanExtra(EXTRA_VENUE_CLICKABLE, true));
}
} else {
Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public void onResume() {
super.onResume();
if (mStateHolder.getIsRunningTipTask()) {
startProgressBar();
}
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
stopProgressBar();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTipTask(null);
return mStateHolder;
}
private void ensureUi() {
Tip tip = mStateHolder.getTip();
Venue venue = tip.getVenue();
LinearLayout llHeader = (LinearLayout)findViewById(R.id.tipActivityHeaderView);
if (mStateHolder.getVenueClickable()) {
llHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showVenueDetailsActivity(mStateHolder.getTip().getVenue());
}
});
}
ImageView ivVenueChevron = (ImageView)findViewById(R.id.tipActivityVenueChevron);
if (mStateHolder.getVenueClickable()) {
ivVenueChevron.setVisibility(View.VISIBLE);
} else {
ivVenueChevron.setVisibility(View.INVISIBLE);
}
TextView tvTitle = (TextView)findViewById(R.id.tipActivityName);
TextView tvAddress = (TextView)findViewById(R.id.tipActivityAddress);
if (venue != null) {
tvTitle.setText(venue.getName());
tvAddress.setText(
venue.getAddress() +
(TextUtils.isEmpty(venue.getCrossstreet()) ?
"" : " (" + venue.getCrossstreet() + ")"));
} else {
tvTitle.setText("");
tvAddress.setText("");
}
TextView tvBody = (TextView)findViewById(R.id.tipActivityBody);
tvBody.setText(tip.getText());
String created = getResources().getString(
R.string.tip_activity_created,
StringFormatters.getTipAge(getResources(), tip.getCreated()));
TextView tvDate = (TextView)findViewById(R.id.tipActivityDate);
tvDate.setText(created);
TextView tvAuthor = (TextView)findViewById(R.id.tipActivityAuthor);
if (tip.getUser() != null) {
tvAuthor.setText(tip.getUser().getFirstname());
tvAuthor.setClickable(true);
tvAuthor.setFocusable(true);
tvAuthor.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showUserDetailsActivity(mStateHolder.getTip().getUser());
}
});
tvDate.setText(tvDate.getText() + getResources().getString(
R.string.tip_activity_created_by));
} else {
tvAuthor.setText("");
}
Button btn1 = (Button)findViewById(R.id.tipActivityyAddTodoList);
Button btn2 = (Button)findViewById(R.id.tipActivityIveDoneThis);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onBtnTodo();
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onBtnDone();
}
});
updateButtonStates();
}
private void onBtnTodo() {
Tip tip = mStateHolder.getTip();
if (TipUtils.isTodo(tip)) {
mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(),
TipTask.ACTION_UNMARK_TODO);
} else {
mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(),
TipTask.ACTION_TODO);
}
}
private void onBtnDone() {
Tip tip = mStateHolder.getTip();
if (TipUtils.isDone(tip)) {
mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(),
TipTask.ACTION_UNMARK_DONE);
} else {
mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(),
TipTask.ACTION_DONE);
}
}
private void updateButtonStates() {
Button btn1 = (Button)findViewById(R.id.tipActivityyAddTodoList);
Button btn2 = (Button)findViewById(R.id.tipActivityIveDoneThis);
TextView tv = (TextView)findViewById(R.id.tipActivityCongrats);
Tip tip = mStateHolder.getTip();
if (TipUtils.isTodo(tip)) {
btn1.setText(getResources().getString(R.string.tip_activity_btn_tip_1)); // "REMOVE FROM MY TO-DO LIST"
btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_2)); // "I'VE DONE THIS"
btn1.setVisibility(View.VISIBLE);
tv.setVisibility(View.GONE);
} else if (TipUtils.isDone(tip)) {
tv.setText(getResources().getString(R.string.tip_activity_btn_tip_4)); // "CONGRATS! YOU'VE DONE THIS"
btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_3)); // "UNDO THIS"
btn1.setVisibility(View.GONE);
tv.setVisibility(View.VISIBLE);
} else {
btn1.setText(getResources().getString(R.string.tip_activity_btn_tip_0)); // "ADD TO MY TO-DO LIST"
btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_2)); // "I'VE DONE THIS"
btn1.setVisibility(View.VISIBLE);
tv.setVisibility(View.GONE);
}
}
private void showUserDetailsActivity(User user) {
Intent intent = new Intent(this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, user.getId());
startActivity(intent);
}
private void showVenueDetailsActivity(Venue venue) {
Intent intent = new Intent(this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
startActivity(intent);
}
private void startProgressBar() {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, "",
getResources().getString(R.string.tip_activity_progress_message));
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
private void prepareResultIntent(Tip tip, Todo todo) {
Intent intent = new Intent();
intent.putExtra(EXTRA_TIP_RETURNED, tip);
if (todo != null) {
intent.putExtra(EXTRA_TODO_RETURNED, todo); // tip is also a part of the to-do.
}
mStateHolder.setPreparedResult(intent);
setPreparedResultIntent();
}
private void setPreparedResultIntent() {
if (mStateHolder.getPreparedResult() != null) {
setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult());
}
}
private void onTipTaskComplete(FoursquareType tipOrTodo, int type, Exception ex) {
stopProgressBar();
mStateHolder.setIsRunningTipTask(false);
if (tipOrTodo != null) {
// When the tip and todo are serialized into the intent result, the
// link between them will be lost, they'll appear as two separate
// tip object instances (ids etc will all be the same though).
if (tipOrTodo instanceof Tip) {
Tip tip = (Tip)tipOrTodo;
mStateHolder.setTip(tip);
prepareResultIntent(tip, null);
} else {
Todo todo = (Todo)tipOrTodo;
Tip tip = todo.getTip();
mStateHolder.setTip(tip);
prepareResultIntent(tip, todo);
}
} else if (ex != null) {
Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Error updating tip!", Toast.LENGTH_LONG).show();
}
ensureUi();
}
private static class TipTask extends AsyncTask<String, Void, FoursquareType> {
private TipActivity mActivity;
private String mTipId;
private int mTask;
private Exception mReason;
public static final int ACTION_TODO = 0;
public static final int ACTION_DONE = 1;
public static final int ACTION_UNMARK_TODO = 2;
public static final int ACTION_UNMARK_DONE = 3;
public TipTask(TipActivity activity, String tipid, int task) {
mActivity = activity;
mTipId = tipid;
mTask = task;
}
public void setActivity(TipActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected FoursquareType doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
switch (mTask) {
case ACTION_TODO:
return foursquare.markTodo(mTipId); // returns a todo.
case ACTION_DONE:
return foursquare.markDone(mTipId); // returns a tip.
case ACTION_UNMARK_TODO:
return foursquare.unmarkTodo(mTipId); // returns a tip
case ACTION_UNMARK_DONE:
return foursquare.unmarkDone(mTipId); // returns a tip
default:
return null;
}
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "TipTask: Exception performing tip task.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(FoursquareType tipOrTodo) {
if (DEBUG) Log.d(TAG, "TipTask: onPostExecute()");
if (mActivity != null) {
mActivity.onTipTaskComplete(tipOrTodo, mTask, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTipTaskComplete(null, mTask, new Exception("Tip task cancelled."));
}
}
}
private static class StateHolder {
private Tip mTip;
private TipTask mTipTask;
private boolean mIsRunningTipTask;
private boolean mVenueClickable;
private Intent mPreparedResult;
public StateHolder() {
mTip = null;
mPreparedResult = null;
mIsRunningTipTask = false;
mVenueClickable = true;
}
public Tip getTip() {
return mTip;
}
public void setTip(Tip tip) {
mTip = tip;
}
public void startTipTask(TipActivity activity, String tipId, int task) {
mIsRunningTipTask = true;
mTipTask = new TipTask(activity, tipId, task);
mTipTask.execute();
}
public void setActivityForTipTask(TipActivity activity) {
if (mTipTask != null) {
mTipTask.setActivity(activity);
}
}
public void setIsRunningTipTask(boolean isRunningTipTask) {
mIsRunningTipTask = isRunningTipTask;
}
public boolean getIsRunningTipTask() {
return mIsRunningTipTask;
}
public boolean getVenueClickable() {
return mVenueClickable;
}
public void setVenueClickable(boolean venueClickable) {
mVenueClickable = venueClickable;
}
public Intent getPreparedResult() {
return mPreparedResult;
}
public void setPreparedResult(Intent intent) {
mPreparedResult = intent;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.joelapenna.foursquared.widget.TipsListAdapter;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.Observable;
import java.util.Observer;
/**
* Shows a list of nearby tips. User can sort tips by friends-only.
*
* @date August 31, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TipsActivity extends LoadableListActivityWithViewAndHeader {
static final String TAG = "TipsActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int ACTIVITY_TIP = 500;
private StateHolder mStateHolder;
private TipsListAdapter mListAdapter;
private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver();
private View 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();
mStateHolder.setFriendsOnly(true);
}
ensureUi();
// Friend tips is shown first by default so auto-fetch it if necessary.
if (!mStateHolder.getRanOnceTipsFriends()) {
mStateHolder.startTaskTips(this, true);
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver);
if (isFinishing()) {
mStateHolder.cancelTasks();
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void ensureUi() {
LayoutInflater inflater = LayoutInflater.from(this);
mLayoutEmpty = inflater.inflate(R.layout.tips_activity_empty, null);
mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
mListAdapter = new TipsListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item);
if (mStateHolder.getFriendsOnly()) {
mListAdapter.setGroup(mStateHolder.getTipsFriends());
if (mStateHolder.getTipsFriends().size() == 0) {
if (mStateHolder.getRanOnceTipsFriends()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
} else {
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
if (mStateHolder.getTipsEveryone().size() == 0) {
if (mStateHolder.getRanOnceTipsEveryone()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
}
SegmentedButton buttons = getHeaderButton();
buttons.clearButtons();
buttons.addButtons(
getString(R.string.tips_activity_btn_friends_only),
getString(R.string.tips_activity_btn_everyone));
if (mStateHolder.mFriendsOnly) {
buttons.setPushedButtonIndex(0);
} else {
buttons.setPushedButtonIndex(1);
}
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
if (index == 0) {
mStateHolder.setFriendsOnly(true);
mListAdapter.setGroup(mStateHolder.getTipsFriends());
if (mStateHolder.getTipsFriends().size() < 1) {
if (mStateHolder.getRanOnceTipsFriends()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(TipsActivity.this, true);
}
}
} else {
mStateHolder.setFriendsOnly(false);
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
if (mStateHolder.getTipsEveryone().size() < 1) {
if (mStateHolder.getRanOnceTipsEveryone()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(TipsActivity.this, false);
}
}
}
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) {
Tip tip = (Tip) parent.getAdapter().getItem(position);
Intent intent = new Intent(TipsActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip);
startActivityForResult(intent, ACTIVITY_TIP);
}
});
if (mStateHolder.getIsRunningTaskTipsFriends() ||
mStateHolder.getIsRunningTaskTipsEveryone()) {
setProgressBarIndeterminateVisibility(true);
} else {
setProgressBarIndeterminateVisibility(false);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh)
.setIcon(R.drawable.ic_menu_refresh);
MenuUtils.addPreferencesToMenu(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
mStateHolder.startTaskTips(this, mStateHolder.getFriendsOnly());
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// We don't care about the returned to-do (if any) since we're not bound
// to a venue in this activity for update. We just update the status member
// of the target tip.
if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) {
if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) {
Log.d(TAG, "onActivityResult(), return tip intent extra found, processing.");
updateTip((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED));
} else {
Log.d(TAG, "onActivityResult(), no return tip intent extra found.");
}
}
}
private void updateTip(Tip tip) {
mStateHolder.updateTip(tip);
mListAdapter.notifyDataSetInvalidated();
}
private void onStartTaskTips() {
if (mListAdapter != null) {
if (mStateHolder.getFriendsOnly()) {
mStateHolder.setIsRunningTaskTipsFriends(true);
mListAdapter.setGroup(mStateHolder.getTipsFriends());
} else {
mStateHolder.setIsRunningTaskTipsEveryone(true);
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
}
mListAdapter.notifyDataSetChanged();
}
setProgressBarIndeterminateVisibility(true);
setLoadingView();
}
private void onTaskTipsComplete(Group<Tip> group, boolean friendsOnly, Exception ex) {
SegmentedButton buttons = getHeaderButton();
boolean update = false;
if (group != null) {
if (friendsOnly) {
mStateHolder.setTipsFriends(group);
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsFriends());
update = true;
}
} else {
mStateHolder.setTipsEveryone(group);
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
update = true;
}
}
}
else {
if (friendsOnly) {
mStateHolder.setTipsFriends(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsFriends());
update = true;
}
} else {
mStateHolder.setTipsEveryone(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
update = true;
}
}
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (friendsOnly) {
mStateHolder.setIsRunningTaskTipsFriends(false);
mStateHolder.setRanOnceTipsFriends(true);
if (mStateHolder.getTipsFriends().size() == 0 &&
buttons.getSelectedButtonIndex() == 0) {
setEmptyView(mLayoutEmpty);
}
} else {
mStateHolder.setIsRunningTaskTipsEveryone(false);
mStateHolder.setRanOnceTipsEveryone(true);
if (mStateHolder.getTipsEveryone().size() == 0 &&
buttons.getSelectedButtonIndex() == 1) {
setEmptyView(mLayoutEmpty);
}
}
if (update) {
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
if (!mStateHolder.getIsRunningTaskTipsFriends() &&
!mStateHolder.getIsRunningTaskTipsEveryone()) {
setProgressBarIndeterminateVisibility(false);
}
}
/**
* Gets friends of the current user we're working for.
*/
private static class TaskTips extends AsyncTask<Void, Void, Group<Tip>> {
private TipsActivity mActivity;
private boolean mFriendsOnly;
private Exception mReason;
public TaskTips(TipsActivity activity, boolean friendsOnly) {
mActivity = activity;
mFriendsOnly = friendsOnly;
}
@Override
protected void onPreExecute() {
mActivity.onStartTaskTips();
}
@Override
protected Group<Tip> doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
Location loc = foursquared.getLastKnownLocation();
if (loc == null) {
try { Thread.sleep(3000); } catch (InterruptedException ex) {}
loc = foursquared.getLastKnownLocation();
if (loc == null) {
throw new FoursquareException("Your location could not be determined!");
}
}
return foursquare.tips(
LocationUtils.createFoursquareLocation(loc),
null,
mFriendsOnly ? "friends" : "nearby",
null,
30);
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Tip> tips) {
if (mActivity != null) {
mActivity.onTaskTipsComplete(tips, mFriendsOnly, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskTipsComplete(null, mFriendsOnly, mReason);
}
}
public void setActivity(TipsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
/** Tips by friends. */
private Group<Tip> mTipsFriends;
/** Tips by everyone. */
private Group<Tip> mTipsEveryone;
private TaskTips mTaskTipsFriends;
private TaskTips mTaskTipsEveryone;
private boolean mIsRunningTaskTipsFriends;
private boolean mIsRunningTaskTipsEveryone;
private boolean mFriendsOnly;
private boolean mRanOnceTipsFriends;
private boolean mRanOnceTipsEveryone;
public StateHolder() {
mIsRunningTaskTipsFriends = false;
mIsRunningTaskTipsEveryone = false;
mRanOnceTipsFriends = false;
mRanOnceTipsEveryone = false;
mTipsFriends = new Group<Tip>();
mTipsEveryone = new Group<Tip>();
mFriendsOnly = true;
}
public Group<Tip> getTipsFriends() {
return mTipsFriends;
}
public void setTipsFriends(Group<Tip> tipsFriends) {
mTipsFriends = tipsFriends;
}
public Group<Tip> getTipsEveryone() {
return mTipsEveryone;
}
public void setTipsEveryone(Group<Tip> tipsEveryone) {
mTipsEveryone = tipsEveryone;
}
public void startTaskTips(TipsActivity activity,
boolean friendsOnly) {
if (friendsOnly) {
if (mIsRunningTaskTipsFriends) {
return;
}
mIsRunningTaskTipsFriends = true;
mTaskTipsFriends = new TaskTips(activity, friendsOnly);
mTaskTipsFriends.execute();
} else {
if (mIsRunningTaskTipsEveryone) {
return;
}
mIsRunningTaskTipsEveryone = true;
mTaskTipsEveryone = new TaskTips(activity, friendsOnly);
mTaskTipsEveryone.execute();
}
}
public void setActivity(TipsActivity activity) {
if (mTaskTipsFriends != null) {
mTaskTipsFriends.setActivity(activity);
}
if (mTaskTipsEveryone != null) {
mTaskTipsEveryone.setActivity(activity);
}
}
public boolean getIsRunningTaskTipsFriends() {
return mIsRunningTaskTipsFriends;
}
public void setIsRunningTaskTipsFriends(boolean isRunning) {
mIsRunningTaskTipsFriends = isRunning;
}
public boolean getIsRunningTaskTipsEveryone() {
return mIsRunningTaskTipsEveryone;
}
public void setIsRunningTaskTipsEveryone(boolean isRunning) {
mIsRunningTaskTipsEveryone = isRunning;
}
public void cancelTasks() {
if (mTaskTipsFriends != null) {
mTaskTipsFriends.setActivity(null);
mTaskTipsFriends.cancel(true);
}
if (mTaskTipsEveryone != null) {
mTaskTipsEveryone.setActivity(null);
mTaskTipsEveryone.cancel(true);
}
}
public boolean getFriendsOnly() {
return mFriendsOnly;
}
public void setFriendsOnly(boolean friendsOnly) {
mFriendsOnly = friendsOnly;
}
public boolean getRanOnceTipsFriends() {
return mRanOnceTipsFriends;
}
public void setRanOnceTipsFriends(boolean ranOnce) {
mRanOnceTipsFriends = ranOnce;
}
public boolean getRanOnceTipsEveryone() {
return mRanOnceTipsEveryone;
}
public void setRanOnceTipsEveryone(boolean ranOnce) {
mRanOnceTipsEveryone = ranOnce;
}
public void updateTip(Tip tip) {
updateTipFromArray(tip, mTipsFriends);
updateTipFromArray(tip, mTipsEveryone);
}
private void updateTipFromArray(Tip tip, Group<Tip> target) {
for (Tip it : target) {
if (it.getId().equals(tip.getId())) {
it.setStatus(tip.getStatus());
break;
}
}
}
}
/**
* This is really just a dummy observer to get the GPS running
* since this is the new splash page. After getting a fix, we
* might want to stop registering this observer thereafter so
* it doesn't annoy the user too much.
*/
private class SearchLocationObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
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.UserUtils;
import com.joelapenna.foursquared.util.VenueUtils;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.TipsListAdapter;
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 java.util.List;
/**
* Shows tips left at a venue as a sectioned list adapter. Groups are split
* into tips left by friends and tips left by everyone else.
*
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -modified to start TipActivity on tip click (2010-03-25)
* -added photos for tips (2010-03-25)
* -refactored for new VenueActivity design (2010-09-16)
*/
public class VenueTipsActivity extends LoadableListActivity {
public static final String TAG = "VenueTipsActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".VenueTipsActivity.INTENT_EXTRA_VENUE";
public static final String INTENT_EXTRA_RETURN_VENUE = Foursquared.PACKAGE_NAME
+ ".VenueTipsActivity.INTENT_EXTRA_RETURN_VENUE";
private static final int ACTIVITY_TIP = 500;
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;
setPreparedResultIntent();
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE));
} else {
Log.e(TAG, "VenueTipsActivity requires a venue parcel its intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mListAdapter.removeObserver();
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
return mStateHolder;
}
private void ensureUi() {
mListAdapter = new SeparatedListAdapter(this);
if (mStateHolder.getTipsFriends().size() > 0) {
TipsListAdapter adapter = new TipsListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item);
adapter.setDisplayTipVenueTitles(false);
adapter.setGroup(mStateHolder.getTipsFriends());
mListAdapter.addSection(getString(R.string.venue_tips_activity_section_friends,
mStateHolder.getTipsFriends().size()),
adapter);
}
TipsListAdapter adapter = new TipsListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item);
adapter.setDisplayTipVenueTitles(false);
adapter.setGroup(mStateHolder.getTipsAll());
mListAdapter.addSection(getString(R.string.venue_tips_activity_section_all,
mStateHolder.getTipsAll().size()),
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) {
// 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());
Tip tip = (Tip)parent.getAdapter().getItem(position);
tip.setVenue(venue);
Intent intent = new Intent(VenueTipsActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip);
intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false);
startActivityForResult(intent, ACTIVITY_TIP);
}
});
setTitle(getString(R.string.venue_tips_activity_title, mStateHolder.getVenue().getName()));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) {
if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) {
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) {
mStateHolder.updateTip(tip, todo);
mListAdapter.notifyDataSetInvalidated();
prepareResultIntent();
}
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 Group<Tip> mTipsFriends;
private Group<Tip> mTipsAll;
private Intent mPreparedResult;
public StateHolder() {
mPreparedResult = null;
mTipsFriends = new Group<Tip>();
mTipsAll = new Group<Tip>();
}
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
mTipsFriends.clear();
mTipsAll.clear();
for (Tip tip : venue.getTips()) {
if (UserUtils.isFriend(tip.getUser())) {
mTipsFriends.add(tip);
} else {
mTipsAll.add(tip);
}
}
}
public Group<Tip> getTipsFriends() {
return mTipsFriends;
}
public Group<Tip> getTipsAll() {
return mTipsAll;
}
public Intent getPreparedResult() {
return mPreparedResult;
}
public void setPreparedResult(Intent intent) {
mPreparedResult = intent;
}
public void updateTip(Tip tip, Todo todo) {
// Changes to a tip status can produce or remove a to-do for its
// parent venue.
VenueUtils.handleTipChange(mVenue, tip, todo);
// Also update the tip from wherever it appears in the separated
// list adapter sections.
updateTip(tip, mTipsFriends);
updateTip(tip, mTipsAll);
}
private void updateTip(Tip tip, List<Tip> target) {
for (Tip it : target) {
if (it.getId().equals(tip.getId())) {
it.setStatus(tip.getStatus());
break;
}
}
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.CheckinTimestampSort;
import com.joelapenna.foursquared.util.Comparators;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.widget.CheckinListAdapter;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Added dummy location observer, new menu icon logic,
* links to new user activity (3/10/2010).
* -Sorting checkins by distance/time. (3/18/2010).
* -Added option to sort by server response, or by distance. (6/10/2010).
* -Reformatted/refactored. (9/22/2010).
*/
public class FriendsActivity extends LoadableListActivityWithViewAndHeader {
static final String TAG = "FriendsActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final int CITY_RADIUS_IN_METERS = 20 * 1000; // 20km
private static final long SLEEP_TIME_IF_NO_LOCATION = 3000L;
private static final int MENU_GROUP_SEARCH = 0;
private static final int MENU_REFRESH = 1;
private static final int MENU_SHOUT = 2;
private static final int MENU_MORE = 3;
private static final int MENU_MORE_MAP = 20;
private static final int MENU_MORE_LEADERBOARD = 21;
private static final int SORT_METHOD_RECENT = 0;
private static final int SORT_METHOD_NEARBY = 1;
private StateHolder mStateHolder;
private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver();
private LinkedHashMap<Integer, String> mMenuMoreSubitems;
private SeparatedListAdapter mListAdapter;
private ViewGroup mLayoutEmpty;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
if (getLastNonConfigurationInstance() != null) {
mStateHolder = (StateHolder) getLastNonConfigurationInstance();
mStateHolder.setActivity(this);
} else {
mStateHolder = new StateHolder();
mStateHolder.setSortMethod(SORT_METHOD_RECENT);
}
ensureUi();
Foursquared foursquared = (Foursquared)getApplication();
if (foursquared.isReady()) {
if (!mStateHolder.getRanOnce()) {
mStateHolder.startTask(this);
}
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver);
if (isFinishing()) {
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
mStateHolder.cancel();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(MENU_GROUP_SEARCH, MENU_REFRESH, Menu.NONE, R.string.refresh)
.setIcon(R.drawable.ic_menu_refresh);
menu.add(Menu.NONE, MENU_SHOUT, Menu.NONE, R.string.shout_action_label)
.setIcon(R.drawable.ic_menu_shout);
SubMenu menuMore = menu.addSubMenu(Menu.NONE, MENU_MORE, Menu.NONE, "More");
menuMore.setIcon(android.R.drawable.ic_menu_more);
for (Map.Entry<Integer, String> it : mMenuMoreSubitems.entrySet()) {
menuMore.add(it.getValue());
}
MenuUtils.addPreferencesToMenu(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
mStateHolder.startTask(this);
return true;
case MENU_SHOUT:
Intent intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class);
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_SHOUT, true);
startActivity(intent);
return true;
case MENU_MORE:
// Submenu items generate id zero, but we check on item title below.
return true;
default:
if (item.getTitle().equals("Map")) {
Checkin[] checkins = (Checkin[])mStateHolder.getCheckins().toArray(
new Checkin[mStateHolder.getCheckins().size()]);
Intent intentMap = new Intent(FriendsActivity.this, FriendsMapActivity.class);
intentMap.putExtra(FriendsMapActivity.EXTRA_CHECKIN_PARCELS, checkins);
startActivity(intentMap);
return true;
} else if (item.getTitle().equals(mMenuMoreSubitems.get(MENU_MORE_LEADERBOARD))) {
startActivity(new Intent(FriendsActivity.this, StatsActivity.class));
return true;
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
@Override
public int getNoSearchResultsStringId() {
return R.string.no_friend_checkins;
}
private void ensureUi() {
SegmentedButton buttons = getHeaderButton();
buttons.clearButtons();
buttons.addButtons(
getString(R.string.friendsactivity_btn_recent),
getString(R.string.friendsactivity_btn_nearby));
if (mStateHolder.getSortMethod() == SORT_METHOD_RECENT) {
buttons.setPushedButtonIndex(0);
} else {
buttons.setPushedButtonIndex(1);
}
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
if (index == 0) {
mStateHolder.setSortMethod(SORT_METHOD_RECENT);
} else {
mStateHolder.setSortMethod(SORT_METHOD_NEARBY);
}
ensureUiListView();
}
});
mMenuMoreSubitems = new LinkedHashMap<Integer, String>();
mMenuMoreSubitems.put(MENU_MORE_MAP, getResources().getString(
R.string.friendsactivity_menu_map));
mMenuMoreSubitems.put(MENU_MORE_LEADERBOARD, getResources().getString(
R.string.friendsactivity_menu_leaderboard));
ensureUiListView();
}
private void ensureUiListView() {
mListAdapter = new SeparatedListAdapter(this);
if (mStateHolder.getSortMethod() == SORT_METHOD_RECENT) {
sortCheckinsRecent(mStateHolder.getCheckins(), mListAdapter);
} else {
sortCheckinsDistance(mStateHolder.getCheckins(), mListAdapter);
}
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setDividerHeight(0);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Checkin checkin = (Checkin) parent.getAdapter().getItem(position);
if (checkin.getUser() != null) {
Intent intent = new Intent(FriendsActivity.this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, checkin.getUser());
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
startActivity(intent);
}
}
});
// Prepare our no-results view. Something odd is going on with the layout parameters though.
// If we don't explicitly set the layout to be fill/fill after inflating, the layout jumps
// to a wrap/wrap layout. Furthermore, sdk 3 crashes with the original layout using two
// buttons in a horizontal LinearLayout.
LayoutInflater inflater = LayoutInflater.from(this);
if (UiUtil.sdkVersion() > 3) {
mLayoutEmpty = (ScrollView)inflater.inflate(
R.layout.friends_activity_empty, null);
Button btnAddFriends = (Button)mLayoutEmpty.findViewById(
R.id.friendsActivityEmptyBtnAddFriends);
btnAddFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FriendsActivity.this, AddFriendsActivity.class);
startActivity(intent);
}
});
Button btnFriendRequests = (Button)mLayoutEmpty.findViewById(
R.id.friendsActivityEmptyBtnFriendRequests);
btnFriendRequests.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FriendsActivity.this, FriendRequestsActivity.class);
startActivity(intent);
}
});
} else {
// Inflation on 1.5 is causing a lot of issues, dropping full layout.
mLayoutEmpty = (ScrollView)inflater.inflate(
R.layout.friends_activity_empty_sdk3, null);
}
mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
if (mListAdapter.getCount() == 0) {
setEmptyView(mLayoutEmpty);
}
if (mStateHolder.getIsRunningTask()) {
setProgressBarIndeterminateVisibility(true);
if (!mStateHolder.getRanOnce()) {
setLoadingView();
}
} else {
setProgressBarIndeterminateVisibility(false);
}
}
private void sortCheckinsRecent(Group<Checkin> checkins, SeparatedListAdapter listAdapter) {
// Sort all by timestamp first.
Collections.sort(checkins, Comparators.getCheckinRecencyComparator());
// We'll group in different section adapters based on some time thresholds.
Group<Checkin> recent = new Group<Checkin>();
Group<Checkin> today = new Group<Checkin>();
Group<Checkin> yesterday = new Group<Checkin>();
Group<Checkin> older = new Group<Checkin>();
Group<Checkin> other = new Group<Checkin>();
CheckinTimestampSort timestamps = new CheckinTimestampSort();
for (Checkin it : checkins) {
// If we can't parse the distance value, it's possible that we
// did not have a geolocation for the device at the time the
// search was run. In this case just assume this friend is nearby
// to sort them in the time buckets.
int meters = 0;
try {
meters = Integer.parseInt(it.getDistance());
} catch (NumberFormatException ex) {
if (DEBUG) Log.d(TAG, "Couldn't parse distance for checkin during friend search.");
meters = 0;
}
if (meters > CITY_RADIUS_IN_METERS) {
other.add(it);
} else {
try {
Date date = new Date(it.getCreated());
if (date.after(timestamps.getBoundaryRecent())) {
recent.add(it);
} else if (date.after(timestamps.getBoundaryToday())) {
today.add(it);
} else if (date.after(timestamps.getBoundaryYesterday())) {
yesterday.add(it);
} else {
older.add(it);
}
} catch (Exception ex) {
older.add(it);
}
}
}
if (recent.size() > 0) {
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(recent);
listAdapter.addSection(getResources().getString(
R.string.friendsactivity_title_sort_recent), adapter);
}
if (today.size() > 0) {
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(today);
listAdapter.addSection(getResources().getString(
R.string.friendsactivity_title_sort_today), adapter);
}
if (yesterday.size() > 0) {
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(yesterday);
listAdapter.addSection(getResources().getString(
R.string.friendsactivity_title_sort_yesterday), adapter);
}
if (older.size() > 0) {
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(older);
listAdapter.addSection(getResources().getString(
R.string.friendsactivity_title_sort_older), adapter);
}
if (other.size() > 0) {
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(other);
listAdapter.addSection(getResources().getString(
R.string.friendsactivity_title_sort_other_city), adapter);
}
}
private void sortCheckinsDistance(Group<Checkin> checkins, SeparatedListAdapter listAdapter) {
Collections.sort(checkins, Comparators.getCheckinDistanceComparator());
Group<Checkin> nearby = new Group<Checkin>();
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
for (Checkin it : checkins) {
int meters = 0;
try {
meters = Integer.parseInt(it.getDistance());
} catch (NumberFormatException ex) {
if (DEBUG) Log.d(TAG, "Couldn't parse distance for checkin during friend search.");
meters = 0;
}
if (meters < CITY_RADIUS_IN_METERS) {
nearby.add(it);
}
}
if (nearby.size() > 0) {
adapter.setGroup(nearby);
listAdapter.addSection(getResources().getString(
R.string.friendsactivity_title_sort_distance), adapter);
}
}
private void onTaskStart() {
setProgressBarIndeterminateVisibility(true);
setLoadingView();
}
private void onTaskComplete(Group<Checkin> checkins, Exception ex) {
mStateHolder.setRanOnce(true);
mStateHolder.setIsRunningTask(false);
setProgressBarIndeterminateVisibility(false);
// Clear list for new batch.
mListAdapter.removeObserver();
mListAdapter.clear();
mListAdapter = new SeparatedListAdapter(this);
// User can sort by default (which is by checkin time), or just by distance.
if (checkins != null) {
mStateHolder.setCheckins(checkins);
if (mStateHolder.getSortMethod() == SORT_METHOD_RECENT) {
sortCheckinsRecent(checkins, mListAdapter);
} else {
sortCheckinsDistance(checkins, mListAdapter);
}
} else if (ex != null) {
mStateHolder.setCheckins(new Group<Checkin>());
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (mStateHolder.getCheckins().size() == 0) {
setEmptyView(mLayoutEmpty);
}
getListView().setAdapter(mListAdapter);
}
private static class TaskCheckins extends AsyncTask<Void, Void, Group<Checkin>> {
private Foursquared mFoursquared;
private FriendsActivity mActivity;
private Exception mException;
public TaskCheckins(FriendsActivity activity) {
mFoursquared = ((Foursquared) activity.getApplication());
mActivity = activity;
}
public void setActivity(FriendsActivity activity) {
mActivity = activity;
}
@Override
public Group<Checkin> doInBackground(Void... params) {
Group<Checkin> checkins = null;
try {
checkins = checkins();
} catch (Exception ex) {
mException = ex;
}
return checkins;
}
@Override
protected void onPreExecute() {
mActivity.onTaskStart();
}
@Override
public void onPostExecute(Group<Checkin> checkins) {
if (mActivity != null) {
mActivity.onTaskComplete(checkins, mException);
}
}
private Group<Checkin> checkins() throws FoursquareException, IOException {
// If we're the startup tab, it's likely that we won't have a geo location
// immediately. For now we can use this ugly method of sleeping for N
// seconds to at least let network location get a lock. We're only trying
// to discern between same-city, so we can even use LocationManager's
// getLastKnownLocation() method because we don't care if we're even a few
// miles off. The api endpoint doesn't require location, so still go ahead
// even if we can't find a location.
Location loc = mFoursquared.getLastKnownLocation();
if (loc == null) {
try { Thread.sleep(SLEEP_TIME_IF_NO_LOCATION); } catch (InterruptedException ex) {}
loc = mFoursquared.getLastKnownLocation();
}
Group<Checkin> checkins = mFoursquared.getFoursquare().checkins(LocationUtils
.createFoursquareLocation(loc));
Collections.sort(checkins, Comparators.getCheckinRecencyComparator());
return checkins;
}
}
private static class StateHolder {
private Group<Checkin> mCheckins;
private int mSortMethod;
private boolean mRanOnce;
private boolean mIsRunningTask;
private TaskCheckins mTaskCheckins;
public StateHolder() {
mRanOnce = false;
mIsRunningTask = false;
mCheckins = new Group<Checkin>();
}
public int getSortMethod() {
return mSortMethod;
}
public void setSortMethod(int sortMethod) {
mSortMethod = sortMethod;
}
public Group<Checkin> getCheckins() {
return mCheckins;
}
public void setCheckins(Group<Checkin> checkins) {
mCheckins = checkins;
}
public boolean getRanOnce() {
return mRanOnce;
}
public void setRanOnce(boolean ranOnce) {
mRanOnce = ranOnce;
}
public boolean getIsRunningTask() {
return mIsRunningTask;
}
public void setIsRunningTask(boolean isRunning) {
mIsRunningTask = isRunning;
}
public void setActivity(FriendsActivity activity) {
if (mIsRunningTask) {
mTaskCheckins.setActivity(activity);
}
}
public void startTask(FriendsActivity activity) {
if (!mIsRunningTask) {
mTaskCheckins = new TaskCheckins(activity);
mTaskCheckins.execute();
mIsRunningTask = true;
}
}
public void cancel() {
if (mIsRunningTask) {
mTaskCheckins.cancel(true);
mIsRunningTask = false;
}
}
}
/**
* This is really just a dummy observer to get the GPS running
* since this is the new splash page. After getting a fix, we
* might want to stop registering this observer thereafter so
* it doesn't annoy the user too much.
*/
private class SearchLocationObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.error.FoursquareException;
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.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* Handles fetching an image from the web, then writes it to a temporary file on
* the sdcard so we can hand it off to a view intent. This activity can be
* styled with a custom transparent-background theme, so that it appears like a
* simple progress dialog to the user over whichever activity launches it,
* instead of two seaparate activities before they finally get to the
* image-viewing activity. The only required intent extra is the URL to download
* the image, the others are optional:
* <ul>
* <li>IMAGE_URL - String, url of the image to download, either jpeg or png.</li>
* <li>CONNECTION_TIMEOUT_IN_SECONDS - int, optional, max timeout wait for
* download, in seconds.</li>
* <li>READ_TIMEOUT_IN_SECONDS - int, optional, max timeout wait for read of
* image, in seconds.</li>
* <li>PROGRESS_BAR_TITLE - String, optional, title of the progress bar during
* download.</li>
* <li>PROGRESS_BAR_MESSAGE - String, optional, message body of the progress bar
* during download.</li>
* </ul>
*
* When the download is complete, the activity will return the path of the
* saved image on disk. The calling activity can then choose to launch an
* intent to view the image.
*
* @date February 25, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class FetchImageForViewIntent extends Activity {
private static final String TAG = "FetchImageForViewIntent";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final String TEMP_FILE_NAME = "tmp_fsq";
public static final String IMAGE_URL = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.IMAGE_URL";
public static final String CONNECTION_TIMEOUT_IN_SECONDS = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.CONNECTION_TIMEOUT_IN_SECONDS";
public static final String READ_TIMEOUT_IN_SECONDS = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.READ_TIMEOUT_IN_SECONDS";
public static final String PROGRESS_BAR_TITLE = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.PROGRESS_BAR_TITLE";
public static final String PROGRESS_BAR_MESSAGE = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.PROGRESS_BAR_MESSAGE";
public static final String LAUNCH_VIEW_INTENT_ON_COMPLETION = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.LAUNCH_VIEW_INTENT_ON_COMPLETION";
public static final String EXTRA_SAVED_IMAGE_PATH_RETURNED = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.EXTRA_SAVED_IMAGE_PATH_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
setContentView(R.layout.fetch_image_for_view_intent_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
String url = null;
if (getIntent().getExtras().containsKey(IMAGE_URL)) {
url = getIntent().getExtras().getString(IMAGE_URL);
} else {
Log.e(TAG, "FetchImageForViewIntent requires intent extras parameter 'IMAGE_URL'.");
finish();
return;
}
if (DEBUG) Log.d(TAG, "Fetching image: " + url);
// Grab the extension of the file that should be present at the end
// of the url. We can do a better job of this, and could even check
// that the extension is of an expected type.
int posdot = url.lastIndexOf(".");
if (posdot < 0) {
Log.e(TAG, "FetchImageForViewIntent requires a url to an image resource with a file extension in its name.");
finish();
return;
}
String progressBarTitle = getIntent().getStringExtra(PROGRESS_BAR_TITLE);
String progressBarMessage = getIntent().getStringExtra(PROGRESS_BAR_MESSAGE);
if (progressBarMessage == null) {
progressBarMessage = "Fetching image...";
}
mStateHolder = new StateHolder();
mStateHolder.setLaunchViewIntentOnCompletion(
getIntent().getBooleanExtra(LAUNCH_VIEW_INTENT_ON_COMPLETION, true));
mStateHolder.startTask(
FetchImageForViewIntent.this,
url,
url.substring(posdot),
progressBarTitle,
progressBarMessage,
getIntent().getIntExtra(CONNECTION_TIMEOUT_IN_SECONDS, 20),
getIntent().getIntExtra(READ_TIMEOUT_IN_SECONDS, 20));
}
}
@Override
public void onResume() {
super.onResume();
if (mStateHolder.getIsRunning()) {
startProgressBar(mStateHolder.getProgressTitle(), mStateHolder.getProgressMessage());
}
}
@Override
public void onPause() {
super.onPause();
stopProgressBar();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void startProgressBar(String title, String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, title, message);
mDlgProgress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dlg) {
mStateHolder.cancel();
finish();
}
});
mDlgProgress.setCancelable(true);
}
mDlgProgress.setTitle(title);
mDlgProgress.setMessage(message);
}
private void stopProgressBar() {
if (mDlgProgress != null && mDlgProgress.isShowing()) {
mDlgProgress.dismiss();
}
mDlgProgress = null;
}
private void onFetchImageTaskComplete(Boolean result, String path, String extension,
Exception ex) {
try {
// If successful, start an intent to view the image.
if (result != null && result.equals(Boolean.TRUE)) {
// If the image can't be loaded or an intent can't be found to
// view it, launchViewIntent() will create a toast with an error
// message.
if (mStateHolder.getLaunchViewIntentOnCompletion()) {
launchViewIntent(path, extension);
} else {
// We'll finish now by handing the save image path back to the
// calling activity.
Intent intent = new Intent();
intent.putExtra(EXTRA_SAVED_IMAGE_PATH_RETURNED, path);
setResult(Activity.RESULT_OK, intent);
}
} else {
NotificationsUtil.ToastReasonForFailure(FetchImageForViewIntent.this, ex);
}
} finally {
// Whether download worked or not, we finish ourselves now. If an
// error occurred, the toast should remain on the calling activity.
mStateHolder.setIsRunning(false);
stopProgressBar();
finish();
}
}
private boolean launchViewIntent(String outputPath, String extension) {
Foursquared foursquared = (Foursquared) getApplication();
if (foursquared.getUseNativeImageViewerForFullScreenImages()) {
// Try to open the file now to create the uri we'll hand to the intent.
Uri uri = null;
try {
File file = new File(outputPath);
uri = Uri.fromFile(file);
} catch (Exception ex) {
Log.e(TAG, "Error opening downloaded image from temp location: ", ex);
Toast.makeText(this, "No application could be found to diplay the full image.",
Toast.LENGTH_SHORT);
return false;
}
// Try to start an intent to view the image. It's possible that the user
// may not have any intents to handle the request.
try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/" + extension);
startActivity(intent);
} catch (Exception ex) {
Log.e(TAG, "Error starting intent to view image: ", ex);
Toast.makeText(this, "There was an error displaying the image.", Toast.LENGTH_SHORT);
return false;
}
} else {
Intent intent = new Intent(this, FullSizeImageActivity.class);
intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_IMAGE_PATH, outputPath);
startActivity(intent);
}
return true;
}
/**
* Handles fetching the image from the net and saving it to disk in a task.
*/
private static class FetchImageTask extends AsyncTask<Void, Void, Boolean> {
private FetchImageForViewIntent mActivity;
private final String mUrl;
private String mExtension;
private final String mOutputPath;
private final int mConnectionTimeoutInSeconds;
private final int mReadTimeoutInSeconds;
private Exception mReason;
public FetchImageTask(FetchImageForViewIntent activity, String url, String extension,
int connectionTimeoutInSeconds, int readTimeoutInSeconds) {
mActivity = activity;
mUrl = url;
mExtension = extension;
mOutputPath = Environment.getExternalStorageDirectory() + "/" + TEMP_FILE_NAME;
mConnectionTimeoutInSeconds = connectionTimeoutInSeconds;
mReadTimeoutInSeconds = readTimeoutInSeconds;
}
public void setActivity(FetchImageForViewIntent activity) {
mActivity = activity;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
saveImage(mUrl, mOutputPath, mConnectionTimeoutInSeconds, mReadTimeoutInSeconds);
return Boolean.TRUE;
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "FetchImageTask: Exception while fetching image.", e);
mReason = e;
}
return Boolean.FALSE;
}
@Override
protected void onPostExecute(Boolean result) {
if (DEBUG) Log.d(TAG, "FetchImageTask: onPostExecute()");
if (mActivity != null) {
mActivity.onFetchImageTaskComplete(result, mOutputPath, mExtension, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onFetchImageTaskComplete(null, null, null,
new FoursquareException("Image download cancelled."));
}
}
}
public static void saveImage(String urlImage, String savePath, int connectionTimeoutInSeconds,
int readTimeoutInSeconds) throws Exception {
URL url = new URL(urlImage);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(connectionTimeoutInSeconds * 1000);
conn.setReadTimeout(readTimeoutInSeconds * 1000);
int contentLength = conn.getContentLength();
InputStream raw = conn.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1) {
break;
}
offset += bytesRead;
}
in.close();
if (offset != contentLength) {
Log.e(TAG, "Error fetching image, only read " + offset + " bytes of " + contentLength
+ " total.");
throw new FoursquareException("Error fetching full image, please try again.");
}
// This will fail if the user has no sdcard present, catch it specifically
// to alert user.
try {
FileOutputStream out = new FileOutputStream(savePath);
out.write(data);
out.flush();
out.close();
} catch (Exception ex) {
Log.e(TAG, "Error saving fetched image to disk.", ex);
throw new FoursquareException("Error opening fetched image, make sure an sdcard is present.");
}
}
/** Maintains state between rotations. */
private static class StateHolder {
FetchImageTask mTaskFetchImage;
boolean mIsRunning;
String mProgressTitle;
String mProgressMessage;
boolean mLaunchViewIntentOnCompletion;
public StateHolder() {
mIsRunning = false;
mLaunchViewIntentOnCompletion = true;
}
public void startTask(FetchImageForViewIntent activity, String url, String extension,
String progressBarTitle, String progressBarMessage, int connectionTimeoutInSeconds,
int readTimeoutInSeconds) {
mIsRunning = true;
mProgressTitle = progressBarTitle;
mProgressMessage = progressBarMessage;
mTaskFetchImage = new FetchImageTask(activity, url, extension,
connectionTimeoutInSeconds, readTimeoutInSeconds);
mTaskFetchImage.execute();
}
public void setActivity(FetchImageForViewIntent activity) {
if (mTaskFetchImage != null) {
mTaskFetchImage.setActivity(activity);
}
}
public void setIsRunning(boolean isRunning) {
mIsRunning = isRunning;
}
public boolean getIsRunning() {
return mIsRunning;
}
public String getProgressTitle() {
return mProgressTitle;
}
public String getProgressMessage() {
return mProgressMessage;
}
public void cancel() {
if (mTaskFetchImage != null) {
mTaskFetchImage.cancel(true);
mIsRunning = false;
}
}
public boolean getLaunchViewIntentOnCompletion() {
return mLaunchViewIntentOnCompletion;
}
public void setLaunchViewIntentOnCompletion(boolean launchViewIntentOnCompletion) {
mLaunchViewIntentOnCompletion = launchViewIntentOnCompletion;
}
}
}
| Java |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.joelapenna.foursquared.preferences;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Parcelable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
/**
* This is an example of a custom preference type. The preference counts the number of clicks it has
* received and stores/retrieves it from the storage.
*/
public class ClickPreference extends Preference {
// This is the constructor called by the inflater
public ClickPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
}
@Override
protected void onClick() {
// Data has changed, notify so UI can be refreshed!
notifyChanged();
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
// This preference type's value type is Integer, so we read the default
// value from the attributes as an Integer.
return a.getInteger(index, 0);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
super.onRestoreInstanceState(state);
notifyChanged();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.preferences;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.City;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.UserUtils;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.util.Log;
import java.io.IOException;
import java.util.UUID;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Preferences {
private static final String TAG = "Preferences";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
// Visible Preferences (sync with preferences.xml)
public static final String PREFERENCE_SHARE_CHECKIN = "share_checkin";
public static final String PREFERENCE_IMMEDIATE_CHECKIN = "immediate_checkin";
public static final String PREFERENCE_STARTUP_TAB = "startup_tab";
// Hacks for preference activity extra UI elements.
public static final String PREFERENCE_ADVANCED_SETTINGS = "advanced_settings";
public static final String PREFERENCE_TWITTER_CHECKIN = "twitter_checkin";
public static final String PREFERENCE_FACEBOOK_CHECKIN = "facebook_checkin";
public static final String PREFERENCE_TWITTER_HANDLE = "twitter_handle";
public static final String PREFERENCE_FACEBOOK_HANDLE = "facebook_handle";
public static final String PREFERENCE_FRIEND_REQUESTS = "friend_requests";
public static final String PREFERENCE_FRIEND_ADD = "friend_add";
public static final String PREFERENCE_CHANGELOG = "changelog";
public static final String PREFERENCE_CITY_NAME = "city_name";
public static final String PREFERENCE_LOGOUT = "logout";
public static final String PREFERENCE_HELP = "help";
public static final String PREFERENCE_SEND_FEEDBACK = "send_feedback";
public static final String PREFERENCE_PINGS = "pings_on";
public static final String PREFERENCE_PINGS_INTERVAL = "pings_refresh_interval_in_minutes";
public static final String PREFERENCE_PINGS_VIBRATE = "pings_vibrate";
public static final String PREFERENCE_TOS_PRIVACY = "tos_privacy";
public static final String PREFERENCE_PROFILE_SETTINGS = "profile_settings";
// Credentials related preferences
public static final String PREFERENCE_LOGIN = "phone";
public static final String PREFERENCE_PASSWORD = "password";
// Extra info for getUserCity
private static final String PREFERENCE_CITY_ID = "city_id";
private static final String PREFERENCE_CITY_GEOLAT = "city_geolat";
private static final String PREFERENCE_CITY_GEOLONG = "city_geolong";
private static final String PREFERENCE_CITY_SHORTNAME = "city_shortname";
// Extra info for getUserId
private static final String PREFERENCE_ID = "id";
// Extra for storing user's supplied email address.
private static final String PREFERENCE_USER_EMAIL = "user_email";
// Extra for storing user's supplied first and last name.
private static final String PREFERENCE_USER_NAME = "user_name";
// Extra info about the user, their gender, to control icon used for 'me' in the UI.
private static final String PREFERENCE_GENDER = "gender";
// Extra info, can the user have followers or not.
public static final String PREFERENCE_CAN_HAVE_FOLLOWERS = "can_have_followers";
// Not-in-XML preferences for dumpcatcher
public static final String PREFERENCE_DUMPCATCHER_CLIENT = "dumpcatcher_client";
// Keeps track of the last changelog version shown to the user at startup.
private static final String PREFERENCE_LAST_SEEN_CHANGELOG_VERSION
= "last_seen_changelog_version";
// User can choose to clear geolocation on each search.
public static final String PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES
= "cache_geolocation_for_searches";
// If we're compiled to show the prelaunch activity, flag stating whether to skip
// showing it on startup.
public static final String PREFERENCE_SHOW_PRELAUNCH_ACTIVITY = "show_prelaunch_activity";
// Last time pings service ran.
public static final String PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME = "pings_service_last_run_time";
// Broadcast an intent to show single full-screen images, or use our own poor image viewer.
public static final String PREFERENCE_NATIVE_IMAGE_VIEWER
= "native_full_size_image_viewer";
/**
* Gives us a chance to set some default preferences if this is the first install
* of the application.
*/
public static void setupDefaults(SharedPreferences preferences, Resources resources) {
Editor editor = preferences.edit();
if (!preferences.contains(PREFERENCE_STARTUP_TAB)) {
String[] startupTabValues = resources.getStringArray(R.array.startup_tabs_values);
editor.putString(PREFERENCE_STARTUP_TAB, startupTabValues[0]);
}
if (!preferences.contains(PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES)) {
editor.putBoolean(PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES, false);
}
if (!preferences.contains(PREFERENCE_SHOW_PRELAUNCH_ACTIVITY)) {
editor.putBoolean(PREFERENCE_SHOW_PRELAUNCH_ACTIVITY, true);
}
if (!preferences.contains(PREFERENCE_PINGS_INTERVAL)) {
editor.putString(PREFERENCE_PINGS_INTERVAL, "30");
}
if (!preferences.contains(PREFERENCE_NATIVE_IMAGE_VIEWER)) {
editor.putBoolean(PREFERENCE_NATIVE_IMAGE_VIEWER, true);
}
editor.commit();
}
public static String createUniqueId(SharedPreferences preferences) {
String uniqueId = preferences.getString(PREFERENCE_DUMPCATCHER_CLIENT, null);
if (uniqueId == null) {
uniqueId = UUID.randomUUID().toString();
Editor editor = preferences.edit();
editor.putString(PREFERENCE_DUMPCATCHER_CLIENT, uniqueId);
editor.commit();
}
return uniqueId;
}
public static boolean loginUser(Foursquare foursquare, String login, String password,
Foursquare.Location location, Editor editor) throws FoursquareCredentialsException,
FoursquareException, IOException {
if (DEBUG) Log.d(Preferences.TAG, "Trying to log in.");
foursquare.setCredentials(login, password);
storeLoginAndPassword(editor, login, password);
if (!editor.commit()) {
if (DEBUG) Log.d(TAG, "storeLoginAndPassword commit failed");
return false;
}
User user = foursquare.user(null, false, false, false, location);
storeUser(editor, user);
if (!editor.commit()) {
if (DEBUG) Log.d(TAG, "storeUser commit failed");
return false;
}
return true;
}
public static boolean logoutUser(Foursquare foursquare, Editor editor) {
if (DEBUG) Log.d(Preferences.TAG, "Trying to log out.");
// TODO: If we re-implement oAuth, we'll have to call clearAllCrendentials here.
foursquare.setCredentials(null, null);
return editor.clear().commit();
}
public static City getUserCity(SharedPreferences prefs) {
City city = new City();
city.setId(prefs.getString(Preferences.PREFERENCE_CITY_ID, null));
city.setName(prefs.getString(Preferences.PREFERENCE_CITY_NAME, null));
city.setShortname(prefs.getString(Preferences.PREFERENCE_CITY_SHORTNAME, null));
city.setGeolat(prefs.getString(Preferences.PREFERENCE_CITY_GEOLAT, null));
city.setGeolong(prefs.getString(Preferences.PREFERENCE_CITY_GEOLONG, null));
return city;
}
public static String getUserId(SharedPreferences prefs) {
return prefs.getString(PREFERENCE_ID, null);
}
public static String getUserName(SharedPreferences prefs) {
return prefs.getString(PREFERENCE_USER_NAME, null);
}
public static String getUserEmail(SharedPreferences prefs) {
return prefs.getString(PREFERENCE_USER_EMAIL, null);
}
public static String getUserGender(SharedPreferences prefs) {
return prefs.getString(PREFERENCE_GENDER, null);
}
public static String getLastSeenChangelogVersion(SharedPreferences prefs) {
return prefs.getString(PREFERENCE_LAST_SEEN_CHANGELOG_VERSION, null);
}
public static void storeCity(final Editor editor, City city) {
if (city != null) {
editor.putString(PREFERENCE_CITY_ID, city.getId());
editor.putString(PREFERENCE_CITY_GEOLAT, city.getGeolat());
editor.putString(PREFERENCE_CITY_GEOLONG, city.getGeolong());
editor.putString(PREFERENCE_CITY_NAME, city.getName());
editor.putString(PREFERENCE_CITY_SHORTNAME, city.getShortname());
}
}
public static void storeLoginAndPassword(final Editor editor, String login, String password) {
editor.putString(PREFERENCE_LOGIN, login);
editor.putString(PREFERENCE_PASSWORD, password);
}
public static void storeUser(final Editor editor, User user) {
if (user != null && user.getId() != null) {
editor.putString(PREFERENCE_ID, user.getId());
editor.putString(PREFERENCE_USER_NAME, StringFormatters.getUserFullName(user));
editor.putString(PREFERENCE_USER_EMAIL, user.getEmail());
editor.putBoolean(PREFERENCE_TWITTER_CHECKIN, user.getSettings().sendtotwitter());
editor.putBoolean(PREFERENCE_FACEBOOK_CHECKIN, user.getSettings().sendtofacebook());
editor.putString(PREFERENCE_TWITTER_HANDLE, user.getTwitter() != null ? user.getTwitter() : "");
editor.putString(PREFERENCE_FACEBOOK_HANDLE, user.getFacebook() != null ? user.getFacebook() : "");
editor.putString(PREFERENCE_GENDER, user.getGender());
editor.putBoolean(PREFERENCE_CAN_HAVE_FOLLOWERS, UserUtils.getCanHaveFollowers(user));
if (DEBUG) Log.d(TAG, "Setting user info");
} else {
if (Preferences.DEBUG) Log.d(Preferences.TAG, "Unable to lookup user.");
}
}
public static void storeLastSeenChangelogVersion(final Editor editor, String version) {
editor.putString(PREFERENCE_LAST_SEEN_CHANGELOG_VERSION, version);
if (!editor.commit()) {
Log.e(TAG, "storeLastSeenChangelogVersion commit failed");
}
}
public static boolean getUseNativeImageViewerForFullScreenImages(SharedPreferences prefs) {
return prefs.getBoolean(PREFERENCE_NATIVE_IMAGE_VIEWER, true);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.StringFormatters;
/**
* Lets the user add a todo for a venue.
*
* @date September 16, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class AddTodoActivity extends Activity {
private static final String TAG = "AddTodoActivity";
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".AddTodoActivity.INTENT_EXTRA_VENUE";
public static final String EXTRA_TODO_RETURNED = Foursquared.PACKAGE_NAME
+ ".AddTodoActivity.EXTRA_TODO_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo_activity);
StateHolder holder = (StateHolder) getLastNonConfigurationInstance();
if (holder != null) {
mStateHolder = holder;
mStateHolder.setActivityForTasks(this);
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE));
} else {
Log.e(TAG, "AddTodoActivity must be given a venue parcel as intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTasks(null);
return mStateHolder;
}
private void ensureUi() {
TextView tvVenueName = (TextView)findViewById(R.id.addTodoActivityVenueName);
tvVenueName.setText(mStateHolder.getVenue().getName());
TextView tvVenueAddress = (TextView)findViewById(R.id.addTodoActivityVenueAddress);
tvVenueAddress.setText(StringFormatters.getVenueLocationCrossStreetOrCity(
mStateHolder.getVenue()));
Button btn = (Button) findViewById(R.id.addTodoActivityButton);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.addTodoActivityText);
String text = et.getText().toString();
mStateHolder.startTaskAddTodo(AddTodoActivity.this, mStateHolder.getVenue().getId(), text);
}
});
if (mStateHolder.getIsRunningTaskVenue()) {
startProgressBar();
}
}
private void startProgressBar() {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, "",
getResources().getString(R.string.add_tip_todo_activity_progress_message));
mDlgProgress.setCancelable(true);
mDlgProgress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Log.e(TAG, "User cancelled add todo.");
mStateHolder.cancelTasks();
}
});
}
mDlgProgress.show();
setProgressBarIndeterminateVisibility(true);
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
setProgressBarIndeterminateVisibility(false);
}
private static class TaskAddTodo extends AsyncTask<Void, Void, Todo> {
private AddTodoActivity mActivity;
private String mVenueId;
private String mTipText;
private Exception mReason;
public TaskAddTodo(AddTodoActivity activity, String venueId, String tipText) {
mActivity = activity;
mVenueId = venueId;
mTipText = tipText;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected Todo doInBackground(Void... params) {
try {
// If the user entered optional text, we need to use one endpoint,
// if not, we need to use mark/todo.
Foursquared foursquared = (Foursquared)mActivity.getApplication();
Todo todo = null;
if (!TextUtils.isEmpty(mTipText)) {
// The returned tip won't have the user object or venue attached to it
// as part of the response. The venue is the parent venue and the user
// is the logged-in user.
Tip tip = foursquared.getFoursquare().addTip(
mVenueId, mTipText, "todo",
LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
// So fetch the full tip for convenience.
Tip tipFull = foursquared.getFoursquare().tipDetail(tip.getId());
// The addtip API returns a tip instead of a todo, unlike the mark/todo endpoint,
// so we create a dummy todo object for now to wrap the tip.
String now = StringFormatters.createServerDateFormatV1();
todo = new Todo();
todo.setId("id_" + now);
todo.setCreated(now);
todo.setTip(tipFull);
Log.i(TAG, "Added todo with wrapper ID: " + todo.getId());
} else {
// No text, so in this case we need to mark the venue itself as a todo.
todo = foursquared.getFoursquare().markTodoVenue(mVenueId);
Log.i(TAG, "Added todo with ID: " + todo.getId());
}
return todo;
} catch (Exception e) {
Log.e(TAG, "Error adding tip.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Todo todo) {
mActivity.stopProgressBar();
mActivity.mStateHolder.setIsRunningTaskAddTip(false);
if (todo != null) {
Intent intent = new Intent();
intent.putExtra(EXTRA_TODO_RETURNED, todo);
mActivity.setResult(Activity.RESULT_OK, intent);
mActivity.finish();
} else {
NotificationsUtil.ToastReasonForFailure(mActivity, mReason);
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
}
@Override
protected void onCancelled() {
mActivity.stopProgressBar();
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
public void setActivity(AddTodoActivity activity) {
mActivity = activity;
}
}
private static final class StateHolder {
private Venue mVenue;
private TaskAddTodo mTaskAddTodo;
private boolean mIsRunningTaskAddTip;
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
}
public boolean getIsRunningTaskVenue() {
return mIsRunningTaskAddTip;
}
public void setIsRunningTaskAddTip(boolean isRunningTaskAddTip) {
mIsRunningTaskAddTip = isRunningTaskAddTip;
}
public void startTaskAddTodo(AddTodoActivity activity, String venueId, String text) {
mIsRunningTaskAddTip = true;
mTaskAddTodo = new TaskAddTodo(activity, venueId, text);
mTaskAddTodo.execute();
}
public void setActivityForTasks(AddTodoActivity activity) {
if (mTaskAddTodo != null) {
mTaskAddTodo.setActivity(activity);
}
}
public void cancelTasks() {
if (mTaskAddTodo != null) {
mTaskAddTodo.cancel(true);
}
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.http.AbstractHttpApi;
import com.joelapenna.foursquared.util.NotificationsUtil;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import java.io.IOException;
/**
* Displays a special in a webview. Ideally we could use WebView.setHttpAuthUsernamePassword(),
* but it is unfortunately not working. Instead we download the html content manually, then
* feed it to our webview. Not ideal and we should update this in the future.
*
* @date April 4, 2010.
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*
*/
public class SpecialWebViewActivity extends Activity
{
private static final String TAG = "WebViewActivity";
public static final String EXTRA_CREDENTIALS_USERNAME = Foursquared.PACKAGE_NAME
+ ".SpecialWebViewActivity.EXTRA_CREDENTIALS_USERNAME";
public static final String EXTRA_CREDENTIALS_PASSWORD = Foursquared.PACKAGE_NAME
+ ".SpecialWebViewActivity.EXTRA_CREDENTIALS_PASSWORD";
public static final String EXTRA_SPECIAL_ID = Foursquared.PACKAGE_NAME
+ ".SpecialWebViewActivity.EXTRA_SPECIAL_ID";
private WebView mWebView;
private StateHolder mStateHolder;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.special_webview_activity);
mWebView = (WebView)findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivityForTask(this);
if (mStateHolder.getIsRunningTask() == false) {
mWebView.loadDataWithBaseURL("--", mStateHolder.getHtml(), "text/html", "utf-8", "");
}
} else {
mStateHolder = new StateHolder();
if (getIntent().getExtras() != null &&
getIntent().getExtras().containsKey(EXTRA_CREDENTIALS_USERNAME) &&
getIntent().getExtras().containsKey(EXTRA_CREDENTIALS_PASSWORD) &&
getIntent().getExtras().containsKey(EXTRA_SPECIAL_ID))
{
String username = getIntent().getExtras().getString(EXTRA_CREDENTIALS_USERNAME);
String password = getIntent().getExtras().getString(EXTRA_CREDENTIALS_PASSWORD);
String specialid = getIntent().getExtras().getString(EXTRA_SPECIAL_ID);
mStateHolder.startTask(this, username, password, specialid);
} else {
Log.e(TAG, TAG + " intent missing required extras parameters.");
finish();
}
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTask(null);
return mStateHolder;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void onTaskComplete(String html, Exception ex) {
mStateHolder.setIsRunningTask(false);
if (html != null) {
mStateHolder.setHtml(html);
mWebView.loadDataWithBaseURL("--", mStateHolder.getHtml(), "text/html", "utf-8", "");
} else {
NotificationsUtil.ToastReasonForFailure(this, ex);
}
}
private static class SpecialTask extends AsyncTask<String, Void, String> {
private SpecialWebViewActivity mActivity;
private Exception mReason;
public SpecialTask(SpecialWebViewActivity activity) {
mActivity = activity;
}
public void setActivity(SpecialWebViewActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
String html = null;
try {
String username = params[0];
String password = params[1];
String specialid = params[2];
StringBuilder sbUrl = new StringBuilder(128);
sbUrl.append("https://api.foursquare.com/iphone/special?sid=");
sbUrl.append(specialid);
AuthScope authScope = new AuthScope("api.foursquare.com", 80);
DefaultHttpClient httpClient = AbstractHttpApi.createHttpClient();
httpClient.getCredentialsProvider().setCredentials(authScope,
new UsernamePasswordCredentials(username, password));
httpClient.addRequestInterceptor(preemptiveAuth, 0);
HttpGet httpGet = new HttpGet(sbUrl.toString());
try {
HttpResponse response = httpClient.execute(httpGet);
String responseText = EntityUtils.toString(response.getEntity());
html = responseText.replace("('/img", "('http://www.foursquare.com/img");
} catch (Exception e) {
mReason = e;
}
} catch (Exception e) {
mReason = e;
}
return html;
}
@Override
protected void onPostExecute(String html) {
if (mActivity != null) {
mActivity.onTaskComplete(html, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskComplete(null, new Exception("Special task cancelled."));
}
}
private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider)context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
// If not auth scheme has been initialized yet
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
}
private static class StateHolder {
private String mHtml;
private boolean mIsRunningTask;
private SpecialTask mTask;
public StateHolder() {
mIsRunningTask = false;
}
public void setHtml(String html) {
mHtml = html;
}
public String getHtml() {
return mHtml;
}
public void startTask(SpecialWebViewActivity activity,
String username,
String password,
String specialid)
{
mIsRunningTask = true;
mTask = new SpecialTask(activity);
mTask.execute(username, password, specialid);
}
public void setActivityForTask(SpecialWebViewActivity activity) {
if (mTask != null) {
mTask.setActivity(activity);
}
}
public void setIsRunningTask(boolean isRunningTipTask) {
mIsRunningTask = isRunningTipTask;
}
public boolean getIsRunningTask() {
return mIsRunningTask;
}
}
}
| Java |
// Copyright 2003-2009 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
// www.source-code.biz, www.inventec.ch/chdh
//
// This module is multi-licensed and may be used under the terms
// of any of the following licenses:
//
// EPL, Eclipse Public License, http://www.eclipse.org/legal
// LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html
// AL, Apache License, http://www.apache.org/licenses
// BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php
//
// Please contact the author if you need another license.
// This module is provided "as is", without warranties of any kind.
package com.joelapenna.foursquared.util;
/**
* A Base64 Encoder/Decoder.
* <p>
* This class is used to encode and decode data in Base64 format as described in
* RFC 1521.
* <p>
* Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br>
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
* Multi-licensed: EPL/LGPL/AL/BSD.
* <p>
* Version history:<br>
* 2003-07-22 Christian d'Heureuse (chdh): Module created.<br>
* 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br>
* 2006-11-21 chdh:<br>
* Method encode(String) renamed to encodeString(String).<br>
* Method decode(String) renamed to decodeString(String).<br>
* New method encode(byte[],int) added.<br>
* New method decode(String) added.<br>
* 2009-07-16: Additional licenses (EPL/AL) added.<br>
* 2009-09-16: Additional license (BSD) added.<br>
*/
public class Base64Coder {
// Mapping table from 6-bit nibbles to Base64 characters.
private static char[] map1 = new char[64];
static {
int i = 0;
for (char c = 'A'; c <= 'Z'; c++)
map1[i++] = c;
for (char c = 'a'; c <= 'z'; c++)
map1[i++] = c;
for (char c = '0'; c <= '9'; c++)
map1[i++] = c;
map1[i++] = '+';
map1[i++] = '/';
}
// Mapping table from Base64 characters to 6-bit nibbles.
private static byte[] map2 = new byte[128];
static {
for (int i = 0; i < map2.length; i++)
map2[i] = -1;
for (int i = 0; i < 64; i++)
map2[map1[i]] = (byte) i;
}
/**
* Encodes a string into Base64 format. No blanks or line breaks are
* inserted.
*
* @param s a String to be encoded.
* @return A String with the Base64 encoded data.
*/
public static String encodeString(String s) {
return new String(encode(s.getBytes()));
}
/**
* Encodes a byte array into Base64 format. No blanks or line breaks are
* inserted.
*
* @param in an array containing the data bytes to be encoded.
* @return A character array with the Base64 encoded data.
*/
public static char[] encode(byte[] in) {
return encode(in, in.length);
}
/**
* Encodes a byte array into Base64 format. No blanks or line breaks are
* inserted.
*
* @param in an array containing the data bytes to be encoded.
* @param iLen number of bytes to process in <code>in</code>.
* @return A character array with the Base64 encoded data.
*/
public static char[] encode(byte[] in, int iLen) {
int oDataLen = (iLen * 4 + 2) / 3; // output length without padding
int oLen = ((iLen + 2) / 3) * 4; // output length including padding
char[] out = new char[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iLen ? in[ip++] & 0xff : 0;
int i2 = ip < iLen ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : '=';
op++;
out[op] = op < oDataLen ? map1[o3] : '=';
op++;
}
return out;
}
/**
* Decodes a string from Base64 format.
*
* @param s a Base64 String to be decoded.
* @return A String containing the decoded data.
* @throws IllegalArgumentException if the input is not valid Base64 encoded
* data.
*/
public static String decodeString(String s) {
return new String(decode(s));
}
/**
* Decodes a byte array from Base64 format.
*
* @param s a Base64 String to be decoded.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException if the input is not valid Base64 encoded
* data.
*/
public static byte[] decode(String s) {
return decode(s.toCharArray());
}
/**
* Decodes a byte array from Base64 format. No blanks or line breaks are
* allowed within the Base64 encoded data.
*
* @param in a character array containing the Base64 encoded data.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException if the input is not valid Base64 encoded
* data.
*/
public static byte[] decode(char[] in) {
int iLen = in.length;
if (iLen % 4 != 0)
throw new IllegalArgumentException(
"Length of Base64 encoded input string is not a multiple of 4.");
while (iLen > 0 && in[iLen - 1] == '=')
iLen--;
int oLen = (iLen * 3) / 4;
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++];
int i1 = in[ip++];
int i2 = ip < iLen ? in[ip++] : 'A';
int i3 = ip < iLen ? in[ip++] : 'A';
if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
throw new IllegalArgumentException("Illegal character in Base64 encoded data.");
int b0 = map2[i0];
int b1 = map2[i1];
int b2 = map2[i2];
int b3 = map2[i3];
if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
throw new IllegalArgumentException("Illegal character in Base64 encoded data.");
int o0 = (b0 << 2) | (b1 >>> 4);
int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2);
int o2 = ((b2 & 3) << 6) | b3;
out[op++] = (byte) o0;
if (op < oLen) out[op++] = (byte) o1;
if (op < oLen) out[op++] = (byte) o2;
}
return out;
}
// Dummy constructor.
private Base64Coder() {
}
} // end class Base64Coder
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
/**
* Acts as an interface to the TabSpec class for setting the content view.
* The level 3 SDK doesn't support setting a View for the content sections
* of the tab, so we can only use the big native tab style. The level 4
* SDK and up support specifying a custom view for the tab.
*
* @date March 9, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class TabsUtil4 {
private TabsUtil4() {
}
public static void setTabIndicator(TabSpec spec, View view) {
spec.setIndicator(view);
}
public static int getTabCount(TabHost tabHost) {
return tabHost.getTabWidget().getTabCount();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.FoursquaredSettings;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.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.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 android.net.Uri;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Observable;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.GZIPInputStream;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
class RemoteResourceFetcher extends Observable {
public static final String TAG = "RemoteResourceFetcher";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private DiskCache mResourceCache;
private ExecutorService mExecutor;
private HttpClient mHttpClient;
private ConcurrentHashMap<Request, Callable<Request>> mActiveRequestsMap = new ConcurrentHashMap<Request, Callable<Request>>();
public RemoteResourceFetcher(DiskCache cache) {
mResourceCache = cache;
mHttpClient = createHttpClient();
mExecutor = Executors.newCachedThreadPool();
}
@Override
public void notifyObservers(Object data) {
setChanged();
super.notifyObservers(data);
}
public Future<Request> fetch(Uri uri, String hash) {
Request request = new Request(uri, hash);
synchronized (mActiveRequestsMap) {
Callable<Request> fetcher = newRequestCall(request);
if (mActiveRequestsMap.putIfAbsent(request, fetcher) == null) {
if (DEBUG) Log.d(TAG, "issuing new request for: " + uri);
return mExecutor.submit(fetcher);
} else {
if (DEBUG) Log.d(TAG, "Already have a pending request for: " + uri);
}
}
return null;
}
public void shutdown() {
mExecutor.shutdownNow();
}
private Callable<Request> newRequestCall(final Request request) {
return new Callable<Request>() {
public Request call() {
try {
if (DEBUG) Log.d(TAG, "Requesting: " + request.uri);
HttpGet httpGet = new HttpGet(request.uri.toString());
httpGet.addHeader("Accept-Encoding", "gzip");
HttpResponse response = mHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream is = getUngzippedContent(entity);
mResourceCache.store(request.hash, is);
if (DEBUG) Log.d(TAG, "Request successful: " + request.uri);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "IOException", e);
} finally {
if (DEBUG) Log.d(TAG, "Request finished: " + request.uri);
mActiveRequestsMap.remove(request);
notifyObservers(request.uri);
}
return request;
}
};
}
/**
* Gets the input stream from a response entity. If the entity is gzipped then this will get a
* stream over the uncompressed data.
*
* @param entity the entity whose content should be read
* @return the input stream to read from
* @throws IOException
*/
public static InputStream getUngzippedContent(HttpEntity entity) throws IOException {
InputStream responseStream = entity.getContent();
if (responseStream == null) {
return responseStream;
}
Header header = entity.getContentEncoding();
if (header == null) {
return responseStream;
}
String contentEncoding = header.getValue();
if (contentEncoding == null) {
return responseStream;
}
if (contentEncoding.contains("gzip")) {
responseStream = new GZIPInputStream(responseStream);
}
return responseStream;
}
/**
* 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() {
// Shamelessly cribbed from AndroidHttpClient
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);
// Default connection and socket timeout of 10 seconds. Tweak to taste.
HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
HttpConnectionParams.setSoTimeout(params, 10 * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192);
// 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));
final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,
supportedSchemes);
return new DefaultHttpClient(ccm, params);
}
private static class Request {
Uri uri;
String hash;
public Request(Uri requestUri, String requestHash) {
uri = requestUri;
hash = requestHash;
}
@Override
public int hashCode() {
return hash.hashCode();
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.googlecode.dumpcatcher.logging.Dumpcatcher;
import com.googlecode.dumpcatcher.logging.DumpcatcherUncaughtExceptionHandler;
import com.googlecode.dumpcatcher.logging.StackFormattingUtil;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.R;
import org.apache.http.HttpResponse;
import android.content.res.Resources;
import android.util.Log;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class DumpcatcherHelper {
private static final String TAG = "DumpcatcherHelper";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final ExecutorService mExecutor = Executors.newFixedThreadPool(2);
private static Dumpcatcher sDumpcatcher;
private static String sClient;
public DumpcatcherHelper(String client, Resources resources) {
sClient = client;
setupDumpcatcher(resources);
}
public static void setupDumpcatcher(Resources resources) {
if (FoursquaredSettings.DUMPCATCHER_TEST) {
if (FoursquaredSettings.DEBUG)
Log.d(TAG, "Loading Dumpcatcher TEST");
sDumpcatcher = new Dumpcatcher( //
resources.getString(R.string.test_dumpcatcher_product_key), //
resources.getString(R.string.test_dumpcatcher_secret), //
resources.getString(R.string.test_dumpcatcher_url), sClient, 5);
} else {
if (FoursquaredSettings.DEBUG)
Log.d(TAG, "Loading Dumpcatcher Live");
sDumpcatcher = new Dumpcatcher( //
resources.getString(R.string.dumpcatcher_product_key), //
resources.getString(R.string.dumpcatcher_secret), //
resources.getString(R.string.dumpcatcher_url), sClient, 5);
}
UncaughtExceptionHandler handler = new DefaultUnhandledExceptionHandler(sDumpcatcher);
// This can hang the app starving android of its ability to properly
// kill threads... maybe.
Thread.setDefaultUncaughtExceptionHandler(handler);
Thread.currentThread().setUncaughtExceptionHandler(handler);
}
public static void sendCrash(final String shortMessage, final String longMessage,
final String level, final String tag) {
mExecutor.execute(new Runnable() {
@Override
public void run() {
try {
HttpResponse response = sDumpcatcher.sendCrash(shortMessage, longMessage,
level, "usage");
response.getEntity().consumeContent();
} catch (Exception e) {
if (DEBUG)
Log.d(TAG, "Unable to sendCrash");
}
}
});
}
public static void sendException(Throwable e) {
sendCrash(//
StackFormattingUtil.getStackMessageString(e), //
StackFormattingUtil.getStackTraceString(e), //
String.valueOf(Level.INFO.intValue()), //
"exception");
}
public static void sendUsage(final String usage) {
sendCrash(usage, null, null, "usage");
}
private static final class DefaultUnhandledExceptionHandler extends
DumpcatcherUncaughtExceptionHandler {
private static final UncaughtExceptionHandler mOriginalExceptionHandler = Thread
.getDefaultUncaughtExceptionHandler();
DefaultUnhandledExceptionHandler(Dumpcatcher dumpcatcher) {
super(dumpcatcher);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
super.uncaughtException(t, e);
mOriginalExceptionHandler.uncaughtException(t, e);
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.app.Activity;
import android.database.Cursor;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
/**
* Implementation of address book functions for sdk level 5 and above.
*
* @date February 14, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class AddressBookUtils5 extends AddressBookUtils {
public AddressBookUtils5() {
}
@Override
public String getAllContactsPhoneNumbers(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] { Contacts._ID, Phone.NUMBER };
Cursor c = activity.managedQuery(Phone.CONTENT_URI, PROJECTION, null, null, null);
if (c.moveToFirst()) {
sb.append(c.getString(1));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(1));
}
}
return sb.toString();
}
@Override
public String getAllContactsEmailAddresses(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] { Email.DATA };
Cursor c = activity.managedQuery(Email.CONTENT_URI, PROJECTION, null, null, null);
if (c.moveToFirst()) {
sb.append(c.getString(0));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(0));
}
}
return sb.toString();
}
@Override
public AddressBookEmailBuilder getAllContactsEmailAddressesInfo(Activity activity) {
String[] PROJECTION = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, Email.DATA };
Cursor c = activity.managedQuery(Email.CONTENT_URI, PROJECTION, null, null, null);
// We give a list of emails: markww@gmail.com,johndoe@gmail.com,janedoe@gmail.com
// We get back only a list of emails of users that exist on the system (johndoe@gmail.com)
// Iterate over all those returned users, on each iteration, remove from our hashmap.
// Can now use the left over hashmap, which is still in correct order to display invites.
AddressBookEmailBuilder bld = new AddressBookEmailBuilder();
if (c.moveToFirst()) {
bld.addContact(c.getString(1), c.getString(2));
while (c.moveToNext()) {
bld.addContact(c.getString(1), c.getString(2));
}
}
c.close();
return bld;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public interface DiskCache {
public boolean exists(String key);
public File getFile(String key);
public InputStream getInputStream(String key) throws IOException;
public void store(String key, InputStream is);
public void invalidate(String key);
public void cleanup();
public void clear();
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.graphics.drawable.Drawable;
import android.widget.TabHost.TabSpec;
/**
* Acts as an interface to the TabSpec class for setting the content view.
* The level 3 SDK doesn't support setting a View for the content sections
* of the tab, so we can only use the big native tab style. The level 4
* SDK and up support specifying a custom view for the tab.
*
* @date March 9, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class TabsUtil3 {
private TabsUtil3() {
}
public static void setTabIndicator(TabSpec spec, String title, Drawable drawable) {
// if (drawable != null) {
// spec.setIndicator(title, drawable);
// } else {
spec.setIndicator(title);
// }
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* @date July 24, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class ImageUtils {
private ImageUtils() {
}
public static void resampleImageAndSaveToNewLocation(String pathInput, String pathOutput)
throws Exception
{
Bitmap bmp = resampleImage(pathInput, 640);
OutputStream out = new FileOutputStream(pathOutput);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
}
public static Bitmap resampleImage(String path, int maxDim)
throws Exception {
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bfo);
BitmapFactory.Options optsDownSample = new BitmapFactory.Options();
optsDownSample.inSampleSize = getClosestResampleSize(bfo.outWidth, bfo.outHeight, maxDim);
Bitmap bmpt = BitmapFactory.decodeFile(path, optsDownSample);
Matrix m = new Matrix();
if (bmpt.getWidth() > maxDim || bmpt.getHeight() > maxDim) {
BitmapFactory.Options optsScale = getResampling(bmpt.getWidth(), bmpt.getHeight(), maxDim);
m.postScale((float)optsScale.outWidth / (float)bmpt.getWidth(),
(float)optsScale.outHeight / (float)bmpt.getHeight());
}
int sdk = new Integer(Build.VERSION.SDK).intValue();
if (sdk > 4) {
int rotation = ExifUtils.getExifRotation(path);
if (rotation != 0) {
m.postRotate(rotation);
}
}
return Bitmap.createBitmap(bmpt, 0, 0, bmpt.getWidth(), bmpt.getHeight(), m, true);
}
private static BitmapFactory.Options getResampling(int cx, int cy, int max) {
float scaleVal = 1.0f;
BitmapFactory.Options bfo = new BitmapFactory.Options();
if (cx > cy) {
scaleVal = (float)max / (float)cx;
}
else if (cy > cx) {
scaleVal = (float)max / (float)cy;
}
else {
scaleVal = (float)max / (float)cx;
}
bfo.outWidth = (int)(cx * scaleVal + 0.5f);
bfo.outHeight = (int)(cy * scaleVal + 0.5f);
return bfo;
}
private static int getClosestResampleSize(int cx, int cy, int maxDim) {
int max = Math.max(cx, cy);
int resample = 1;
for (resample = 1; resample < Integer.MAX_VALUE; resample++) {
if (resample * maxDim > max) {
resample--;
break;
}
}
if (resample > 0) {
return resample;
}
return 1;
}
public static BitmapFactory.Options getBitmapDims(String path) throws Exception {
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bfo);
return bfo;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.media.ExifInterface;
import android.text.TextUtils;
/**
* @date July 24, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class ExifUtils
{
private ExifUtils() {
}
public static int getExifRotation(String imgPath) {
try {
ExifInterface exif = new ExifInterface(imgPath);
String rotationAmount = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
if (!TextUtils.isEmpty(rotationAmount)) {
int rotationParam = Integer.parseInt(rotationAmount);
switch (rotationParam) {
case ExifInterface.ORIENTATION_NORMAL:
return 0;
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
default:
return 0;
}
} else {
return 0;
}
} catch (Exception ex) {
return 0;
}
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.app.Activity;
import android.os.Build;
/**
* Acts as an interface to the contacts API which has changed between SDK 4 to
* 5.
*
* @date February 14, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public abstract class AddressBookUtils {
public abstract String getAllContactsPhoneNumbers(Activity activity);
public abstract String getAllContactsEmailAddresses(Activity activity);
public abstract AddressBookEmailBuilder getAllContactsEmailAddressesInfo(
Activity activity);
public static AddressBookUtils addressBookUtils() {
int sdk = new Integer(Build.VERSION.SDK).intValue();
if (sdk < 5) {
return new AddressBookUtils3and4();
} else {
return new AddressBookUtils5();
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.content.res.Resources;
import android.text.TextUtils;
import android.text.format.DateUtils;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.R;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Added date formats for today/yesterday/older contexts.
*/
public class StringFormatters {
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
"EEE, dd MMM yy HH:mm:ss Z");
/** Should look like "9:09 AM". */
public static final SimpleDateFormat DATE_FORMAT_TODAY = new SimpleDateFormat(
"h:mm a");
/** Should look like "Sun 1:56 PM". */
public static final SimpleDateFormat DATE_FORMAT_YESTERDAY = new SimpleDateFormat(
"E h:mm a");
/** Should look like "Sat Mar 20". */
public static final SimpleDateFormat DATE_FORMAT_OLDER = new SimpleDateFormat(
"E MMM d");
public static String getVenueLocationFull(Venue venue) {
StringBuilder sb = new StringBuilder();
sb.append(venue.getAddress());
if (sb.length() > 0) {
sb.append(" ");
}
if (!TextUtils.isEmpty(venue.getCrossstreet())) {
sb.append("(");
sb.append(venue.getCrossstreet());
sb.append(")");
}
return sb.toString();
}
public static String getVenueLocationCrossStreetOrCity(Venue venue) {
if (!TextUtils.isEmpty(venue.getCrossstreet())) {
return "(" + venue.getCrossstreet() + ")";
} else if (!TextUtils.isEmpty(venue.getCity()) && !TextUtils.isEmpty(venue.getState())
&& !TextUtils.isEmpty(venue.getZip())) {
return venue.getCity() + ", " + venue.getState() + " " + venue.getZip();
} else {
return null;
}
}
public static String getCheckinMessageLine1(Checkin checkin, boolean displayAtVenue) {
if (checkin.getDisplay() != null) {
return checkin.getDisplay();
} else {
StringBuilder sb = new StringBuilder();
sb.append(getUserAbbreviatedName(checkin.getUser()));
if (checkin.getVenue() != null && displayAtVenue) {
sb.append(" @ " + checkin.getVenue().getName());
}
return sb.toString();
}
}
public static String getCheckinMessageLine2(Checkin checkin) {
if (TextUtils.isEmpty(checkin.getShout()) == false) {
return checkin.getShout();
} else {
// No shout, show address instead.
if (checkin.getVenue() != null && checkin.getVenue().getAddress() != null) {
String address = checkin.getVenue().getAddress();
if (checkin.getVenue().getCrossstreet() != null
&& checkin.getVenue().getCrossstreet().length() > 0) {
address += " (" + checkin.getVenue().getCrossstreet() + ")";
}
return address;
} else {
return "";
}
}
}
public static String getCheckinMessageLine3(Checkin checkin) {
if (!TextUtils.isEmpty(checkin.getCreated())) {
try {
return getTodayTimeString(checkin.getCreated());
} catch (Exception ex) {
return checkin.getCreated();
}
} else {
return "";
}
}
public static String getUserFullName(User user) {
StringBuffer sb = new StringBuffer();
sb.append(user.getFirstname());
String lastName = user.getLastname();
if (lastName != null && lastName.length() > 0) {
sb.append(" ");
sb.append(lastName);
}
return sb.toString();
}
public static String getUserAbbreviatedName(User user) {
StringBuffer sb = new StringBuffer();
sb.append(user.getFirstname());
String lastName = user.getLastname();
if (lastName != null && lastName.length() > 0) {
sb.append(" ");
sb.append(lastName.substring(0, 1) + ".");
}
return sb.toString();
}
public static CharSequence getRelativeTimeSpanString(String created) {
try {
return DateUtils.getRelativeTimeSpanString(DATE_FORMAT.parse(created).getTime(),
new Date().getTime(), DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
} catch (ParseException e) {
return created;
}
}
/**
* Returns a format that will look like: "9:09 AM".
*/
public static String getTodayTimeString(String created) {
try {
return DATE_FORMAT_TODAY.format(DATE_FORMAT.parse(created));
} catch (ParseException e) {
return created;
}
}
/**
* Returns a format that will look like: "Sun 1:56 PM".
*/
public static String getYesterdayTimeString(String created) {
try {
return DATE_FORMAT_YESTERDAY.format(DATE_FORMAT.parse(created));
} catch (ParseException e) {
return created;
}
}
/**
* Returns a format that will look like: "Sat Mar 20".
*/
public static String getOlderTimeString(String created) {
try {
return DATE_FORMAT_OLDER.format(DATE_FORMAT.parse(created));
} catch (ParseException e) {
return created;
}
}
/**
* Reads an inputstream into a string.
*/
public static String inputStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
public static String getTipAge(Resources res, String created) {
Calendar then = Calendar.getInstance();
then.setTime(new Date(created));
Calendar now = Calendar.getInstance();
now.setTime(new Date(System.currentTimeMillis()));
if (now.get(Calendar.YEAR) == then.get(Calendar.YEAR)) {
if (now.get(Calendar.MONTH) == then.get(Calendar.MONTH)) {
int diffDays = now.get(Calendar.DAY_OF_MONTH)- then.get(Calendar.DAY_OF_MONTH);
if (diffDays == 0) {
return res.getString(R.string.tip_age_today);
} else if (diffDays == 1) {
return res.getString(R.string.tip_age_days, "1", "");
} else {
return res.getString(R.string.tip_age_days, String.valueOf(diffDays), "s");
}
} else {
int diffMonths = now.get(Calendar.MONTH) - then.get(Calendar.MONTH);
if (diffMonths == 1) {
return res.getString(R.string.tip_age_months, "1", "");
} else {
return res.getString(R.string.tip_age_months, String.valueOf(diffMonths), "s");
}
}
} else {
int diffYears = now.get(Calendar.YEAR) - then.get(Calendar.YEAR);
if (diffYears == 1) {
return res.getString(R.string.tip_age_years, "1", "");
} else {
return res.getString(R.string.tip_age_years, String.valueOf(diffYears), "s");
}
}
}
public static String createServerDateFormatV1() {
DateFormat df = new SimpleDateFormat("EEE, dd MMM yy HH:mm:ss Z");
return df.format(new Date());
}
}
| Java |
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Handles building an internal list of all email addresses as both a comma
* separated list, and as a linked hash map for use with email invites. The
* internal map is kept for pruning when we get a list of contacts which are
* already foursquare users back from the invite api method. Note that after
* the prune method is called, the internal mEmailsCommaSeparated memeber may
* be out of sync with the contents of the other maps.
*
* @date April 26, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class AddressBookEmailBuilder {
/**
* Keeps all emails as a flat comma separated list for use with the
* API findFriends method.
*/
private StringBuilder mEmailsCommaSeparated;
/**
* Links a single email address to a single contact name.
*/
private LinkedHashMap<String, String> mEmailsToNames;
/**
* Links a single contact name to multiple email addresses.
*/
private HashMap<String, HashSet<String>> mNamesToEmails;
public AddressBookEmailBuilder() {
mEmailsCommaSeparated = new StringBuilder();
mEmailsToNames = new LinkedHashMap<String, String>();
mNamesToEmails = new HashMap<String, HashSet<String>>();
}
public void addContact(String contactName, String contactEmail) {
// Email addresses should be uniquely tied to a single contact name.
mEmailsToNames.put(contactEmail, contactName);
// Reverse link, a single contact can have multiple email addresses.
HashSet<String> emailsForContact = mNamesToEmails.get(contactName);
if (emailsForContact == null) {
emailsForContact = new HashSet<String>();
mNamesToEmails.put(contactName, emailsForContact);
}
emailsForContact.add(contactEmail);
// Keep building the comma separated flat list of email addresses.
if (mEmailsCommaSeparated.length() > 0) {
mEmailsCommaSeparated.append(",");
}
mEmailsCommaSeparated.append(contactEmail);
}
public String getEmailsCommaSeparated() {
return mEmailsCommaSeparated.toString();
}
public void pruneEmailsAndNames(Group<User> group) {
if (group != null) {
for (User it : group) {
// Get the contact name this email address belongs to.
String contactName = mEmailsToNames.get(it.getEmail());
if (contactName != null) {
Set<String> allEmailsForContact = mNamesToEmails.get(contactName);
if (allEmailsForContact != null) {
for (String jt : allEmailsForContact) {
// Get rid of these emails from the master list.
mEmailsToNames.remove(jt);
}
}
}
}
}
}
/** Returns the map as a list of [email, name] pairs. */
public List<ContactSimple> getEmailsAndNamesAsList() {
List<ContactSimple> list = new ArrayList<ContactSimple>();
for (Map.Entry<String, String> it : mEmailsToNames.entrySet()) {
ContactSimple contact = new ContactSimple();
contact.mName = it.getValue();
contact.mEmail = it.getKey();
list.add(contact);
}
return list;
}
public String getNameForEmail(String email) {
return mEmailsToNames.get(email);
}
public String toStringCurrentEmails() {
StringBuilder sb = new StringBuilder(1024);
sb.append("Current email contents:\n");
for (Map.Entry<String, String> it : mEmailsToNames.entrySet()) {
sb.append(it.getValue()); sb.append(" "); sb.append(it.getKey());
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
AddressBookEmailBuilder bld = new AddressBookEmailBuilder();
bld.addContact("john", "john@google.com");
bld.addContact("john", "john@hotmail.com");
bld.addContact("john", "john@yahoo.com");
bld.addContact("jane", "jane@blah.com");
bld.addContact("dave", "dave@amazon.com");
bld.addContact("dave", "dave@earthlink.net");
bld.addContact("sara", "sara@odwalla.org");
bld.addContact("sara", "sara@test.com");
System.out.println("Comma separated list of emails addresses:");
System.out.println(bld.getEmailsCommaSeparated());
Group<User> users = new Group<User>();
User userJohn = new User();
userJohn.setEmail("john@hotmail.com");
users.add(userJohn);
User userSara = new User();
userSara.setEmail("sara@test.com");
users.add(userSara);
bld.pruneEmailsAndNames(users);
System.out.println(bld.toStringCurrentEmails());
}
public static class ContactSimple {
public String mName;
public String mEmail;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import com.google.android.maps.GeoPoint;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;
/**
* @date June 30, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class GeoUtils {
/**
* To be used if you just want a one-shot best last location, iterates over
* all providers and returns the most accurate result.
*/
public static Location getBestLastGeolocation(Context context) {
LocationManager manager = (LocationManager)context.getSystemService(
Context.LOCATION_SERVICE);
List<String> providers = manager.getAllProviders();
Location bestLocation = null;
for (String it : providers) {
Location location = manager.getLastKnownLocation(it);
if (location != null) {
if (bestLocation == null ||
location.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = location;
}
}
}
return bestLocation;
}
public static GeoPoint locationToGeoPoint(Location location) {
if (location != null) {
GeoPoint pt = new GeoPoint(
(int)(location.getLatitude() * 1E6 + 0.5),
(int)(location.getLongitude() * 1E6 + 0.5));
return pt;
} else {
return null;
}
}
public static GeoPoint stringLocationToGeoPoint(String strlat, String strlon) {
try {
double lat = Double.parseDouble(strlat);
double lon = Double.parseDouble(strlon);
GeoPoint pt = new GeoPoint(
(int)(lat * 1E6 + 0.5),
(int)(lon * 1E6 + 0.5));
return pt;
} catch (Exception ex) {
return null;
}
}
} | Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.net.Uri;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class RemoteResourceManager extends Observable {
private static final String TAG = "RemoteResourceManager";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private DiskCache mDiskCache;
private RemoteResourceFetcher mRemoteResourceFetcher;
private FetcherObserver mFetcherObserver = new FetcherObserver();
public RemoteResourceManager(String cacheName) {
this(new BaseDiskCache("foursquare", cacheName));
}
public RemoteResourceManager(DiskCache cache) {
mDiskCache = cache;
mRemoteResourceFetcher = new RemoteResourceFetcher(mDiskCache);
mRemoteResourceFetcher.addObserver(mFetcherObserver);
}
public boolean exists(Uri uri) {
return mDiskCache.exists(Uri.encode(uri.toString()));
}
/**
* If IOException is thrown, we don't have the resource available.
*/
public File getFile(Uri uri) {
if (DEBUG) Log.d(TAG, "getInputStream(): " + uri);
return mDiskCache.getFile(Uri.encode(uri.toString()));
}
/**
* If IOException is thrown, we don't have the resource available.
*/
public InputStream getInputStream(Uri uri) throws IOException {
if (DEBUG) Log.d(TAG, "getInputStream(): " + uri);
return mDiskCache.getInputStream(Uri.encode(uri.toString()));
}
/**
* Request a resource be downloaded. Useful to call after a IOException from getInputStream.
*/
public void request(Uri uri) {
if (DEBUG) Log.d(TAG, "request(): " + uri);
mRemoteResourceFetcher.fetch(uri, Uri.encode(uri.toString()));
}
/**
* Explicitly expire an individual item.
*/
public void invalidate(Uri uri) {
mDiskCache.invalidate(Uri.encode(uri.toString()));
}
public void shutdown() {
mRemoteResourceFetcher.shutdown();
mDiskCache.cleanup();
}
public void clear() {
mRemoteResourceFetcher.shutdown();
mDiskCache.clear();
}
public static abstract class ResourceRequestObserver implements Observer {
private Uri mRequestUri;
abstract public void requestReceived(Observable observable, Uri uri);
public ResourceRequestObserver(Uri requestUri) {
mRequestUri = requestUri;
}
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Recieved update: " + data);
Uri dataUri = (Uri)data;
if (dataUri == mRequestUri) {
if (DEBUG) Log.d(TAG, "requestReceived: " + dataUri);
requestReceived(observable, dataUri);
}
}
}
/**
* Relay the observed download to this controlling class.
*/
private class FetcherObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
setChanged();
notifyObservers(data);
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.PreferenceActivity;
import com.joelapenna.foursquared.R;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
/**
* Collection of common functions which are called from the menu
*
* @author Alex Volovoy (avolovoy@gmail.com)
*/
public class MenuUtils {
// Common menu items
private static final int MENU_PREFERENCES = -1;
private static final int MENU_GROUP_SYSTEM = 20;
public static void addPreferencesToMenu(Context context, Menu menu) {
Intent intent = new Intent(context, PreferenceActivity.class);
menu.add(MENU_GROUP_SYSTEM, MENU_PREFERENCES, Menu.CATEGORY_SECONDARY,
R.string.preferences_label).setIcon(R.drawable.ic_menu_preferences).setIntent(
intent);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.text.TextUtils;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
/**
* @date September 2, 2010.
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TipUtils {
public static final String TIP_STATUS_TODO = "todo";
public static final String TIP_STATUS_DONE = "done";
public static boolean isTodo(Tip tip) {
if (tip != null) {
if (!TextUtils.isEmpty(tip.getStatus())) {
return tip.getStatus().equals(TIP_STATUS_TODO);
}
}
return false;
}
public static boolean isDone(Tip tip) {
if (tip != null) {
if (!TextUtils.isEmpty(tip.getStatus())) {
return tip.getStatus().equals(TIP_STATUS_DONE);
}
}
return false;
}
public static boolean areEqual(FoursquareType tipOrTodo1, FoursquareType tipOrTodo2) {
if (tipOrTodo1 instanceof Tip) {
if (tipOrTodo2 instanceof Todo) {
return false;
}
Tip tip1 = (Tip)tipOrTodo1;
Tip tip2 = (Tip)tipOrTodo2;
if (!tip1.getId().equals(tip2.getId())) {
return false;
}
if (!TextUtils.isEmpty(tip1.getStatus()) && !TextUtils.isEmpty(tip2.getStatus())) {
return tip1.getStatus().equals(tip2.getStatus());
} else if (TextUtils.isEmpty(tip1.getStatus()) && TextUtils.isEmpty(tip2.getStatus())) {
return true;
} else {
return false;
}
} else if (tipOrTodo1 instanceof Todo) {
if (tipOrTodo2 instanceof Tip) {
return false;
}
Todo todo1 = (Todo)tipOrTodo1;
Todo todo2 = (Todo)tipOrTodo2;
if (!todo1.getId().equals(todo2.getId())) {
return false;
}
if (todo1.getTip().getId().equals(todo2.getId())) {
return true;
}
}
return false;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.R;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;
/**
* Acts as an interface to the TabSpec class for setting the content view. The
* level 3 SDK doesn't support setting a View for the content sections of the
* tab, so we can only use the big native tab style. The level 4 SDK and up
* support specifying a custom view for the tab.
*
* @date March 9, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public abstract class TabsUtil {
private static void setTabIndicator(TabSpec spec, String title, Drawable drawable, View view) {
int sdk = new Integer(Build.VERSION.SDK).intValue();
if (sdk < 4) {
TabsUtil3.setTabIndicator(spec, title, drawable);
} else {
TabsUtil4.setTabIndicator(spec, view);
}
}
public static void addTab(TabHost host, String title, int drawable, int index, int layout) {
TabHost.TabSpec spec = host.newTabSpec("tab" + index);
spec.setContent(layout);
View view = prepareTabView(host.getContext(), title, drawable);
TabsUtil.setTabIndicator(spec, title, host.getContext().getResources().getDrawable(drawable), view);
host.addTab(spec);
}
public static void addTab(TabHost host, String title, int drawable, int index, Intent intent) {
TabHost.TabSpec spec = host.newTabSpec("tab" + index);
spec.setContent(intent);
View view = prepareTabView(host.getContext(), title, drawable);
TabsUtil.setTabIndicator(spec, title, host.getContext().getResources().getDrawable(drawable), view);
host.addTab(spec);
}
private static View prepareTabView(Context context, String text, int drawable) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_main_nav, null);
TextView tv = (TextView) view.findViewById(R.id.tvTitle);
tv.setText(text);
ImageView iv = (ImageView) view.findViewById(R.id.ivIcon);
iv.setImageResource(drawable);
return view;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import java.io.IOException;
import java.util.Observable;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class UserUtils {
public static void ensureUserPhoto(final Context context, final User user, final boolean DEBUG,
final String TAG) {
Activity activity = ((Activity) context);
final ImageView photo = (ImageView) activity.findViewById(R.id.photo);
if (user.getPhoto() == null) {
photo.setImageResource(R.drawable.blank_boy);
return;
}
final Uri photoUri = Uri.parse(user.getPhoto());
if (photoUri != null) {
RemoteResourceManager userPhotosManager = ((Foursquared) activity.getApplication())
.getRemoteResourceManager();
try {
Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager
.getInputStream(photoUri));
photo.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "photo not already retrieved, requesting: " + photoUri);
userPhotosManager.addObserver(new RemoteResourceManager.ResourceRequestObserver(
photoUri) {
@Override
public void requestReceived(Observable observable, Uri uri) {
observable.deleteObserver(this);
updateUserPhoto(context, photo, uri, user, DEBUG, TAG);
}
});
userPhotosManager.request(photoUri);
}
}
}
private static void updateUserPhoto(Context context, final ImageView photo, final Uri uri,
final User user, final boolean DEBUG, final String TAG) {
final Activity activity = ((Activity) context);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
if (DEBUG) Log.d(TAG, "Loading user photo: " + uri);
RemoteResourceManager userPhotosManager = ((Foursquared) activity
.getApplication()).getRemoteResourceManager();
Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager
.getInputStream(uri));
photo.setImageBitmap(bitmap);
if (DEBUG) Log.d(TAG, "Loaded user photo: " + uri);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "Unable to load user photo: " + uri);
if (Foursquare.MALE.equals(user.getGender())) {
photo.setImageResource(R.drawable.blank_boy);
} else {
photo.setImageResource(R.drawable.blank_girl);
}
} catch (Exception e) {
Log.d(TAG, "Ummm............", e);
}
}
});
}
public static boolean isFriend(User user) {
if (user == null) {
return false;
} else if (TextUtils.isEmpty(user.getFriendstatus())) {
return false;
} else if (user.getFriendstatus().equals("friend")) {
return true;
} else {
return false;
}
}
public static boolean isFollower(User user) {
if (user == null) {
return false;
} else if (TextUtils.isEmpty(user.getFriendstatus())) {
return false;
} else if (user.getFriendstatus().equals("pendingyou")) {
return true;
} else {
return false;
}
}
public static boolean isFriendStatusPendingYou(User user) {
return user != null && user.getFriendstatus() != null &&
user.getFriendstatus().equals("pendingyou");
}
public static boolean isFriendStatusPendingThem(User user) {
return user != null && user.getFriendstatus() != null &&
user.getFriendstatus().equals("pendingthem");
}
public static boolean isFriendStatusFollowingThem(User user) {
return user != null && user.getFriendstatus() != null &&
user.getFriendstatus().equals("followingthem");
}
public static int getDrawableForMeTabByGender(String gender) {
if (gender != null && gender.equals("female")) {
return R.drawable.tab_main_nav_me_girl_selector;
} else {
return R.drawable.tab_main_nav_me_boy_selector;
}
}
public static int getDrawableForMeMenuItemByGender(String gender) {
if (gender == null) {
return R.drawable.ic_menu_myinfo_boy;
} else if (gender.equals("female")) {
return R.drawable.ic_menu_myinfo_girl;
} else {
return R.drawable.ic_menu_myinfo_boy;
}
}
public static boolean getCanHaveFollowers(User user) {
if (user.getTypes() != null && user.getTypes().size() > 0) {
if (user.getTypes().contains("canHaveFollowers")) {
return true;
}
}
return false;
}
public static int getDrawableByGenderForUserThumbnail(User user) {
String gender = user.getGender();
if (gender != null && gender.equals("female")) {
return R.drawable.blank_girl;
} else {
return R.drawable.blank_boy;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
/**
* @date September 15, 2010.
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UiUtil {
private static final String TAG = "UiUtil";
public static int sdkVersion() {
return new Integer(Build.VERSION.SDK).intValue();
}
public static void startDialer(Context context, String phoneNumber) {
try {
Intent dial = new Intent();
dial.setAction(Intent.ACTION_DIAL);
dial.setData(Uri.parse("tel:" + phoneNumber));
context.startActivity(dial);
} catch (Exception ex) {
Log.e(TAG, "Error starting phone dialer intent.", ex);
Toast.makeText(context, "Sorry, we couldn't find any app to place a phone call!",
Toast.LENGTH_SHORT).show();
}
}
public static void startSmsIntent(Context context, String phoneNumber) {
try {
Uri uri = Uri.parse("sms:" + phoneNumber);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra("address", phoneNumber);
intent.setType("vnd.android-dir/mms-sms");
context.startActivity(intent);
} catch (Exception ex) {
Log.e(TAG, "Error starting sms intent.", ex);
Toast.makeText(context, "Sorry, we couldn't find any app to send an SMS!",
Toast.LENGTH_SHORT).show();
}
}
public static void startEmailIntent(Context context, String emailAddress) {
try {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {
emailAddress
});
context.startActivity(intent);
} catch (Exception ex) {
Log.e(TAG, "Error starting email intent.", ex);
Toast.makeText(context, "Sorry, we couldn't find any app for sending emails!",
Toast.LENGTH_SHORT).show();
}
}
public static void startWebIntent(Context context, String url) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
} catch (Exception ex) {
Log.e(TAG, "Error starting url intent.", ex);
Toast.makeText(context, "Sorry, we couldn't find any app for viewing this url!",
Toast.LENGTH_SHORT).show();
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class JavaLoggingHandler extends Handler {
private static Map<Level, Integer> sLoglevelMap = new HashMap<Level, Integer>();
static {
sLoglevelMap.put(Level.FINEST, Log.VERBOSE);
sLoglevelMap.put(Level.FINER, Log.DEBUG);
sLoglevelMap.put(Level.FINE, Log.DEBUG);
sLoglevelMap.put(Level.INFO, Log.INFO);
sLoglevelMap.put(Level.WARNING, Log.WARN);
sLoglevelMap.put(Level.SEVERE, Log.ERROR);
}
@Override
public void publish(LogRecord record) {
Integer level = sLoglevelMap.get(record.getLevel());
if (level == null) {
level = Log.VERBOSE;
}
Log.println(level, record.getLoggerName(), record.getMessage());
}
@Override
public void close() {
}
@Override
public void flush() {
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class BaseDiskCache implements DiskCache {
private static final String TAG = "BaseDiskCache";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final String NOMEDIA = ".nomedia";
private static final int MIN_FILE_SIZE_IN_BYTES = 100;
private File mStorageDirectory;
BaseDiskCache(String dirPath, String name) {
// Lets make sure we can actually cache things!
File baseDirectory = new File(Environment.getExternalStorageDirectory(), dirPath);
File storageDirectory = new File(baseDirectory, name);
createDirectory(storageDirectory);
mStorageDirectory = storageDirectory;
// cleanup(); // Remove invalid files that may have shown up.
cleanupSimple();
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#exists(java.lang.String)
*/
@Override
public boolean exists(String key) {
return getFile(key).exists();
}
/**
* This is silly, but our content provider *has* to serve content: URIs as File/FileDescriptors
* using ContentProvider.openAssetFile, this is a limitation of the StreamLoader that is used by
* the WebView. So, we handle this by writing the file to disk, and returning a File pointer to
* it.
*
* @param guid
* @return
*/
public File getFile(String hash) {
return new File(mStorageDirectory.toString() + File.separator + hash);
}
public InputStream getInputStream(String hash) throws IOException {
return (InputStream)new FileInputStream(getFile(hash));
}
/*
* (non-Javadoc)
* @see com.joelapenna.everdroid.evernote.NoteResourceDataBodyCache#storeResource (com
* .evernote.edam.type.Resource)
*/
public void store(String key, InputStream is) {
if (DEBUG) Log.d(TAG, "store: " + key);
is = new BufferedInputStream(is);
try {
OutputStream os = new BufferedOutputStream(new FileOutputStream(getFile(key)));
byte[] b = new byte[2048];
int count;
int total = 0;
while ((count = is.read(b)) > 0) {
os.write(b, 0, count);
total += count;
}
os.close();
if (DEBUG) Log.d(TAG, "store complete: " + key);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "store failed to store: " + key, e);
return;
}
}
public void invalidate(String key) {
getFile(key).delete();
}
public void cleanup() {
// removes files that are too small to be valid. Cheap and cheater way to remove files that
// were corrupted during download.
String[] children = mStorageDirectory.list();
if (children != null) { // children will be null if hte directyr does not exist.
for (int i = 0; i < children.length; i++) {
File child = new File(mStorageDirectory, children[i]);
if (!child.equals(new File(mStorageDirectory, NOMEDIA))
&& child.length() <= MIN_FILE_SIZE_IN_BYTES) {
if (DEBUG) Log.d(TAG, "Deleting: " + child);
child.delete();
}
}
}
}
/**
* Temporary fix until we rework this disk cache. We delete the first 50 youngest files
* if we find the cache has more than 1000 images in it.
*/
public void cleanupSimple() {
final int maxNumFiles = 1000;
final int numFilesToDelete = 50;
String[] children = mStorageDirectory.list();
if (children != null) {
if (DEBUG) Log.d(TAG, "Found disk cache length to be: " + children.length);
if (children.length > maxNumFiles) {
if (DEBUG) Log.d(TAG, "Disk cache found to : " + children);
for (int i = children.length - 1, m = i - numFilesToDelete; i > m; i--) {
File child = new File(mStorageDirectory, children[i]);
if (DEBUG) Log.d(TAG, " deleting: " + child.getName());
child.delete();
}
}
}
}
public void clear() {
// Clear the whole cache. Coolness.
String[] children = mStorageDirectory.list();
if (children != null) { // children will be null if hte directyr does not exist.
for (int i = 0; i < children.length; i++) {
File child = new File(mStorageDirectory, children[i]);
if (!child.equals(new File(mStorageDirectory, NOMEDIA))) {
if (DEBUG) Log.d(TAG, "Deleting: " + child);
child.delete();
}
}
}
mStorageDirectory.delete();
}
private static final void createDirectory(File storageDirectory) {
if (!storageDirectory.exists()) {
Log.d(TAG, "Trying to create storageDirectory: "
+ String.valueOf(storageDirectory.mkdirs()));
Log.d(TAG, "Exists: " + storageDirectory + " "
+ String.valueOf(storageDirectory.exists()));
Log.d(TAG, "State: " + Environment.getExternalStorageState());
Log.d(TAG, "Isdir: " + storageDirectory + " "
+ String.valueOf(storageDirectory.isDirectory()));
Log.d(TAG, "Readable: " + storageDirectory + " "
+ String.valueOf(storageDirectory.canRead()));
Log.d(TAG, "Writable: " + storageDirectory + " "
+ String.valueOf(storageDirectory.canWrite()));
File tmp = storageDirectory.getParentFile();
Log.d(TAG, "Exists: " + tmp + " " + String.valueOf(tmp.exists()));
Log.d(TAG, "Isdir: " + tmp + " " + String.valueOf(tmp.isDirectory()));
Log.d(TAG, "Readable: " + tmp + " " + String.valueOf(tmp.canRead()));
Log.d(TAG, "Writable: " + tmp + " " + String.valueOf(tmp.canWrite()));
tmp = tmp.getParentFile();
Log.d(TAG, "Exists: " + tmp + " " + String.valueOf(tmp.exists()));
Log.d(TAG, "Isdir: " + tmp + " " + String.valueOf(tmp.isDirectory()));
Log.d(TAG, "Readable: " + tmp + " " + String.valueOf(tmp.canRead()));
Log.d(TAG, "Writable: " + tmp + " " + String.valueOf(tmp.canWrite()));
}
File nomediaFile = new File(storageDirectory, NOMEDIA);
if (!nomediaFile.exists()) {
try {
Log.d(TAG, "Created file: " + nomediaFile + " "
+ String.valueOf(nomediaFile.createNewFile()));
} catch (IOException e) {
Log.d(TAG, "Unable to create .nomedia file for some reason.", e);
throw new IllegalStateException("Unable to create nomedia file.");
}
}
// After we best-effort try to create the file-structure we need,
// lets make sure it worked.
if (!(storageDirectory.isDirectory() && nomediaFile.exists())) {
throw new RuntimeException("Unable to create storage directory and nomedia file.");
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.R;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.widget.Toast;
/**
* Collection of common functions for sending feedback.
*
* @author Alex Volovoy (avolovoy@gmail.com)
*/
public class FeedbackUtils {
private static final String FEEDBACK_EMAIL_ADDRESS = "crashreport-android@foursquare.com";
public static void SendFeedBack(Context context, Foursquared foursquared) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
final String[] mailto = {
FEEDBACK_EMAIL_ADDRESS
};
final String new_line = "\n";
StringBuilder body = new StringBuilder();
Resources res = context.getResources();
body.append(new_line);
body.append(new_line);
body.append(res.getString(R.string.feedback_more));
body.append(new_line);
body.append(res.getString(R.string.feedback_question_how_to_reproduce));
body.append(new_line);
body.append(new_line);
body.append(res.getString(R.string.feedback_question_expected_output));
body.append(new_line);
body.append(new_line);
body.append(res.getString(R.string.feedback_question_additional_information));
body.append(new_line);
body.append(new_line);
body.append("--------------------------------------");
body.append(new_line);
body.append("ver: ");
body.append(foursquared.getVersion());
body.append(new_line);
body.append("user: ");
body.append(foursquared.getUserId());
body.append(new_line);
body.append("p: ");
body.append(Build.MODEL);
body.append(new_line);
body.append("os: ");
body.append(Build.VERSION.RELEASE);
body.append(new_line);
body.append("build#: ");
body.append(Build.DISPLAY);
body.append(new_line);
body.append(new_line);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.feedback_subject));
sendIntent.putExtra(Intent.EXTRA_EMAIL, mailto);
sendIntent.putExtra(Intent.EXTRA_TEXT, body.toString());
sendIntent.setType("message/rfc822");
try {
context.startActivity(Intent.createChooser(sendIntent, context
.getText(R.string.feedback_subject)));
} catch (ActivityNotFoundException ex) {
Toast.makeText(context, context.getText(R.string.feedback_error), Toast.LENGTH_SHORT)
.show();
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.os.Parcel;
import android.text.TextUtils;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.Venue;
/**
* @date September 16, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class VenueUtils {
public static void handleTipChange(Venue venue, Tip tip, Todo todo) {
// Update the tip in the tips group, if it exists.
updateTip(venue, tip);
// If it is a to-do, then make sure a to-do exists for it
// in the to-do group.
if (TipUtils.isTodo(tip)) {
addTodo(venue, tip, todo);
} else {
// If it is not a to-do, make sure it does not exist in the
// to-do group.
removeTodo(venue, tip);
}
}
private static void updateTip(Venue venue, Tip tip) {
if (venue.getTips() != null) {
for (Tip it : venue.getTips()) {
if (it.getId().equals(tip.getId())) {
it.setStatus(tip.getStatus());
break;
}
}
}
}
public static void addTodo(Venue venue, Tip tip, Todo todo) {
venue.setHasTodo(true);
if (venue.getTodos() == null) {
venue.setTodos(new Group<Todo>());
}
// If found a to-do linked to the tip ID, then overwrite to-do attributes
// with newer to-do object.
for (Todo it : venue.getTodos()) {
if (it.getTip().getId().equals(tip.getId())) {
it.setId(todo.getId());
it.setCreated(todo.getCreated());
return;
}
}
venue.getTodos().add(todo);
}
public static void addTip(Venue venue, Tip tip) {
if (venue.getTips() == null) {
venue.setTips(new Group<Tip>());
}
for (Tip it : venue.getTips()) {
if (it.getId().equals(tip.getId())) {
return;
}
}
venue.getTips().add(tip);
}
private static void removeTodo(Venue venue, Tip tip) {
for (Todo it : venue.getTodos()) {
if (it.getTip().getId().equals(tip.getId())) {
venue.getTodos().remove(it);
break;
}
}
if (venue.getTodos().size() > 0) {
venue.setHasTodo(true);
} else {
venue.setHasTodo(false);
}
}
public static void replaceTipsAndTodos(Venue venueTarget, Venue venueSource) {
if (venueTarget.getTips() == null) {
venueTarget.setTips(new Group<Tip>());
}
if (venueTarget.getTodos() == null) {
venueTarget.setTodos(new Group<Todo>());
}
if (venueSource.getTips() == null) {
venueSource.setTips(new Group<Tip>());
}
if (venueSource.getTodos() == null) {
venueSource.setTodos(new Group<Todo>());
}
venueTarget.getTips().clear();
venueTarget.getTips().addAll(venueSource.getTips());
venueTarget.getTodos().clear();
venueTarget.getTodos().addAll(venueSource.getTodos());
if (venueTarget.getTodos().size() > 0) {
venueTarget.setHasTodo(true);
} else {
venueTarget.setHasTodo(false);
}
}
public static boolean getSpecialHere(Venue venue) {
if (venue != null && venue.getSpecials() != null && venue.getSpecials().size() > 0) {
Venue specialVenue = venue.getSpecials().get(0).getVenue();
if (specialVenue == null || specialVenue.getId().equals(venue.getId())) {
return true;
}
}
return false;
}
/**
* Creates a copy of the passed venue. This should really be implemented
* as a copy constructor.
*/
public static Venue cloneVenue(Venue venue) {
Parcel p1 = Parcel.obtain();
Parcel p2 = Parcel.obtain();
byte[] bytes = null;
p1.writeValue(venue);
bytes = p1.marshall();
p2.unmarshall(bytes, 0, bytes.length);
p2.setDataPosition(0);
Venue venueNew = (Venue)p2.readValue(Venue.class.getClassLoader());
p1.recycle();
p2.recycle();
return venueNew;
}
public static String toStringVenueShare(Venue venue) {
StringBuilder sb = new StringBuilder();
sb.append(venue.getName()); sb.append("\n");
sb.append(StringFormatters.getVenueLocationFull(venue));
if (!TextUtils.isEmpty(venue.getPhone())) {
sb.append("\n");
sb.append(venue.getPhone());
}
return sb.toString();
}
/**
* Dumps some info about a venue. This can be moved into the Venue class.
*/
public static String toString(Venue venue) {
StringBuilder sb = new StringBuilder();
sb.append(venue.toString()); sb.append(":\n");
sb.append(" id: "); sb.append(venue.getId()); sb.append("\n");
sb.append(" name: "); sb.append(venue.getName()); sb.append("\n");
sb.append(" address: "); sb.append(venue.getAddress()); sb.append("\n");
sb.append(" cross: "); sb.append(venue.getCrossstreet()); sb.append("\n");
sb.append(" hastodo: "); sb.append(venue.getHasTodo()); sb.append("\n");
sb.append(" tips: "); sb.append(venue.getTips() == null ? "(null)" : venue.getTips().size()); sb.append("\n");
sb.append(" todos: "); sb.append(venue.getTodos() == null ? "(null)" : venue.getTodos().size()); sb.append("\n");
sb.append(" specials: "); sb.append(venue.getSpecials() == null ? "(null)" : venue.getSpecials().size()); sb.append("\n");
return sb.toString();
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.util.Log;
import java.util.Calendar;
import java.util.Date;
/**
* Initializes a few Date objects to act as boundaries for sorting checkin lists
* by the following time categories:
*
* <ul>
* <li>Within the last three hours.</li>
* <li>Today</li>
* <li>Yesterday</li>
* </ul>
*
* Create an instance of this class, then call one of the three getBoundary() methods
* and compare against a Date object to see if it falls before or after.
*
* @date March 22, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class CheckinTimestampSort {
private static final String TAG = "CheckinTimestampSort";
private static final boolean DEBUG = false;
private static final int IDX_RECENT = 0;
private static final int IDX_TODAY = 1;
private static final int IDX_YESTERDAY = 2;
private Date[] mBoundaries;
public CheckinTimestampSort() {
mBoundaries = getDateObjects();
}
public Date getBoundaryRecent() {
return mBoundaries[IDX_RECENT];
}
public Date getBoundaryToday() {
return mBoundaries[IDX_TODAY];
}
public Date getBoundaryYesterday() {
return mBoundaries[IDX_YESTERDAY];
}
private static Date[] getDateObjects() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
if (DEBUG) Log.d(TAG, "Now: " + cal.getTime().toGMTString());
// Three hours ago or newer.
cal.add(Calendar.HOUR, -3);
Date dateRecent = cal.getTime();
if (DEBUG) Log.d(TAG, "Recent: " + cal.getTime().toGMTString());
// Today.
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.HOUR);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
Date dateToday = cal.getTime();
if (DEBUG) Log.d(TAG, "Today: " + cal.getTime().toGMTString());
// Yesterday.
cal.add(Calendar.DAY_OF_MONTH, -1);
Date dateYesterday = cal.getTime();
if (DEBUG) Log.d(TAG, "Yesterday: " + cal.getTime().toGMTString());
return new Date[] { dateRecent, dateToday, dateYesterday };
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.app.Activity;
import android.database.Cursor;
import android.provider.Contacts;
import android.provider.Contacts.PhonesColumns;
/**
* Implementation of address book functions for sdk levels 3 and 4.
*
* @date February 14, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class AddressBookUtils3and4 extends AddressBookUtils {
public AddressBookUtils3and4() {
}
@Override
public String getAllContactsPhoneNumbers(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] {
PhonesColumns.NUMBER
};
Cursor c = activity.managedQuery(Contacts.Phones.CONTENT_URI, PROJECTION, null, null,
Contacts.Phones.DEFAULT_SORT_ORDER);
if (c.moveToFirst()) {
sb.append(c.getString(0));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(0));
}
}
c.close();
return sb.toString();
}
@Override
public String getAllContactsEmailAddresses(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] {
Contacts.ContactMethods.DATA
};
Cursor c = activity.managedQuery(
Contacts.ContactMethods.CONTENT_EMAIL_URI,
PROJECTION, null, null,
Contacts.ContactMethods.DEFAULT_SORT_ORDER);
if (c.moveToFirst()) {
sb.append(c.getString(0));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(0));
}
}
c.close();
return sb.toString();
}
@Override
public AddressBookEmailBuilder getAllContactsEmailAddressesInfo(Activity activity) {
String[] PROJECTION = new String[] {
Contacts.PeopleColumns.NAME,
Contacts.ContactMethods.DATA
};
Cursor c = activity.managedQuery(
Contacts.ContactMethods.CONTENT_EMAIL_URI,
PROJECTION, null, null,
Contacts.ContactMethods.DEFAULT_SORT_ORDER);
// We give a list of emails: markww@gmail.com,johndoe@gmail.com,janedoe@gmail.com
// We get back only a list of emails of users that exist on the system (johndoe@gmail.com)
// Iterate over all those returned users, on each iteration, remove from our hashmap.
// Can now use the left over hashmap, which is still in correct order to display invites.
AddressBookEmailBuilder bld = new AddressBookEmailBuilder();
if (c.moveToFirst()) {
bld.addContact(c.getString(0), c.getString(1));
while (c.moveToNext()) {
bld.addContact(c.getString(0), c.getString(1));
}
}
c.close();
return bld;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import java.text.ParseException;
import java.util.Comparator;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Updated getVenueDistanceComparator() to do numeric comparison. (2010-03-23)
*/
public class Comparators {
private static Comparator<Venue> sVenueDistanceComparator = null;
private static Comparator<User> sUserRecencyComparator = null;
private static Comparator<Checkin> sCheckinRecencyComparator = null;
private static Comparator<Checkin> sCheckinDistanceComparator = null;
private static Comparator<Tip> sTipRecencyComparator = null;
public static Comparator<Venue> getVenueDistanceComparator() {
if (sVenueDistanceComparator == null) {
sVenueDistanceComparator = new Comparator<Venue>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Venue object1, Venue object2) {
// TODO: In practice we're pretty much guaranteed to get valid locations
// from foursquare, but.. what if we don't, what's a good fail behavior
// here?
try {
int d1 = Integer.parseInt(object1.getDistance());
int d2 = Integer.parseInt(object2.getDistance());
if (d1 < d2) {
return -1;
} else if (d1 > d2) {
return 1;
} else {
return 0;
}
} catch (NumberFormatException ex) {
return object1.getDistance().compareTo(object2.getDistance());
}
}
};
}
return sVenueDistanceComparator;
}
public static Comparator<Venue> getVenueNameComparator() {
if (sVenueDistanceComparator == null) {
sVenueDistanceComparator = new Comparator<Venue>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Venue object1, Venue object2) {
return object1.getName().toLowerCase().compareTo(
object2.getName().toLowerCase());
}
};
}
return sVenueDistanceComparator;
}
public static Comparator<User> getUserRecencyComparator() {
if (sUserRecencyComparator == null) {
sUserRecencyComparator = new Comparator<User>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(User object1, User object2) {
try {
return StringFormatters.DATE_FORMAT.parse(object2.getCreated()).compareTo(
StringFormatters.DATE_FORMAT.parse(object1.getCreated()));
} catch (ParseException e) {
return 0;
}
}
};
}
return sUserRecencyComparator;
}
public static Comparator<Checkin> getCheckinRecencyComparator() {
if (sCheckinRecencyComparator == null) {
sCheckinRecencyComparator = new Comparator<Checkin>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Checkin object1, Checkin object2) {
try {
return StringFormatters.DATE_FORMAT.parse(object2.getCreated()).compareTo(
StringFormatters.DATE_FORMAT.parse(object1.getCreated()));
} catch (ParseException e) {
return 0;
}
}
};
}
return sCheckinRecencyComparator;
}
public static Comparator<Checkin> getCheckinDistanceComparator() {
if (sCheckinDistanceComparator == null) {
sCheckinDistanceComparator = new Comparator<Checkin>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Checkin object1, Checkin object2) {
try {
int d1 = Integer.parseInt(object1.getDistance());
int d2 = Integer.parseInt(object2.getDistance());
if (d1 > d2) {
return 1;
} else if (d2 > d1) {
return -1;
} else {
return 0;
}
} catch (NumberFormatException ex) {
return 0;
}
}
};
}
return sCheckinDistanceComparator;
}
public static Comparator<Tip> getTipRecencyComparator() {
if (sTipRecencyComparator == null) {
sTipRecencyComparator = new Comparator<Tip>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Tip object1, Tip object2) {
try {
return StringFormatters.DATE_FORMAT.parse(object2.getCreated()).compareTo(
StringFormatters.DATE_FORMAT.parse(object1.getCreated()));
} catch (ParseException e) {
return 0;
}
}
};
}
return sTipRecencyComparator;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class NullDiskCache implements DiskCache {
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#exists(java.lang.String)
*/
@Override
public boolean exists(String key) {
return false;
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#getFile(java.lang.String)
*/
@Override
public File getFile(String key) {
return null;
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#getInputStream(java.lang.String)
*/
@Override
public InputStream getInputStream(String key) throws IOException {
throw new FileNotFoundException();
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#store(java.lang.String, java.io.InputStream)
*/
@Override
public void store(String key, InputStream is) {
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#cleanup()
*/
@Override
public void cleanup() {
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#invalidate(java.lang.String)
*/
@Override
public void invalidate(String key) {
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#clear()
*/
@Override
public void clear() {
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.error.LocationException;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class NotificationsUtil {
private static final String TAG = "NotificationsUtil";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static void ToastReasonForFailure(Context context, Exception e) {
if (DEBUG) Log.d(TAG, "Toasting for exception: ", e);
if (e == null) {
Toast.makeText(context, "A surprising new problem has occured. Try again!",
Toast.LENGTH_SHORT).show();
} else if (e instanceof SocketTimeoutException) {
Toast.makeText(context, "Foursquare over capacity, server request timed out!", Toast.LENGTH_SHORT).show();
} else if (e instanceof SocketException) {
Toast.makeText(context, "Foursquare server not responding", Toast.LENGTH_SHORT).show();
} else if (e instanceof IOException) {
Toast.makeText(context, "Network unavailable", Toast.LENGTH_SHORT).show();
} else if (e instanceof LocationException) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
} else if (e instanceof FoursquareCredentialsException) {
Toast.makeText(context, "Authorization failed.", Toast.LENGTH_SHORT).show();
} else if (e instanceof FoursquareException) {
// FoursquareError is one of these
String message;
int toastLength = Toast.LENGTH_SHORT;
if (e.getMessage() == null) {
message = "Invalid Request";
} else {
message = e.getMessage();
toastLength = Toast.LENGTH_LONG;
}
Toast.makeText(context, message, toastLength).show();
} else {
Toast.makeText(context, "A surprising new problem has occured. Try again!",
Toast.LENGTH_SHORT).show();
DumpcatcherHelper.sendException(e);
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.LinearLayout;
/**
* Renders the result of a checkin using a CheckinResult object. This is called
* from CheckinExecuteActivity. It would be nicer to put this in another activity,
* but right now the CheckinResult is quite large and would require a good amount
* of work to add serializers for all its inner classes. This wouldn't be a huge
* problem, but maintaining it as the classes evolve could more trouble than it's
* worth.
*
* The only way the user can dismiss this dialog is by hitting the 'back' key.
* CheckingExecuteActivity depends on this so it knows when to finish() itself.
*
* @date March 3, 2010.
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*
*/
public class WebViewDialog extends Dialog
{
private WebView mWebView;
private String mTitle;
private String mContent;
public WebViewDialog(Context context, String title, String content) {
super(context, R.style.ThemeCustomDlgBase_ThemeCustomDlg);
mTitle = title;
mContent = content;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_dialog);
setTitle(mTitle);
mWebView = (WebView)findViewById(R.id.webView);
mWebView.loadDataWithBaseURL("--", mContent, "text/html", "utf-8", "");
LinearLayout llMain = (LinearLayout)findViewById(R.id.llMain);
inflateDialog(llMain);
}
/**
* Force-inflates a dialog main linear-layout to take max available screen space even though
* contents might not occupy full screen size.
*/
public static void inflateDialog(LinearLayout layout) {
WindowManager wm = (WindowManager) layout.getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
layout.setMinimumWidth(display.getWidth() - 30);
layout.setMinimumHeight(display.getHeight() - 40);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.StringFormatters;
/**
* Lets the user add a tip to a venue.
*
* @date September 16, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class AddTipActivity extends Activity {
private static final String TAG = "AddTipActivity";
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".AddTipActivity.INTENT_EXTRA_VENUE";
public static final String EXTRA_TIP_RETURNED = Foursquared.PACKAGE_NAME
+ ".AddTipActivity.EXTRA_TIP_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_tip_activity);
StateHolder holder = (StateHolder) getLastNonConfigurationInstance();
if (holder != null) {
mStateHolder = holder;
mStateHolder.setActivityForTasks(this);
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE));
} else {
Log.e(TAG, "AddTipActivity must be given a venue parcel as intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTasks(null);
return mStateHolder;
}
private void ensureUi() {
TextView tvVenueName = (TextView)findViewById(R.id.addTipActivityVenueName);
tvVenueName.setText(mStateHolder.getVenue().getName());
TextView tvVenueAddress = (TextView)findViewById(R.id.addTipActivityVenueAddress);
tvVenueAddress.setText(StringFormatters.getVenueLocationCrossStreetOrCity(
mStateHolder.getVenue()));
Button btn = (Button) findViewById(R.id.addTipActivityButton);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.addTipActivityText);
String text = et.getText().toString();
if (!TextUtils.isEmpty(text)) {
mStateHolder.startTaskAddTip(AddTipActivity.this, mStateHolder.getVenue().getId(), text);
} else {
Toast.makeText(AddTipActivity.this, text, Toast.LENGTH_SHORT).show();
}
}
});
if (mStateHolder.getIsRunningTaskVenue()) {
startProgressBar();
}
}
private void startProgressBar() {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, "",
getResources().getString(R.string.add_tip_todo_activity_progress_message));
mDlgProgress.setCancelable(true);
mDlgProgress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Log.e(TAG, "User cancelled add tip.");
mStateHolder.cancelTasks();
}
});
}
mDlgProgress.show();
setProgressBarIndeterminateVisibility(true);
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
setProgressBarIndeterminateVisibility(false);
}
private static class TaskAddTip extends AsyncTask<Void, Void, Tip> {
private AddTipActivity mActivity;
private String mVenueId;
private String mTipText;
private Exception mReason;
public TaskAddTip(AddTipActivity activity, String venueId, String tipText) {
mActivity = activity;
mVenueId = venueId;
mTipText = tipText;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected Tip doInBackground(Void... params) {
try {
// The returned tip won't have the user object or venue attached to it
// as part of the response. The venue is the parent venue and the user
// is the logged-in user.
Foursquared foursquared = (Foursquared)mActivity.getApplication();
Tip tip = foursquared.getFoursquare().addTip(
mVenueId, mTipText, "tip",
LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
// So fetch the full tip for convenience.
Tip tipFull = foursquared.getFoursquare().tipDetail(tip.getId());
return tipFull;
} catch (Exception e) {
Log.e(TAG, "Error adding tip.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Tip tip) {
mActivity.stopProgressBar();
mActivity.mStateHolder.setIsRunningTaskAddTip(false);
if (tip != null) {
Intent intent = new Intent();
intent.putExtra(EXTRA_TIP_RETURNED, tip);
mActivity.setResult(Activity.RESULT_OK, intent);
mActivity.finish();
} else {
NotificationsUtil.ToastReasonForFailure(mActivity, mReason);
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
}
@Override
protected void onCancelled() {
mActivity.stopProgressBar();
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
public void setActivity(AddTipActivity activity) {
mActivity = activity;
}
}
private static final class StateHolder {
private Venue mVenue;
private TaskAddTip mTaskAddTip;
private boolean mIsRunningTaskAddTip;
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
}
public boolean getIsRunningTaskVenue() {
return mIsRunningTaskAddTip;
}
public void setIsRunningTaskAddTip(boolean isRunningTaskAddTip) {
mIsRunningTaskAddTip = isRunningTaskAddTip;
}
public void startTaskAddTip(AddTipActivity activity, String venueId, String text) {
mIsRunningTaskAddTip = true;
mTaskAddTip = new TaskAddTip(activity, venueId, text);
mTaskAddTip.execute();
}
public void setActivityForTasks(AddTipActivity activity) {
if (mTaskAddTip != null) {
mTaskAddTip.setActivity(activity);
}
}
public void cancelTasks() {
if (mTaskAddTip != null) {
mTaskAddTip.cancel(true);
}
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
/**
* Can be called to execute a checkin. Should be presented with the transparent
* dialog theme to appear only as a progress bar. When execution is complete, a
* successful checkin will show an instance of CheckinResultDialog to handle
* rendering the CheckinResult response object. A failed checkin will show a
* toast with the error message. Ideally we could launch another activity for
* rendering the result, but passing the CheckinResult between activities using
* the extras data will have to be done when we have more time.
*
* For the location paramters of the checkin method, this activity will grab the
* global last-known best location.
*
* The activity will setResult(RESULT_OK) if the checkin worked, and will
* setResult(RESULT_CANCELED) if it did not work.
*
* @date March 2, 2010
* @author Mark Wyszomierski (markww@gmail.com).
*/
public class CheckinExecuteActivity extends Activity {
public static final String TAG = "CheckinExecuteActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_VENUE_ID = Foursquared.PACKAGE_NAME
+ ".CheckinExecuteActivity.INTENT_EXTRA_VENUE_ID";
public static final String INTENT_EXTRA_SHOUT = Foursquared.PACKAGE_NAME
+ ".CheckinExecuteActivity.INTENT_EXTRA_SHOUT";
public static final String INTENT_EXTRA_TELL_FRIENDS = Foursquared.PACKAGE_NAME
+ ".CheckinExecuteActivity.INTENT_EXTRA_TELL_FRIENDS";
public static final String INTENT_EXTRA_TELL_FOLLOWERS = Foursquared.PACKAGE_NAME
+ ".CheckinExecuteActivity.INTENT_EXTRA_TELL_FOLLOWERS";
public static final String INTENT_EXTRA_TELL_TWITTER = Foursquared.PACKAGE_NAME
+ ".CheckinExecuteActivity.INTENT_EXTRA_TELL_TWITTER";
public static final String INTENT_EXTRA_TELL_FACEBOOK = Foursquared.PACKAGE_NAME
+ ".CheckinExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK";
private static final int DIALOG_CHECKIN_RESULT = 1;
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.checkin_execute_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
// We start the checkin immediately on creation.
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
mStateHolder = new StateHolder();
String venueId = null;
if (getIntent().getExtras().containsKey(INTENT_EXTRA_VENUE_ID)) {
venueId = getIntent().getExtras().getString(INTENT_EXTRA_VENUE_ID);
} else {
Log.e(TAG, "CheckinExecuteActivity requires intent extra 'INTENT_EXTRA_VENUE_ID'.");
finish();
return;
}
Foursquared foursquared = (Foursquared) getApplication();
Location location = foursquared.getLastKnownLocation();
mStateHolder.startTask(
CheckinExecuteActivity.this,
venueId,
location,
getIntent().getExtras().getString(INTENT_EXTRA_SHOUT),
getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FRIENDS, false),
getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FOLLOWERS, false),
getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_TWITTER, false),
getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FACEBOOK, false)
);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
@Override
public void onResume() {
super.onResume();
if (mStateHolder.getIsRunning()) {
startProgressBar(getResources().getString(R.string.checkin_action_label),
getResources().getString(R.string.checkin_execute_activity_progress_bar_message));
}
}
@Override
public void onPause() {
super.onPause();
stopProgressBar();
if (isFinishing()) {
mStateHolder.cancelTasks();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
private void startProgressBar(String title, String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, title, message);
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_CHECKIN_RESULT:
// When the user cancels the dialog (by hitting the 'back' key), we
// finish this activity. We don't listen to onDismiss() for this
// action, because a device rotation will fire onDismiss(), and our
// dialog would not be re-displayed after the rotation is complete.
CheckinResultDialog dlg = new CheckinResultDialog(
this,
mStateHolder.getCheckinResult(),
((Foursquared)getApplication()));
dlg.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
removeDialog(DIALOG_CHECKIN_RESULT);
setResult(Activity.RESULT_OK);
finish();
}
});
return dlg;
}
return null;
}
private void onCheckinComplete(CheckinResult result, Exception ex) {
mStateHolder.setIsRunning(false);
stopProgressBar();
if (result != null) {
mStateHolder.setCheckinResult(result);
showDialog(DIALOG_CHECKIN_RESULT);
} else {
NotificationsUtil.ToastReasonForFailure(this, ex);
setResult(Activity.RESULT_CANCELED);
finish();
}
}
private static class CheckinTask extends AsyncTask<Void, Void, CheckinResult> {
private CheckinExecuteActivity mActivity;
private String mVenueId;
private Location mLocation;
private String mShout;
private boolean mTellFriends;
private boolean mTellFollowers;
private boolean mTellTwitter;
private boolean mTellFacebook;
private Exception mReason;
public CheckinTask(CheckinExecuteActivity activity,
String venueId,
Location location,
String shout,
boolean tellFriends,
boolean tellFollowers,
boolean tellTwitter,
boolean tellFacebook) {
mActivity = activity;
mVenueId = venueId;
mLocation = location;
mShout = shout;
mTellFriends = tellFriends;
mTellFollowers = tellFollowers;
mTellTwitter = tellTwitter;
mTellFacebook = tellFacebook;
}
public void setActivity(CheckinExecuteActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar(mActivity.getResources().getString(
R.string.checkin_action_label), mActivity.getResources().getString(
R.string.checkin_execute_activity_progress_bar_message));
}
@Override
protected CheckinResult doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
CheckinResult result =
foursquare.checkin(
mVenueId,
null, // passing in the real venue name causes a 400 response from the server.
LocationUtils.createFoursquareLocation(mLocation),
mShout,
!mTellFriends, // (isPrivate)
mTellFollowers,
mTellTwitter,
mTellFacebook);
// Here we should really be downloading the mayor's photo serially, so that this
// work is done in the background while the progress bar is already spinning.
// When the checkin result dialog pops up, the photo would already be loaded.
// We can at least start the request if necessary here in the background thread.
if (result != null && result.getMayor() != null && result.getMayor().getUser() != null) {
if (result.getMayor() != null && result.getMayor().getUser() != null) {
Uri photoUri = Uri.parse(result.getMayor().getUser().getPhoto());
RemoteResourceManager rrm = foursquared.getRemoteResourceManager();
if (rrm.exists(photoUri) == false) {
rrm.request(photoUri);
}
}
}
return result;
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "CheckinTask: Exception checking in.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(CheckinResult result) {
if (DEBUG) Log.d(TAG, "CheckinTask: onPostExecute()");
if (mActivity != null) {
mActivity.onCheckinComplete(result, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onCheckinComplete(null, new FoursquareException(
"Check-in cancelled."));
}
}
}
private static class StateHolder {
private CheckinTask mTask;
private CheckinResult mCheckinResult;
private boolean mIsRunning;
public StateHolder() {
mCheckinResult = null;
mIsRunning = false;
}
public void startTask(CheckinExecuteActivity activity,
String venueId,
Location location,
String shout,
boolean tellFriends,
boolean tellFollowers,
boolean tellTwitter,
boolean tellFacebook) {
mIsRunning = true;
mTask = new CheckinTask(
activity, venueId, location, shout, tellFriends,
tellFollowers, tellTwitter, tellFacebook);
mTask.execute();
}
public void setActivity(CheckinExecuteActivity activity) {
if (mTask != null) {
mTask.setActivity(activity);
}
}
public boolean getIsRunning() {
return mIsRunning;
}
public void setIsRunning(boolean isRunning) {
mIsRunning = isRunning;
}
public CheckinResult getCheckinResult() {
return mCheckinResult;
}
public void setCheckinResult(CheckinResult result) {
mCheckinResult = result;
}
public void cancelTasks() {
if (mTask != null && mIsRunning) {
mTask.setActivity(null);
mTask.cancel(true);
}
}
}
}
| Java |
/*
* Copyright 2010 Mark Wyszomierski
* Portions Copyright (c) 2008-2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import android.os.Bundle;
import android.text.TextUtils;
import java.io.IOException;
import java.net.MalformedURLException;
/**
* Main Facebook object for storing session token and session expiration date
* in memory, as well as generating urls to access different facebook endpoints.
*
* @author Steven Soneff (ssoneff@facebook.com):
* -original author.
* @author Mark Wyszomierski (markww@gmail.com):
* -modified to remove network operation calls, and dialog creation,
* focused on making this class only generate urls for external use
* and storage of a session token and expiration date.
*/
public class Facebook {
/** Strings used in the OAuth flow */
public static final String REDIRECT_URI = "fbconnect://success";
public static final String CANCEL_URI = "fbconnect:cancel";
public static final String TOKEN = "access_token";
public static final String EXPIRES = "expires_in";
/** Login action requires a few extra steps for setup and completion. */
public static final String LOGIN = "login";
/** Facebook server endpoints: may be modified in a subclass for testing */
protected static String OAUTH_ENDPOINT =
"https://graph.facebook.com/oauth/authorize"; // https
protected static String UI_SERVER =
"http://www.facebook.com/connect/uiserver.php"; // http
protected static String GRAPH_BASE_URL =
"https://graph.facebook.com/";
protected static String RESTSERVER_URL =
"https://api.facebook.com/restserver.php";
private String mAccessToken = null;
private long mAccessExpires = 0;
public Facebook() {
}
/**
* Invalidates the current access token in memory, and generates a
* prepared URL that can be used to log the user out.
*
* @throws MalformedURLException
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl logout()
throws MalformedURLException, IOException
{
setAccessToken(null);
setAccessExpires(0);
Bundle b = new Bundle();
b.putString("method", "auth.expireSession");
return requestUrl(b);
}
/**
* Build a url to Facebook's old (pre-graph) API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
*
* See http://developers.facebook.com/docs/reference/rest/
*
* Example:
* <code>
* Bundle parameters = new Bundle();
* parameters.putString("method", "auth.expireSession");
* PreparedUrl preparedUrl = requestUrl(parameters);
* </code>
*
* @param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* @throws MalformedURLException
* if accessing an invalid endpoint
* @throws IllegalArgumentException
* if one of the parameters is not "method"
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl requestUrl(Bundle parameters)
throws MalformedURLException {
if (!parameters.containsKey("method")) {
throw new IllegalArgumentException("API method must be specified. "
+ "(parameters must contain key \"method\" and value). See"
+ " http://developers.facebook.com/docs/reference/rest/");
}
return requestUrl(null, parameters, "GET");
}
/**
* Build a url to the Facebook Graph API without any parameters.
*
* See http://developers.facebook.com/docs/api
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @throws MalformedURLException
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl requestUrl(String graphPath)
throws MalformedURLException {
return requestUrl(graphPath, new Bundle(), "GET");
}
/**
* Build a url to the Facebook Graph API with the given string
* parameters using an HTTP GET (default method).
*
* See http://developers.facebook.com/docs/api
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters "q" : "facebook" would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @throws MalformedURLException
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl requestUrl(String graphPath, Bundle parameters)
throws MalformedURLException {
return requestUrl(graphPath, parameters, "GET");
}
/**
* Build a PreparedUrl object which can be used with Util.openUrl().
* You can also use the returned PreparedUrl.getUrl() to run the
* network operation yourself.
*
* Note that binary data parameters
* (e.g. pictures) are not yet supported by this helper function.
*
* See http://developers.facebook.com/docs/api
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters {"q" : "facebook"} would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @param httpMethod
* http verb, e.g. "GET", "POST", "DELETE"
* @throws MalformedURLException
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl requestUrl(String graphPath,
Bundle parameters,
String httpMethod)
throws MalformedURLException
{
parameters.putString("format", "json");
if (isSessionValid()) {
parameters.putString(TOKEN, getAccessToken());
}
String url = graphPath != null ?
GRAPH_BASE_URL + graphPath :
RESTSERVER_URL;
return new PreparedUrl(url, parameters, httpMethod);
}
public boolean isSessionValid() {
return (getAccessToken() != null) && ((getAccessExpires() == 0) ||
(System.currentTimeMillis() < getAccessExpires()));
}
public String getAccessToken() {
return mAccessToken;
}
public long getAccessExpires() {
return mAccessExpires;
}
public void setAccessToken(String token) {
mAccessToken = token;
}
public void setAccessExpires(long time) {
mAccessExpires = time;
}
public void setAccessExpiresIn(String expiresIn) {
if (expiresIn != null) {
setAccessExpires(System.currentTimeMillis()
+ Integer.parseInt(expiresIn) * 1000);
}
}
public String generateUrl(String action, String appId, String[] permissions) {
Bundle params = new Bundle();
String endpoint;
if (action.equals(LOGIN)) {
params.putString("client_id", appId);
if (permissions != null && permissions.length > 0) {
params.putString("scope", TextUtils.join(",", permissions));
}
endpoint = OAUTH_ENDPOINT;
params.putString("type", "user_agent");
params.putString("redirect_uri", REDIRECT_URI);
} else {
endpoint = UI_SERVER;
params.putString("method", action);
params.putString("next", REDIRECT_URI);
}
params.putString("display", "touch");
params.putString("sdk", "android");
if (isSessionValid()) {
params.putString(TOKEN, getAccessToken());
}
String url = endpoint + "?" + FacebookUtil.encodeUrl(params);
return url;
}
/**
* Stores a prepared url and parameters bundle from one of the <code>requestUrl</code>
* methods. It can then be used with Util.openUrl() to run the network operation.
* The Util.openUrl() requires the original params bundle and http method, so this
* is just a convenience wrapper around it.
*
* @author Mark Wyszomierski (markww@gmail.com)
*/
public static class PreparedUrl
{
private String mUrl;
private Bundle mParameters;
private String mHttpMethod;
public PreparedUrl(String url, Bundle parameters, String httpMethod) {
mUrl = url;
mParameters = parameters;
mHttpMethod = httpMethod;
}
public String getUrl() {
return mUrl;
}
public Bundle getParameters() {
return mParameters;
}
public String getHttpMethod() {
return mHttpMethod;
}
}
} | Java |
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
/**
* Encapsulation of a Facebook Error: a Facebook request that could not be
* fulfilled.
*
* @author ssoneff@facebook.com
*/
public class FacebookError extends Throwable {
private static final long serialVersionUID = 1L;
private int mErrorCode = 0;
private String mErrorType;
public FacebookError(String message) {
super(message);
}
public FacebookError(String message, String type, int code) {
super(message);
mErrorType = type;
mErrorCode = code;
}
public int getErrorCode() {
return mErrorCode;
}
public String getErrorType() {
return mErrorType;
}
} | Java |
/*
* Copyright 2010 Mark Wyszomierski
* Portions Copyright (c) 2008-2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
/**
* Utility class supporting the Facebook Object.
*
* @author ssoneff@facebook.com
* -original author.
* @author Mark Wyszomierski (markww@gmail.com):
* -just removed alert dialog method which can be handled by managed
* dialogs in third party apps.
*/
public final class FacebookUtil {
public static String encodeUrl(Bundle parameters) {
if (parameters == null) {
return "";
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String key : parameters.keySet()) {
if (first) first = false; else sb.append("&");
sb.append(key + "=" + parameters.getString(key));
}
return sb.toString();
}
public static Bundle decodeUrl(String s) {
Bundle params = new Bundle();
if (s != null) {
String array[] = s.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
params.putString(v[0], v[1]);
}
}
return params;
}
/**
* Parse a URL query and fragment parameters into a key-value bundle.
*
* @param url the URL to parse
* @return a dictionary bundle of keys and values
*/
public static Bundle parseUrl(String url) {
// hack to prevent MalformedURLException
url = url.replace("fbconnect", "http");
try {
URL u = new URL(url);
Bundle b = decodeUrl(u.getQuery());
b.putAll(decodeUrl(u.getRef()));
return b;
} catch (MalformedURLException e) {
return new Bundle();
}
}
/**
* Connect to an HTTP URL and return the response as a string.
*
* Note that the HTTP method override is used on non-GET requests. (i.e.
* requests are made as "POST" with method specified in the body).
*
* @param url - the resource to open: must be a welformed URL
* @param method - the HTTP method to use ("GET", "POST", etc.)
* @param params - the query parameter for the URL (e.g. access_token=foo)
* @return the URL contents as a String
* @throws MalformedURLException - if the URL format is invalid
* @throws IOException - if a network problem occurs
*/
public static String openUrl(String url, String method, Bundle params)
throws MalformedURLException, IOException {
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
}
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("User-Agent", System.getProperties().
getProperty("http.agent") + " FacebookAndroidSDK");
if (!method.equals("GET")) {
// use method override
params.putString("method", method);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.getOutputStream().write(
encodeUrl(params).getBytes("UTF-8"));
}
String response = "";
try {
response = read(conn.getInputStream());
} catch (FileNotFoundException e) {
// Error Stream contains JSON that we can parse to a FB error
response = read(conn.getErrorStream());
}
return response;
}
private static String read(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}
in.close();
return sb.toString();
}
/**
* Parse a server response into a JSON Object. This is a basic
* implementation using org.json.JSONObject representation. More
* sophisticated applications may wish to do their own parsing.
*
* The parsed JSON is checked for a variety of error fields and
* a FacebookException is thrown if an error condition is set,
* populated with the error message and error type or code if
* available.
*
* @param response - string representation of the response
* @return the response as a JSON Object
* @throws JSONException - if the response is not valid JSON
* @throws FacebookError - if an error condition is set
*/
public static JSONObject parseJson(String response)
throws JSONException, FacebookError {
// Edge case: when sending a POST request to /[post_id]/likes
// the return value is 'true' or 'false'. Unfortunately
// these values cause the JSONObject constructor to throw
// an exception.
if (response.equals("false")) {
throw new FacebookError("request failed");
}
if (response.equals("true")) {
response = "{value : true}";
}
JSONObject json = new JSONObject(response);
// errors set by the server are not consistent
// they depend on the method and endpoint
if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
throw new FacebookError(
error.getString("message"), error.getString("type"), 0);
}
if (json.has("error_code") && json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"), "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_code")) {
throw new FacebookError("request failed", "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"));
}
if (json.has("error_reason")) {
throw new FacebookError(json.getString("error_reason"));
}
return json;
}
public static String printBundle(Bundle bundle) {
StringBuilder sb = new StringBuilder();
sb.append("Bundle: ");
if (bundle != null) {
sb.append(bundle.toString()); sb.append("\n");
Set<String> keys = bundle.keySet();
for (String it : keys) {
sb.append(" ");
sb.append(it);
sb.append(": ");
sb.append(bundle.get(it).toString());
sb.append("\n");
}
} else {
sb.append("(null)");
}
return sb.toString();
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*
* 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.facebook.android;
import com.joelapenna.foursquared.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* This activity can be used to run a facebook url request through a webview.
* The user must supply these intent extras:
* <ul>
* <li>INTENT_EXTRA_ACTION - string, which facebook action to perform, like
* "login", or "stream.publish".</li>
* <li>INTENT_EXTRA_KEY_APP_ID - string, facebook developer key.</li>
* <li>INTENT_EXTRA_KEY_PERMISSIONS - string array, set of facebook permissions
* you want to use.</li>
* </ul>
* or you can supply only INTENT_EXTRA_KEY_CLEAR_COOKIES to just have the
* activity clear its stored cookies (you can also supply it in combination with
* the above flags to clear cookies before trying to run a request too). If
* you've already authenticated the user, you can optionally pass in the token
* and expiration time as intent extras using:
* <ul>
* <li>INTENT_EXTRA_AUTHENTICATED_TOKEN</li>
* <li>INTENT_EXTRA_AUTHENTICATED_EXPIRES</li>
* </ul>
* they will then be used in web requests. You should use
* <code>startActivityForResult</code> to start the activity. When the activity
* finishes, it will return status code RESULT_OK. You can then check the
* returned intent data object for:
* <ul>
* <li>INTENT_RESULT_KEY_RESULT_STATUS - boolean, whether the request succeeded
* or not.</li>
* <li>INTENT_RESULT_KEY_SUPPLIED_ACTION - string, the action you supplied as an
* intent extra echoed back as a convenience.</li>
* <li>INTENT_RESULT_KEY_RESULT_BUNDLE - bundle, present if request succeeded,
* will have all the returned parameters as supplied by the WebView operation.</li>
* <li>INTENT_RESULT_KEY_ERROR - string, present if request failed.</li>
* </ul>
* If the user canceled this activity, the activity result code will be
* RESULT_CANCELED and there will be no intent data returned. You need the
* <code>android.permission.INTERNET</code> permission added to your manifest.
* You need to add this activity definition to your manifest. You can prevent
* this activity from restarting on rotation so the network operations are
* preserved within the WebView like so:
*
* <activity
* android:name="com.facebook.android.FacebookWebViewActivity"
* android:configChanges="orientation|keyboardHidden" />
*
* This class and the rest of the facebook classes within this package are from
* the facebook android library project:
*
* http://github.com/facebook/facebook-android-sdk
*
* The project implementation had several problems with it which made it unusable
* in a production application. It has been rewritten here for use with the
* Foursquare project.
*
* @date June 14, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class FacebookWebViewActivity extends Activity {
private static final String TAG = "FacebookWebViewActivity";
public static final String INTENT_EXTRA_ACTION = "com.facebook.android.FacebookWebViewActivity.action";
public static final String INTENT_EXTRA_KEY_APP_ID = "com.facebook.android.FacebookWebViewActivity.appid";
public static final String INTENT_EXTRA_KEY_PERMISSIONS = "com.facebook.android.FacebookWebViewActivity.permissions";
public static final String INTENT_EXTRA_AUTHENTICATED_TOKEN = "com.facebook.android.FacebookWebViewActivity.authenticated_token";
public static final String INTENT_EXTRA_AUTHENTICATED_EXPIRES = "com.facebook.android.FacebookWebViewActivity.authenticated_expires";
public static final String INTENT_EXTRA_KEY_CLEAR_COOKIES = "com.facebook.android.FacebookWebViewActivity.clear_cookies";
public static final String INTENT_EXTRA_KEY_DEBUG = "com.facebook.android.FacebookWebViewActivity.debug";
public static final String INTENT_RESULT_KEY_RESULT_STATUS = "result_status";
public static final String INTENT_RESULT_KEY_SUPPLIED_ACTION = "supplied_action";
public static final String INTENT_RESULT_KEY_RESULT_BUNDLE = "bundle";
public static final String INTENT_RESULT_KEY_ERROR = "error";
private static final String DISPLAY_STRING = "touch";
private static final int FB_BLUE = 0xFF6D84B4;
private static final int MARGIN = 4;
private static final int PADDING = 2;
private TextView mTitle;
private WebView mWebView;
private ProgressDialog mSpinner;
private String mAction;
private String mAppId;
private String[] mPermissions;
private boolean mDebug;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
CookieSyncManager.createInstance(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mTitle = new TextView(this);
mTitle.setText("Facebook");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(FB_BLUE);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(this.getResources().getDrawable(
R.drawable.facebook_icon), null, null, null);
ll.addView(mTitle);
mWebView = new WebView(this);
mWebView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mWebView.setWebViewClient(new WebViewClientFacebook());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.getSettings().setJavaScriptEnabled(true);
ll.addView(mWebView);
mSpinner = new ProgressDialog(this);
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
setContentView(ll, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey(INTENT_EXTRA_KEY_DEBUG)) {
mDebug = extras.getBoolean(INTENT_EXTRA_KEY_DEBUG);
}
if (extras.containsKey(INTENT_EXTRA_ACTION)) {
if (extras.getBoolean(INTENT_EXTRA_KEY_CLEAR_COOKIES, false)) {
clearCookies();
}
if (extras.containsKey(INTENT_EXTRA_KEY_APP_ID)) {
if (extras.containsKey(INTENT_EXTRA_KEY_PERMISSIONS)) {
mAction = extras.getString(INTENT_EXTRA_ACTION);
mAppId = extras.getString(INTENT_EXTRA_KEY_APP_ID);
mPermissions = extras.getStringArray(INTENT_EXTRA_KEY_PERMISSIONS);
// If the user supplied a pre-authenticated info, use it
// here.
Facebook facebook = new Facebook();
if (extras.containsKey(INTENT_EXTRA_AUTHENTICATED_TOKEN) &&
extras.containsKey(INTENT_EXTRA_AUTHENTICATED_EXPIRES)) {
facebook.setAccessToken(extras
.getString(INTENT_EXTRA_AUTHENTICATED_TOKEN));
facebook.setAccessExpires(extras
.getLong(INTENT_EXTRA_AUTHENTICATED_EXPIRES));
if (mDebug) {
Log.d(TAG, "onCreate(): authenticated token being used.");
}
}
// Generate the url based on the action.
String url = facebook.generateUrl(mAction, mAppId, mPermissions);
if (mDebug) {
String permissionsDump = "(null)";
if (mPermissions != null) {
if (mPermissions.length > 0) {
for (int i = 0; i < mPermissions.length; i++) {
permissionsDump += mPermissions[i] + ", ";
}
} else {
permissionsDump = "[empty]";
}
}
Log.d(TAG, "onCreate(): action: " + mAction + ", appid: " + mAppId
+ ", permissions: " + permissionsDump);
Log.d(TAG, "onCreate(): Loading url: " + url);
}
// Start the request finally.
mWebView.loadUrl(url);
} else {
Log.e(TAG, "Missing intent extra: INTENT_EXTRA_KEY_PERMISSIONS, finishing immediately.");
finish();
}
} else {
Log.e(TAG, "Missing intent extra: INTENT_EXTRA_KEY_APP_ID, finishing immediately.");
finish();
}
} else if (extras.getBoolean(INTENT_EXTRA_KEY_CLEAR_COOKIES)) {
clearCookies();
} else {
Log.e(TAG, "Missing intent extra: INTENT_EXTRA_ACTION or INTENT_EXTRA_KEY_CLEAR_COOKIES, finishing immediately.");
finish();
}
} else {
Log.e(TAG, "No intent extras supplied, finishing immediately.");
finish();
}
}
private void clearCookies() {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
@Override
protected void onResume() {
super.onResume();
CookieSyncManager.getInstance().startSync();
}
@Override
protected void onPause() {
super.onPause();
CookieSyncManager.getInstance().stopSync();
}
private class WebViewClientFacebook extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mDebug) {
Log.d(TAG, "WebViewClientFacebook:shouldOverrideUrlLoading(): " + url);
}
if (url.startsWith(Facebook.REDIRECT_URI)) {
Bundle values = FacebookUtil.parseUrl(url);
String error = values.getString("error_reason");
Intent result = new Intent();
result.putExtra(INTENT_RESULT_KEY_SUPPLIED_ACTION, mAction);
if (error == null) {
CookieSyncManager.getInstance().sync();
result.putExtra(INTENT_RESULT_KEY_RESULT_STATUS, true);
result.putExtra(INTENT_RESULT_KEY_RESULT_BUNDLE, values);
FacebookWebViewActivity.this.setResult(Activity.RESULT_OK, result);
} else {
result.putExtra(INTENT_RESULT_KEY_RESULT_STATUS, false);
result.putExtra(INTENT_RESULT_KEY_SUPPLIED_ACTION, mAction);
result.putExtra(INTENT_RESULT_KEY_ERROR, error);
FacebookWebViewActivity.this.setResult(Activity.RESULT_OK, result);
}
FacebookWebViewActivity.this.finish();
return true;
} else if (url.startsWith(Facebook.CANCEL_URI)) {
FacebookWebViewActivity.this.setResult(Activity.RESULT_CANCELED);
FacebookWebViewActivity.this.finish();
return true;
} else if (url.contains(DISPLAY_STRING)) {
return false;
}
// Launch non-dialog URLs in a full browser.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
if (mDebug) {
Log.e(TAG, "WebViewClientFacebook:onReceivedError(): " + errorCode + ", "
+ description + ", " + failingUrl);
}
Intent result = new Intent();
result.putExtra(INTENT_RESULT_KEY_RESULT_STATUS, false);
result.putExtra(INTENT_RESULT_KEY_SUPPLIED_ACTION, mAction);
result.putExtra(INTENT_RESULT_KEY_ERROR, description + ", " + errorCode + ", "
+ failingUrl);
FacebookWebViewActivity.this.setResult(Activity.RESULT_OK, result);
FacebookWebViewActivity.this.finish();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (mDebug) {
Log.d(TAG, "WebViewClientFacebook:onPageStarted(): " + url);
}
mSpinner.show();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mDebug) {
Log.d(TAG, "WebViewClientFacebook:onPageFinished(): " + url);
}
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare;
public class TestCredentials {
public static final String oAuthConsumerKey = "";
public static final String oAuthConsumerSecret = "";
public static final String oAuthToken = "";
public static final String oAuthTokenSecret = "";
public static final String testFoursquarePhone = "";
public static final String testFoursquarePassword = "";
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquaredSettings {
public static final boolean USE_DEBUG_SERVER = false;
public static final boolean DEBUG = false;
public static final boolean LOCATION_DEBUG = false;
public static final boolean USE_DUMPCATCHER = true;
public static final boolean DUMPCATCHER_TEST = false;
}
| Java |
package com.google.code.apndroid.apisample;
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.view.View;
import android.widget.CheckBox;
import android.widget.ToggleButton;
public class NewApiActivity extends Activity {
private ToggleButton mToggle;
private CheckBox mMmsCheckbBox;
private BroadcastReceiver mReceiver;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.switch_screen);
mToggle = (ToggleButton) findViewById(R.id.btn_switch);
mMmsCheckbBox = (CheckBox) findViewById(R.id.btn_checkbox);
// receiver that updates UI according to Apndroid switch state
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("apndroid.intent.action.STATUS")) {
boolean dataEnabled = intent.getBooleanExtra("apndroid.intent.extra.STATUS", true);
mToggle.setChecked(dataEnabled);
}
}
};
mToggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent("apndroid.intent.action.CHANGE_STATUS");
intent.putExtra("apndroid.intent.extra.STATUS", mToggle.isChecked());
intent.putExtra("apndroid.intent.extra.KEEP_MMS_ON", mMmsCheckbBox.isChecked());
startService(intent);
}
});
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, new IntentFilter("apndroid.intent.action.STATUS"));
// request switch state
startService(new Intent("apndroid.intent.action.GET_STATUS"));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
} | Java |
package com.google.code.apndroid.apisample;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ToggleButton;
public class OldApiActivity extends Activity {
private static final int GET_STATE_REQUEST = 1;
private static final int CHANGE_STATE_REQUEST = 2;
private ToggleButton mToggle;
private CheckBox mMmsCheckbBox;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.switch_screen);
mToggle = (ToggleButton) findViewById(R.id.btn_switch);
mMmsCheckbBox = (CheckBox) findViewById(R.id.btn_checkbox);
mToggle.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent("com.google.code.apndroid.intent.action.CHANGE_REQUEST");
intent.putExtra("com.google.code.apndroid.intent.extra.TARGET_STATE", mToggle.isChecked());
intent.putExtra("com.google.code.apndroid.intent.extra.TARGET_MMS_STATE", mMmsCheckbBox.isChecked());
startActivityForResult(intent, CHANGE_STATE_REQUEST);
}
});
// request switch state
startActivityForResult(new Intent("com.google.code.apndroid.intent.action.STATUS_REQUEST"), GET_STATE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == GET_STATE_REQUEST && resultCode == RESULT_OK && intent != null) {
if (intent.getAction().equals("com.google.code.apndroid.intent.REQUEST_RESULT")) {
boolean dataEnabled = (intent.getIntExtra("APN_STATE", 1) == 1);
mToggle.setChecked(dataEnabled);
}
}
}
} | Java |
package com.google.code.apndroid.apisample;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btnNewApi).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, NewApiActivity.class));
}
});
findViewById(R.id.btnOldApi).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, OldApiActivity.class));
}
});
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.services.TrackRecordingService;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.test.AndroidTestCase;
import java.util.List;
/**
* Tests for the BootReceiver.
*
* @author Youtao Liu
*/
public class BootReceiverTest extends AndroidTestCase {
private static final String SERVICE_NAME = "com.google.android.apps.mytracks.services.TrackRecordingService";
/**
* Tests the behavior when receive notification which is the phone boot.
*/
public void testOnReceive_startService() {
// Make sure no TrackRecordingService
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
getContext().stopService(stopIntent);
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
BootReceiver bootReceiver = new BootReceiver();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_BOOT_COMPLETED);
bootReceiver.onReceive(getContext(), intent);
// Check if the service is started
assertTrue(isServiceExisted(getContext(), SERVICE_NAME));
}
/**
* Tests the behavior when receive notification which is not the phone boot.
*/
public void testOnReceive_noStartService() {
// Make sure no TrackRecordingService
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
getContext().stopService(stopIntent);
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
BootReceiver bootReceiver = new BootReceiver();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_BUG_REPORT);
bootReceiver.onReceive(getContext(), intent);
// Check if the service is not started
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
}
/**
* Checks if a service is started in a context.
*
* @param context the context for checking a service
* @param serviceName the service name to find if existed
*/
private boolean isServiceExisted(Context context, String serviceName) {
ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
.getRunningServices(Integer.MAX_VALUE);
for (int i = 0; i < serviceList.size(); i++) {
RunningServiceInfo serviceInfo = serviceList.get(i);
ComponentName componentName = serviceInfo.service;
if (componentName.getClassName().equals(serviceName)) {
return true;
}
}
return false;
}
} | Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
/**
* Tests for the AntPreference.
*
* @author Youtao Liu
*/
public class AntPreferenceTest extends AndroidTestCase {
public void testNotPaired() {
AntPreference antPreference = new AntPreference(getContext()) {
@Override
protected int getPersistedInt(int defaultReturnValue) {
return 0;
}
};
assertEquals(getContext().getString(R.string.settings_sensor_ant_not_paired),
antPreference.getSummary());
}
public void testPaired() {
int persistInt = 1;
AntPreference antPreference = new AntPreference(getContext()) {
@Override
protected int getPersistedInt(int defaultReturnValue) {
return 1;
}
};
assertEquals(
getContext().getString(R.string.settings_sensor_ant_paired, persistInt),
antPreference.getSummary());
}
} | Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.maps.SingleColorTrackPathPainter;
import com.google.android.maps.MapView;
import android.graphics.Canvas;
import android.graphics.Path;
import android.location.Location;
import android.test.AndroidTestCase;
/**
* Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*/
public class MapOverlayTest extends AndroidTestCase {
private Canvas canvas;
private MockMyTracksOverlay myTracksOverlay;
private MapView mockView;
@Override
protected void setUp() throws Exception {
super.setUp();
canvas = new Canvas();
myTracksOverlay = new MockMyTracksOverlay(getContext());
// Enable drawing.
myTracksOverlay.setTrackDrawingEnabled(true);
// Set a TrackPathPainter with a MockPath.
myTracksOverlay.setTrackPathPainter(new SingleColorTrackPathPainter(getContext()) {
@Override
public Path newPath() {
return new MockPath();
}
});
mockView = null;
}
public void testAddLocation() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
location.setLatitude(20);
location.setLongitude(30);
myTracksOverlay.addLocation(location);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
// Draw and make sure that we don't lose any point.
myTracksOverlay.draw(canvas, mockView, false);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(2, path.totalPoints);
myTracksOverlay.draw(canvas, mockView, true);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
}
public void testClearPoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
// Same after drawing on canvas.
final int locations = 100;
for (int i = 0; i < locations; ++i) {
myTracksOverlay.addLocation(location);
}
assertEquals(locations, myTracksOverlay.getNumLocations());
myTracksOverlay.draw(canvas, mockView, false);
myTracksOverlay.draw(canvas, mockView, true);
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
}
public void testAddWaypoint() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
final int waypoints = 10;
for (int i = 0; i < waypoints; ++i) {
waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
assertEquals(1 + waypoints, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
}
public void testClearWaypoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
myTracksOverlay.clearWaypoints();
assertEquals(0, myTracksOverlay.getNumWaypoints());
}
public void testDrawing() {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 40; ++i) {
location.setLongitude(20 + i);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
}
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
// Shadow.
myTracksOverlay.draw(canvas, mockView, true);
// We don't expect to do anything if
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
// No shadow.
myTracksOverlay.draw(canvas, mockView, false);
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
assertEquals(100, path.totalPoints);
// TODO: Check the points from the path (and the segments).
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Tests {@link DefaultTrackNameFactory}
*
* @author Matthew Simmons
*/
public class DefaultTrackNameFactoryTest extends AndroidTestCase {
private static final long TRACK_ID = 1L;
private static final long START_TIME = 1288213406000L;
public void testDefaultTrackName_date_local() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_date_local_value);
}
};
assertEquals(StringUtils.formatDateTime(getContext(), START_TIME),
defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
public void testDefaultTrackName_date_iso_8601() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_date_iso_8601_value);
}
};
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
DefaultTrackNameFactory.ISO_8601_FORMAT);
assertEquals(simpleDateFormat.format(new Date(START_TIME)),
defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
public void testDefaultTrackName_number() {
DefaultTrackNameFactory defaultTrackNameFactory = new DefaultTrackNameFactory(getContext()) {
@Override
String getTrackNameSetting() {
return getContext().getString(R.string.settings_recording_track_name_number_value);
}
};
assertEquals(
"Track " + TRACK_ID, defaultTrackNameFactory.getDefaultTrackName(TRACK_ID, START_TIME));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.test.AndroidTestCase;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import org.easymock.Capture;
/**
* Tests for {@link StatusAnnouncerTask}.
* WARNING: I'm not responsible if your eyes start bleeding while reading this
* code. You have been warned. It's still better than no test, though.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerTaskTest extends AndroidTestCase {
// Use something other than our hardcoded value
private static final Locale DEFAULT_LOCALE = Locale.KOREAN;
private static final String ANNOUNCEMENT = "I can haz cheeseburger?";
private Locale oldDefaultLocale;
private StatusAnnouncerTask task;
private StatusAnnouncerTask mockTask;
private Capture<OnInitListener> initListenerCapture;
private Capture<PhoneStateListener> phoneListenerCapture;
private TextToSpeechDelegate ttsDelegate;
private TextToSpeechInterface tts;
/**
* Mockable interface that we delegate TTS calls to.
*/
interface TextToSpeechInterface {
int addEarcon(String earcon, String packagename, int resourceId);
int addEarcon(String earcon, String filename);
int addSpeech(String text, String packagename, int resourceId);
int addSpeech(String text, String filename);
boolean areDefaultsEnforced();
String getDefaultEngine();
Locale getLanguage();
int isLanguageAvailable(Locale loc);
boolean isSpeaking();
int playEarcon(String earcon, int queueMode,
HashMap<String, String> params);
int playSilence(long durationInMs, int queueMode,
HashMap<String, String> params);
int setEngineByPackageName(String enginePackageName);
int setLanguage(Locale loc);
int setOnUtteranceCompletedListener(OnUtteranceCompletedListener listener);
int setPitch(float pitch);
int setSpeechRate(float speechRate);
void shutdown();
int speak(String text, int queueMode, HashMap<String, String> params);
int stop();
int synthesizeToFile(String text, HashMap<String, String> params,
String filename);
}
/**
* Subclass of {@link TextToSpeech} which delegates calls to the interface
* above.
* The logic here is stupid and the author is ashamed of having to write it
* like this, but basically the issue is that TextToSpeech cannot be mocked
* without running its constructor, its constructor runs async operations
* which call other methods (and then if the methods are part of a mock we'd
* have to set a behavior, but we can't 'cause the object hasn't been fully
* built yet).
* The logic is that calls made during the constructor (when tts is not yet
* set) will go up to the original class, but after tts is set we'll forward
* them all to the mock.
*/
private class TextToSpeechDelegate
extends TextToSpeech implements TextToSpeechInterface {
public TextToSpeechDelegate(Context context, OnInitListener listener) {
super(context, listener);
}
@Override
public int addEarcon(String earcon, String packagename, int resourceId) {
if (tts == null) {
return super.addEarcon(earcon, packagename, resourceId);
}
return tts.addEarcon(earcon, packagename, resourceId);
}
@Override
public int addEarcon(String earcon, String filename) {
if (tts == null) {
return super.addEarcon(earcon, filename);
}
return tts.addEarcon(earcon, filename);
}
@Override
public int addSpeech(String text, String packagename, int resourceId) {
if (tts == null) {
return super.addSpeech(text, packagename, resourceId);
}
return tts.addSpeech(text, packagename, resourceId);
}
@Override
public int addSpeech(String text, String filename) {
if (tts == null) {
return super.addSpeech(text, filename);
}
return tts.addSpeech(text, filename);
}
@Override
public Locale getLanguage() {
if (tts == null) {
return super.getLanguage();
}
return tts.getLanguage();
}
@Override
public int isLanguageAvailable(Locale loc) {
if (tts == null) {
return super.isLanguageAvailable(loc);
}
return tts.isLanguageAvailable(loc);
}
@Override
public boolean isSpeaking() {
if (tts == null) {
return super.isSpeaking();
}
return tts.isSpeaking();
}
@Override
public int playEarcon(String earcon, int queueMode,
HashMap<String, String> params) {
if (tts == null) {
return super.playEarcon(earcon, queueMode, params);
}
return tts.playEarcon(earcon, queueMode, params);
}
@Override
public int playSilence(long durationInMs, int queueMode,
HashMap<String, String> params) {
if (tts == null) {
return super.playSilence(durationInMs, queueMode, params);
}
return tts.playSilence(durationInMs, queueMode, params);
}
@Override
public int setLanguage(Locale loc) {
if (tts == null) {
return super.setLanguage(loc);
}
return tts.setLanguage(loc);
}
@Override
public int setOnUtteranceCompletedListener(
OnUtteranceCompletedListener listener) {
if (tts == null) {
return super.setOnUtteranceCompletedListener(listener);
}
return tts.setOnUtteranceCompletedListener(listener);
}
@Override
public int setPitch(float pitch) {
if (tts == null) {
return super.setPitch(pitch);
}
return tts.setPitch(pitch);
}
@Override
public int setSpeechRate(float speechRate) {
if (tts == null) {
return super.setSpeechRate(speechRate);
}
return tts.setSpeechRate(speechRate);
}
@Override
public void shutdown() {
if (tts == null) {
super.shutdown();
return;
}
tts.shutdown();
}
@Override
public int speak(
String text, int queueMode, HashMap<String, String> params) {
if (tts == null) {
return super.speak(text, queueMode, params);
}
return tts.speak(text, queueMode, params);
}
@Override
public int stop() {
if (tts == null) {
return super.stop();
}
return tts.stop();
}
@Override
public int synthesizeToFile(String text, HashMap<String, String> params,
String filename) {
if (tts == null) {
return super.synthesizeToFile(text, params, filename);
}
return tts.synthesizeToFile(text, params, filename);
}
}
@UsesMocks({
StatusAnnouncerTask.class,
StringUtils.class,
})
@Override
protected void setUp() throws Exception {
super.setUp();
oldDefaultLocale = Locale.getDefault();
Locale.setDefault(DEFAULT_LOCALE);
// Eww, the effort required just to mock TextToSpeech is insane
final AtomicBoolean listenerCalled = new AtomicBoolean();
OnInitListener blockingListener = new OnInitListener() {
@Override
public void onInit(int status) {
synchronized (this) {
listenerCalled.set(true);
notify();
}
}
};
ttsDelegate = new TextToSpeechDelegate(getContext(), blockingListener);
// Wait for all async operations done in the constructor to finish.
synchronized (blockingListener) {
while (!listenerCalled.get()) {
// Releases the synchronized lock until we're woken up.
blockingListener.wait();
}
}
// Phew, done, now we can start forwarding calls
tts = AndroidMock.createMock(TextToSpeechInterface.class);
initListenerCapture = new Capture<OnInitListener>();
phoneListenerCapture = new Capture<PhoneStateListener>();
// Create a partial forwarding mock
mockTask = AndroidMock.createMock(StatusAnnouncerTask.class, getContext());
task = new StatusAnnouncerTask(getContext()) {
@Override
protected TextToSpeech newTextToSpeech(Context ctx,
OnInitListener onInitListener) {
return mockTask.newTextToSpeech(ctx, onInitListener);
}
@Override
protected String getAnnouncement(TripStatistics stats) {
return mockTask.getAnnouncement(stats);
}
@Override
protected void listenToPhoneState(
PhoneStateListener listener, int events) {
mockTask.listenToPhoneState(listener, events);
}
};
}
@Override
protected void tearDown() {
Locale.setDefault(oldDefaultLocale);
}
public void testStart() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setLanguage(DEFAULT_LOCALE))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
AndroidMock.verify(mockTask, tts);
}
public void testStart_languageNotSupported() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_NOT_SUPPORTED);
expect(tts.setLanguage(Locale.ENGLISH))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
AndroidMock.verify(mockTask, tts);
}
public void testStart_notReady() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.ERROR);
AndroidMock.verify(mockTask, tts);
}
public void testShutdown() {
// First, start
doStart();
AndroidMock.verify(mockTask);
AndroidMock.reset(mockTask);
// Then, shut down
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
mockTask.listenToPhoneState(
same(phoneListener), eq(PhoneStateListener.LISTEN_NONE));
tts.shutdown();
AndroidMock.replay(mockTask, tts);
task.shutdown();
AndroidMock.verify(mockTask, tts);
}
public void testRun() throws Exception {
// Expect service data calls
TripStatistics stats = new TripStatistics();
// Expect announcement building call
expect(mockTask.getAnnouncement(same(stats))).andStubReturn(ANNOUNCEMENT);
// Put task in "ready" state
startTask(TextToSpeech.SUCCESS);
// Expect actual announcement call
expect(tts.speak(
eq(ANNOUNCEMENT), eq(TextToSpeech.QUEUE_FLUSH),
AndroidMock.<HashMap<String, String>>isNull()))
.andReturn(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(stats);
AndroidMock.verify(mockTask, tts);
}
public void testRun_notReady() throws Exception {
// Put task in "not ready" state
startTask(TextToSpeech.ERROR);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_duringCall() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(false);
// Run the announcement
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_OFFHOOK, null);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_ringWhileSpeaking() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(true);
expect(tts.stop()).andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
// Update the state to ringing - this should stop the current announcement.
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
// Run the announcement - this should do nothing.
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_whileRinging() throws Exception {
startTask(TextToSpeech.SUCCESS);
expect(tts.isSpeaking()).andStubReturn(false);
// Run the announcement
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_noService() throws Exception {
startTask(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.run(null);
AndroidMock.verify(mockTask, tts);
}
public void testRun_noStats() throws Exception {
// Expect service data calls
startTask(TextToSpeech.SUCCESS);
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
AndroidMock.verify(mockTask, tts);
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time zero.
*/
public void testGetAnnounceTime_time_zero() {
long time = 0; // 0 seconds
assertEquals("0 minutes 0 seconds", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time one.
*/
public void testGetAnnounceTime_time_one() {
long time = 1 * 1000; // 1 second
assertEquals("0 minutes 1 second", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* numbers with the hour unit.
*/
public void testGetAnnounceTime_singular_has_hour() {
long time = (1 * 60 * 60 * 1000) + (1 * 60 * 1000) + (1 * 1000); // 1 hour 1 minute 1 second
assertEquals("1 hour 1 minute", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* with the hour unit.
*/
public void testGetAnnounceTime_plural_has_hour() {
long time = (2 * 60 * 60 * 1000) + (2 * 60 * 1000) + (2 * 1000); // 2 hours 2 minutes 2 seconds
assertEquals("2 hours 2 minutes", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* numbers without the hour unit.
*/
public void testGetAnnounceTime_singular_no_hour() {
long time = (1 * 60 * 1000) + (1 * 1000); // 1 minute 1 second
assertEquals("1 minute 1 second", task.getAnnounceTime(time));
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* without the hour unit.
*/
public void testGetAnnounceTime_plural_no_hour() {
long time = (2 * 60 * 1000) + (2 * 1000); // 2 minutes 2 seconds
assertEquals("2 minutes 2 seconds", task.getAnnounceTime(time));
}
private void startTask(int state) {
AndroidMock.resetToNice(tts);
AndroidMock.replay(tts);
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
ttsInitListener.onInit(state);
AndroidMock.resetToDefault(tts);
}
private void doStart() {
mockTask.listenToPhoneState(capture(phoneListenerCapture),
eq(PhoneStateListener.LISTEN_CALL_STATE));
expect(mockTask.newTextToSpeech(
same(getContext()), capture(initListenerCapture)))
.andStubReturn(ttsDelegate);
AndroidMock.replay(mockTask);
task.start();
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import android.test.AndroidTestCase;
/**
* Tests for {@link StatusAnnouncerFactory}.
* These tests require Donut+ to run.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerFactoryTest extends AndroidTestCase {
public void testCreate() {
PeriodicTaskFactory factory = new StatusAnnouncerFactory();
PeriodicTask task = factory.create(getContext());
assertTrue(task instanceof StatusAnnouncerTask);
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import static com.google.android.apps.mytracks.Constants.RESUME_TRACK_EXTRA_NAME;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProvider;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.maps.mytracks.R;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.os.IBinder;
import android.test.RenamingDelegatingContext;
import android.test.ServiceTestCase;
import android.test.mock.MockContentResolver;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Tests for the MyTracks track recording service.
*
* @author Bartlomiej Niechwiej
*
* TODO: The original class, ServiceTestCase, has a few limitations, e.g.
* it's not possible to properly shutdown the service, unless tearDown()
* is called, which prevents from testing multiple scenarios in a single
* test (see runFunctionTest for more details).
*/
public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingService> {
private Context context;
private MyTracksProviderUtils providerUtils;
private SharedPreferences sharedPreferences;
/*
* In order to support starting and binding to the service in the same
* unit test, we provide a workaround, as the original class doesn't allow
* to bind after the service has been previously started.
*/
private boolean bound;
private Intent serviceIntent;
public TrackRecordingServiceTest() {
super(TestRecordingService.class);
}
/**
* A context wrapper with the user provided {@link ContentResolver}.
*
* TODO: Move to test utils package.
*/
public static class MockContext extends ContextWrapper {
private final ContentResolver contentResolver;
public MockContext(ContentResolver contentResolver, Context base) {
super(base);
this.contentResolver = contentResolver;
}
@Override
public ContentResolver getContentResolver() {
return contentResolver;
}
}
@Override
protected IBinder bindService(Intent intent) {
if (getService() != null) {
if (bound) {
throw new IllegalStateException(
"Service: " + getService() + " is already bound");
}
bound = true;
serviceIntent = intent.cloneFilter();
return getService().onBind(intent);
} else {
return super.bindService(intent);
}
}
@Override
protected void shutdownService() {
if (bound) {
assertNotNull(getService());
getService().onUnbind(serviceIntent);
bound = false;
}
super.shutdownService();
}
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
// Disable auto resume by default.
updateAutoResumePrefs(0, -1);
// No recording track.
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), -1);
editor.apply();
}
@SmallTest
public void testStartable() {
startService(createStartIntent());
assertNotNull(getService());
}
@MediumTest
public void testBindable() {
IBinder service = bindService(createStartIntent());
assertNotNull(service);
}
@MediumTest
public void testResumeAfterReboot_shouldResume() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We expect to resume the previous track.
assertTrue(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(123, service.getRecordingTrackId());
}
// TODO: shutdownService() has a bug and doesn't set mServiceCreated
// to false, thus preventing from a second call to onCreate().
// Report the bug to Android team. Until then, the following tests
// and checks must be commented out.
//
// TODO: If fixed, remove "disabled" prefix from the test name.
@MediumTest
public void disabledTestResumeAfterReboot_simulateReboot() throws Exception {
updateAutoResumePrefs(0, 10);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Simulate recording a track.
long id = service.startNewTrack();
assertTrue(service.isRecording());
assertEquals(id, service.getRecordingTrackId());
shutdownService();
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
assertTrue(getService().isRecording());
}
@MediumTest
public void testResumeAfterReboot_noRecordingTrack() throws Exception {
// Insert a dummy track and mark it as recording track.
createDummyTrack(123, System.currentTimeMillis(), false);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because it was stopped.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_expiredTrack() throws Exception {
// Insert a dummy track last updated 20 min ago.
createDummyTrack(123, System.currentTimeMillis() - 20 * 60 * 1000, true);
// Clear the number of attempts and set the timeout to 10 min.
updateAutoResumePrefs(0, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because it has expired.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testResumeAfterReboot_tooManyAttempts() throws Exception {
// Insert a dummy track.
createDummyTrack(123, System.currentTimeMillis(), true);
// Set the number of attempts to max.
updateAutoResumePrefs(
TrackRecordingService.MAX_AUTO_RESUME_TRACK_RETRY_ATTEMPTS, 10);
// Start the service in "resume" mode (simulates the on-reboot action).
Intent startIntent = createStartIntent();
startIntent.putExtra(RESUME_TRACK_EXTRA_NAME, true);
startService(startIntent);
assertNotNull(getService());
// We don't expect to resume the previous track, because there were already
// too many attempts.
assertFalse(getService().isRecording());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_noTracks() throws Exception {
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
ITrackRecordingService service = bindAndGetService(createStartIntent());
// Test if we start in no-recording mode by default.
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_oldTracks() throws Exception {
createDummyTrack(123, -1, false);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testRecording_orphanedRecordingTrack() throws Exception {
// Just set recording track to a bogus value.
setRecordingTrack(256);
// Make sure that the service will not start recording and will clear
// the bogus track.
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
}
/**
* Synchronous/waitable broadcast receiver to be used in testing.
*/
private class BlockingBroadcastReceiver extends BroadcastReceiver {
private static final long MAX_WAIT_TIME_MS = 10000;
private List<Intent> receivedIntents = new ArrayList<Intent>();
public List<Intent> getReceivedIntents() {
return receivedIntents;
}
@Override
public void onReceive(Context ctx, Intent intent) {
Log.d("MyTracksTest", "Got broadcast: " + intent);
synchronized (receivedIntents) {
receivedIntents.add(intent);
receivedIntents.notifyAll();
}
}
public boolean waitUntilReceived(int receiveCount) {
long deadline = System.currentTimeMillis() + MAX_WAIT_TIME_MS;
synchronized (receivedIntents) {
while (receivedIntents.size() < receiveCount) {
try {
// Wait releases synchronized lock until it returns
receivedIntents.wait(500);
} catch (InterruptedException e) {
// Do nothing
}
if (System.currentTimeMillis() > deadline) {
return false;
}
}
}
return true;
}
}
@MediumTest
public void testStartNewTrack_noRecording() throws Exception {
// NOTICE: due to the way Android permissions work, if this fails,
// uninstall the test apk then retry - the test must be installed *after*
// My Tracks (go figure).
// Reference: http://code.google.com/p/android/issues/detail?id=5521
BlockingBroadcastReceiver startReceiver = new BlockingBroadcastReceiver();
String startAction = context.getString(R.string.track_started_broadcast_action);
context.registerReceiver(startReceiver, new IntentFilter(startAction));
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
long id = service.startNewTrack();
assertTrue(id >= 0);
assertTrue(service.isRecording());
Track track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
assertEquals(sharedPreferences.getString(context.getString(R.string.default_activity_key), ""),
track.getCategory());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, service.getRecordingTrackId());
// Verify that the start broadcast was received.
assertTrue(startReceiver.waitUntilReceived(1));
List<Intent> receivedIntents = startReceiver.getReceivedIntents();
assertEquals(1, receivedIntents.size());
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(startAction, broadcastIntent.getAction());
assertEquals(id, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
context.unregisterReceiver(startReceiver);
}
@MediumTest
public void testStartNewTrack_alreadyRecording() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
// Starting a new track when there is a recording should just return -1L.
long newTrack = service.startNewTrack();
assertEquals(-1L, newTrack);
assertEquals(123, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(123, service.getRecordingTrackId());
}
@MediumTest
public void testEndCurrentTrack_alreadyRecording() throws Exception {
// See comment above if this fails randomly.
BlockingBroadcastReceiver stopReceiver = new BlockingBroadcastReceiver();
String stopAction = context.getString(R.string.track_stopped_broadcast_action);
context.registerReceiver(stopReceiver, new IntentFilter(stopAction));
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
// End the current track.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
// Verify that the stop broadcast was received.
assertTrue(stopReceiver.waitUntilReceived(1));
List<Intent> receivedIntents = stopReceiver.getReceivedIntents();
assertEquals(1, receivedIntents.size());
Intent broadcastIntent = receivedIntents.get(0);
assertEquals(stopAction, broadcastIntent.getAction());
assertEquals(123, broadcastIntent.getLongExtra(
context.getString(R.string.track_id_broadcast_extra), -1));
context.unregisterReceiver(stopReceiver);
}
@MediumTest
public void testEndCurrentTrack_noRecording() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Ending the current track when there is no recording should not result in any error.
service.endCurrentTrack();
assertEquals(-1, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), 0));
assertEquals(-1, service.getRecordingTrackId());
}
@MediumTest
public void testIntegration_completeRecordingSession() throws Exception {
List<Track> tracks = providerUtils.getAllTracks();
assertTrue(tracks.isEmpty());
fullRecordingSession();
}
@MediumTest
public void testInsertStatisticsMarker_noRecordingTrack() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
try {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS);
fail("Expecting IllegalStateException");
} catch (IllegalStateException e) {
// Expected.
}
}
@MediumTest
public void testInsertStatisticsMarker_validLocation() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS));
assertEquals(2, service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS));
Waypoint wpt = providerUtils.getWaypoint(1);
assertEquals(getContext().getString(R.string.marker_statistics_icon_url),
wpt.getIcon());
assertEquals(getContext().getString(R.string.marker_type_statistics),
wpt.getName());
assertEquals(Waypoint.TYPE_STATISTICS, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNotNull(wpt.getStatistics());
// TODO check the rest of the params.
// TODO: Check waypoint 2.
}
@MediumTest
public void testInsertWaypointMarker_noRecordingTrack() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
try {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER);
fail("Expecting IllegalStateException");
} catch (IllegalStateException e) {
// Expected.
}
}
@MediumTest
public void testInsertWaypointMarker_validWaypoint() throws Exception {
createDummyTrack(123, -1, true);
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertTrue(service.isRecording());
assertEquals(1, service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER));
Waypoint wpt = providerUtils.getWaypoint(1);
assertEquals(getContext().getString(R.string.marker_waypoint_icon_url),
wpt.getIcon());
assertEquals(getContext().getString(R.string.marker_type_waypoint),
wpt.getName());
assertEquals(Waypoint.TYPE_WAYPOINT, wpt.getType());
assertEquals(123, wpt.getTrackId());
assertEquals(0.0, wpt.getLength());
assertNotNull(wpt.getLocation());
assertNull(wpt.getStatistics());
}
@MediumTest
public void testWithProperties_noAnnouncementFreq() throws Exception {
functionalTest(R.string.announcement_frequency_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultAnnouncementFreq() throws Exception {
functionalTest(R.string.announcement_frequency_key, 1);
}
@MediumTest
public void testWithProperties_noMaxRecordingDist() throws Exception {
functionalTest(R.string.max_recording_distance_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMaxRecordingDist() throws Exception {
functionalTest(R.string.max_recording_distance_key, 5);
}
@MediumTest
public void testWithProperties_noMinRecordingDist() throws Exception {
functionalTest(R.string.min_recording_distance_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRecordingDist() throws Exception {
functionalTest(R.string.min_recording_distance_key, 2);
}
@MediumTest
public void testWithProperties_noSplitFreq() throws Exception {
functionalTest(R.string.split_frequency_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultSplitFreqByDist() throws Exception {
functionalTest(R.string.split_frequency_key, 5);
}
@MediumTest
public void testWithProperties_defaultSplitFreqByTime() throws Exception {
functionalTest(R.string.split_frequency_key, -2);
}
@MediumTest
public void testWithProperties_noMetricUnits() throws Exception {
functionalTest(R.string.metric_units_key, (Object) null);
}
@MediumTest
public void testWithProperties_metricUnitsEnabled() throws Exception {
functionalTest(R.string.metric_units_key, true);
}
@MediumTest
public void testWithProperties_metricUnitsDisabled() throws Exception {
functionalTest(R.string.metric_units_key, false);
}
@MediumTest
public void testWithProperties_noMinRecordingInterval() throws Exception {
functionalTest(R.string.min_recording_interval_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRecordingInterval()
throws Exception {
functionalTest(R.string.min_recording_interval_key, 3);
}
@MediumTest
public void testWithProperties_noMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, (Object) null);
}
@MediumTest
public void testWithProperties_defaultMinRequiredAccuracy() throws Exception {
functionalTest(R.string.min_required_accuracy_key, 500);
}
@MediumTest
public void testWithProperties_noSensorType() throws Exception {
functionalTest(R.string.sensor_type_key, (Object) null);
}
@MediumTest
public void testWithProperties_zephyrSensorType() throws Exception {
functionalTest(R.string.sensor_type_key,
context.getString(R.string.sensor_type_value_zephyr));
}
private ITrackRecordingService bindAndGetService(Intent intent) {
ITrackRecordingService service = ITrackRecordingService.Stub.asInterface(
bindService(intent));
assertNotNull(service);
return service;
}
private Track createDummyTrack(long id, long stopTime, boolean isRecording) {
Track dummyTrack = new Track();
dummyTrack.setId(id);
dummyTrack.setName("Dummy Track");
TripStatistics tripStatistics = new TripStatistics();
tripStatistics.setStopTime(stopTime);
dummyTrack.setStatistics(tripStatistics);
addTrack(dummyTrack, isRecording);
return dummyTrack;
}
private void updateAutoResumePrefs(int attempts, int timeoutMins) {
Editor editor = sharedPreferences.edit();
editor.putInt(context.getString(
R.string.auto_resume_track_current_retry_key), attempts);
editor.putInt(context.getString(
R.string.auto_resume_track_timeout_key), timeoutMins);
editor.apply();
}
private Intent createStartIntent() {
Intent startIntent = new Intent();
startIntent.setClass(context, TrackRecordingService.class);
return startIntent;
}
private void addTrack(Track track, boolean isRecording) {
assertTrue(track.getId() >= 0);
providerUtils.insertTrack(track);
assertEquals(track.getId(), providerUtils.getTrack(track.getId()).getId());
setRecordingTrack(isRecording ? track.getId() : -1);
}
private void setRecordingTrack(long id) {
Editor editor = sharedPreferences.edit();
editor.putLong(context.getString(R.string.recording_track_key), id);
editor.apply();
}
// TODO: We support multiple values for readability, however this test's
// base class doesn't properly shutdown the service, so it's not possible
// to pass more than 1 value at a time.
private void functionalTest(int resourceId, Object ...values)
throws Exception {
final String key = context.getString(resourceId);
for (Object value : values) {
// Remove all properties and set the property for the given key.
Editor editor = sharedPreferences.edit();
editor.clear();
if (value instanceof String) {
editor.putString(key, (String) value);
} else if (value instanceof Long) {
editor.putLong(key, (Long) value);
} else if (value instanceof Integer) {
editor.putInt(key, (Integer) value);
} else if (value instanceof Boolean) {
editor.putBoolean(key, (Boolean) value);
} else if (value == null) {
// Do nothing, as clear above has already removed this property.
}
editor.apply();
fullRecordingSession();
}
}
private void fullRecordingSession() throws Exception {
ITrackRecordingService service = bindAndGetService(createStartIntent());
assertFalse(service.isRecording());
// Start a track.
long id = service.startNewTrack();
assertTrue(id >= 0);
assertTrue(service.isRecording());
Track track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
assertEquals(id, sharedPreferences.getLong(
context.getString(R.string.recording_track_key), -1));
assertEquals(id, service.getRecordingTrackId());
// Insert a few points, markers and statistics.
long startTime = System.currentTimeMillis();
for (int i = 0; i < 30; i++) {
Location loc = new Location("gps");
loc.setLongitude(35.0f + i / 10.0f);
loc.setLatitude(45.0f - i / 5.0f);
loc.setAccuracy(5);
loc.setSpeed(10);
loc.setTime(startTime + i * 10000);
loc.setBearing(3.0f);
service.recordLocation(loc);
if (i % 10 == 0) {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_STATISTICS);
} else if (i % 7 == 0) {
service.insertWaypoint(WaypointCreationRequest.DEFAULT_MARKER);
}
}
// Stop the track. Validate if it has correct data.
service.endCurrentTrack();
assertFalse(service.isRecording());
assertEquals(-1, service.getRecordingTrackId());
track = providerUtils.getTrack(id);
assertNotNull(track);
assertEquals(id, track.getId());
TripStatistics tripStatistics = track.getStatistics();
assertNotNull(tripStatistics);
assertTrue(tripStatistics.getStartTime() > 0);
assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services;
import static com.google.android.testing.mocking.AndroidMock.expect;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.test.AndroidTestCase;
import java.io.File;
/**
* Tests {@link RemoveTempFilesService}.
*
* @author Sandor Dornbush
*/
public class RemoveTempFilesServiceTest extends AndroidTestCase {
private static final String DIR_NAME = "/tmp";
private static final String FILE_NAME = "foo";
private RemoveTempFilesService service;
@UsesMocks({ File.class, })
protected void setUp() throws Exception {
service = new RemoveTempFilesService();
};
/**
* Tests when the directory doesn't exists.
*/
public void test_noDir() {
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(false);
AndroidMock.replay(dir);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir);
}
/**
* Tests when the directory is empty.
*/
public void test_emptyDir() {
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[0]);
AndroidMock.replay(dir);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir);
}
/**
* Tests when there is a new file and it shouldn't get deleted.
*/
public void test_newFile() {
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
expect(file.lastModified()).andStubReturn(System.currentTimeMillis());
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[] { file });
AndroidMock.replay(dir, file);
assertEquals(0, service.cleanTempDirectory(dir));
AndroidMock.verify(dir, file);
}
/**
* Tests when there is an old file and it should get deleted.
*/
public void test_oldFile() {
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
// qSet to one hour and 1 millisecond later than the current time
expect(file.lastModified()).andStubReturn(System.currentTimeMillis() - 3600001);
expect(file.delete()).andStubReturn(true);
File dir = AndroidMock.createMock(File.class, DIR_NAME);
expect(dir.exists()).andStubReturn(true);
expect(dir.listFiles()).andStubReturn(new File[] { file });
AndroidMock.replay(dir, file);
assertEquals(1, service.cleanTempDirectory(dir));
AndroidMock.verify(dir, file);
}
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.services.sensors.ant.AntDirectSensorManager;
import com.google.android.apps.mytracks.services.sensors.ant.AntSrmBridgeSensorManager;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
public class SensorManagerFactoryTest extends AndroidTestCase {
private SharedPreferences sharedPreferences;
@Override
protected void setUp() throws Exception {
super.setUp();
sharedPreferences = getContext().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
}
@SmallTest
public void testDefaultSettings() throws Exception {
assertNull(SensorManagerFactory.getInstance().getSensorManager(getContext()));
}
@SmallTest
public void testCreateZephyr() throws Exception {
assertClassForName(ZephyrSensorManager.class, R.string.sensor_type_value_zephyr);
}
@SmallTest
public void testCreateAnt() throws Exception {
assertClassForName(AntDirectSensorManager.class, R.string.sensor_type_value_ant);
}
@SmallTest
public void testCreateAntSRM() throws Exception {
assertClassForName(AntSrmBridgeSensorManager.class, R.string.sensor_type_value_srm_ant_bridge);
}
private void assertClassForName(Class<?> c, int i) {
sharedPreferences.edit()
.putString(getContext().getString(R.string.sensor_type_key),
getContext().getString(i))
.apply();
SensorManager sm = SensorManagerFactory.getInstance().getSensorManager(getContext());
assertNotNull(sm);
assertTrue(c.isInstance(sm));
SensorManagerFactory.getInstance().releaseSensorManager(sm);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntStartupMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0x12,
};
AntStartupMessage message = new AntStartupMessage(rawMessage);
assertEquals(0x12, message.getMessage());
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import com.dsi.ant.AntDefine;
import com.dsi.ant.AntMesg;
import android.test.AndroidTestCase;
public class AntChannelResponseMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0,
AntMesg.MESG_EVENT_ID,
AntDefine.EVENT_RX_SEARCH_TIMEOUT
};
AntChannelResponseMessage message = new AntChannelResponseMessage(rawMessage);
assertEquals(0, message.getChannelNumber());
assertEquals(AntMesg.MESG_EVENT_ID, message.getMessageId());
assertEquals(AntDefine.EVENT_RX_SEARCH_TIMEOUT, message.getMessageCode());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Laszlo Molnar
*/
public class SensorEventCounterTest extends AndroidTestCase {
@SmallTest
public void testGetEventsPerMinute() {
SensorEventCounter sec = new SensorEventCounter();
assertEquals(0, sec.getEventsPerMinute(0, 0, 0));
assertEquals(0, sec.getEventsPerMinute(1, 1024, 1000));
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2000));
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2500));
assertTrue(60 > sec.getEventsPerMinute(2, 1024 * 2, 4000));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntChannelIdMessageTest extends AndroidTestCase {
public void testParse() {
byte[] rawMessage = {
0, // channel number
0x34, 0x12, // device number
(byte) 0xaa, // device type id
(byte) 0xbb, // transmission type
};
AntChannelIdMessage message = new AntChannelIdMessage(rawMessage);
assertEquals(0, message.getChannelNumber());
assertEquals(0x1234, message.getDeviceNumber());
assertEquals((byte) 0xaa, message.getDeviceTypeId());
assertEquals((byte) 0xbb, message.getTransmissionType());
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.test.AndroidTestCase;
public class AntMessageTest extends AndroidTestCase {
private static class TestAntMessage extends AntMessage {
public static short decodeShort(byte low, byte high) {
return AntMessage.decodeShort(low, high);
}
}
public void testDecode() {
assertEquals(0x1234, TestAntMessage.decodeShort((byte) 0x34, (byte) 0x12));
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import android.content.Context;
import android.test.AndroidTestCase;
import android.test.MoreAsserts;
public class AntSensorManagerTest extends AndroidTestCase {
private class TestAntSensorManager extends AntSensorManager {
public TestAntSensorManager(Context context) {
super(context);
}
public byte messageId;
public byte[] messageData;
@Override
protected void setupAntSensorChannels() {}
@SuppressWarnings("deprecation")
@Override
public void handleMessage(byte[] rawMessage) {
super.handleMessage(rawMessage);
}
@SuppressWarnings("hiding")
@Override
public boolean handleMessage(byte messageId, byte[] messageData) {
this.messageId = messageId;
this.messageData = messageData;
return true;
}
}
private TestAntSensorManager sensorManager;
@Override
protected void setUp() throws Exception {
super.setUp();
sensorManager = new TestAntSensorManager(getContext());
}
public void testSimple() {
byte[] rawMessage = {
0x03, // length
0x12, // message id
0x11, 0x22, 0x33, // body
};
byte[] expectedBody = { 0x11, 0x22, 0x33 };
sensorManager.handleMessage(rawMessage);
assertEquals((byte) 0x12, sensorManager.messageId);
MoreAsserts.assertEquals(expectedBody, sensorManager.messageData);
}
public void testTooShort() {
byte[] rawMessage = {
0x53, // length
0x12 // message id
};
sensorManager.handleMessage(rawMessage);
assertEquals(0, sensorManager.messageId);
assertNull(sensorManager.messageData);
}
public void testLengthWrong() {
byte[] rawMessage = {
0x53, // length
0x12, // message id
0x34, // body
};
sensorManager.handleMessage(rawMessage);
assertEquals(0, sensorManager.messageId);
assertNull(sensorManager.messageData);
}
}
| Java |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.sensors.ant;
import com.dsi.ant.AntMesg;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
public class AntDirectSensorManagerTest extends AndroidTestCase {
private SharedPreferences sharedPreferences;
private AntSensorBase heartRateSensor;
private static final byte HEART_RATE_CHANNEL = 0;
private class MockAntDirectSensorManager extends AntDirectSensorManager {
public MockAntDirectSensorManager(Context context) {
super(context);
}
@Override
protected boolean setupChannel(AntSensorBase sensor, byte channel) {
if (channel == HEART_RATE_CHANNEL) {
heartRateSensor = sensor;
return true;
}
return false;
}
}
private AntDirectSensorManager manager;
public void setUp() {
sharedPreferences = getContext().getSharedPreferences(
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
// Let's use default values.
sharedPreferences.edit().clear().apply();
manager = new MockAntDirectSensorManager(getContext());
}
@SmallTest
public void testBroadcastData() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
heartRateSensor.setDeviceNumber((short) 42);
byte[] buff = new byte[9];
buff[0] = HEART_RATE_CHANNEL;
buff[8] = (byte) 220;
manager.handleMessage(AntMesg.MESG_BROADCAST_DATA_ID, buff);
Sensor.SensorDataSet sds = manager.getSensorDataSet();
assertNotNull(sds);
assertTrue(sds.hasHeartRate());
assertEquals(Sensor.SensorState.SENDING,
sds.getHeartRate().getState());
assertEquals(220, sds.getHeartRate().getValue());
assertFalse(sds.hasCadence());
assertFalse(sds.hasPower());
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
}
@SmallTest
public void testChannelId() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
byte[] buff = new byte[9];
buff[1] = 43;
manager.handleMessage(AntMesg.MESG_CHANNEL_ID_ID, buff);
assertEquals(43, heartRateSensor.getDeviceNumber());
assertEquals(43,
sharedPreferences.getInt(
getContext().getString(R.string.ant_heart_rate_sensor_id_key), -1));
assertNull(manager.getSensorDataSet());
}
@SmallTest
public void testResponseEvent() {
manager.setupAntSensorChannels();
assertNotNull(heartRateSensor);
manager.setHeartRate(210);
heartRateSensor.setDeviceNumber((short) 42);
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
byte[] buff = new byte[3];
buff[0] = HEART_RATE_CHANNEL;
buff[1] = AntMesg.MESG_UNASSIGN_CHANNEL_ID;
buff[2] = 0; // code
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
heartRateSensor.setDeviceNumber((short) 0);
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
assertEquals(Sensor.SensorState.DISCONNECTED, manager.getSensorState());
}
// TODO: Test timeout too.
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import java.util.Arrays;
import com.google.android.apps.mytracks.content.Sensor;
import junit.framework.TestCase;
public class PolarMessageParserTest extends TestCase {
PolarMessageParser parser = new PolarMessageParser();
// A complete and valid Polar HxM packet
// FE08F701D1001104FE08F702D1001104
private final byte[] originalBuf =
{(byte) 0xFE, 0x08, (byte) 0xF7, 0x01, (byte) 0xD1, 0x00, 0x11, 0x04, (byte) 0xFE, 0x08,
(byte) 0xF7, 0x02, (byte) 0xD1, 0x00, 0x11, 0x04};
private byte[] buf;
public void setUp() {
buf = Arrays.copyOf(originalBuf, originalBuf.length);
}
public void testIsValid() {
assertTrue(parser.isValid(buf));
}
public void testIsValid_invalidHeader() {
// Invalidate header.
buf[0] = 0x03;
assertFalse(parser.isValid(buf));
}
public void testIsValid_invalidCheckbyte() {
// Invalidate checkbyte.
buf[2] = 0x03;
assertFalse(parser.isValid(buf));
}
public void testIsValid_invalidSequence() {
// Invalidate sequence.
buf[3] = 0x11;
assertFalse(parser.isValid(buf));
}
public void testParseBuffer() {
buf[5] = 70;
Sensor.SensorDataSet sds = parser.parseBuffer(buf);
assertTrue(sds.hasHeartRate());
assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING);
assertEquals(70, sds.getHeartRate().getValue());
}
public void testFindNextAlignment_offset() {
// The first 4 bytes are garbage
buf = new byte[originalBuf.length + 4];
buf[0] = 4;
buf[1] = 2;
buf[2] = 4;
buf[3] = 2;
// Then the valid message.
System.arraycopy(originalBuf, 0, buf, 4, originalBuf.length);
assertEquals(4, parser.findNextAlignment(buf));
}
public void testFindNextAlignment_invalid() {
buf[0] = 0;
assertEquals(-1, parser.findNextAlignment(buf));
}
}
| Java |
package com.google.android.apps.mytracks.services.sensors;
import com.google.android.apps.mytracks.content.Sensor;
import junit.framework.TestCase;
public class ZephyrMessageParserTest extends TestCase {
ZephyrMessageParser parser = new ZephyrMessageParser();
public void testIsValid() {
byte[] smallBuf = new byte[59];
assertFalse(parser.isValid(smallBuf));
// A complete and valid Zephyr HxM packet
byte[] buf = { 2,38,55,26,0,49,101,80,0,49,98,100,42,113,120,-53,-24,-60,-123,-61,117,-69,42,-75,74,-78,51,-79,27,-83,28,-88,28,-93,29,-98,25,-103,26,-108,26,-113,59,-118,0,0,0,0,0,0,-22,3,125,1,48,0,96,4,30,0 };
// Make buffer invalid
buf[0] = buf[58] = buf[59] = 0;
assertFalse(parser.isValid(buf));
buf[0] = 0x02;
assertFalse(parser.isValid(buf));
buf[58] = 0x1E;
assertFalse(parser.isValid(buf));
buf[59] = 0x03;
assertTrue(parser.isValid(buf));
}
public void testParseBuffer() {
byte[] buf = new byte[60];
// Heart Rate (-1 =^ 255 unsigned byte)
buf[12] = -1;
// Battery Level
buf[11] = 51;
// Cadence (=^ 255*16 strides/min)
buf[56] = -1;
buf[57] = 15;
Sensor.SensorDataSet sds = parser.parseBuffer(buf);
assertTrue(sds.hasHeartRate());
assertTrue(sds.getHeartRate().getState() == Sensor.SensorState.SENDING);
assertEquals(255, sds.getHeartRate().getValue());
assertTrue(sds.hasBatteryLevel());
assertTrue(sds.getBatteryLevel().getState() == Sensor.SensorState.SENDING);
assertEquals(51, sds.getBatteryLevel().getValue());
assertTrue(sds.hasCadence());
assertTrue(sds.getCadence().getState() == Sensor.SensorState.SENDING);
assertEquals(255, sds.getCadence().getValue());
}
public void testFindNextAlignment() {
byte[] buf = new byte[60];
assertEquals(-1, parser.findNextAlignment(buf));
buf[10] = 0x03;
buf[11] = 0x02;
assertEquals(10, parser.findNextAlignment(buf));
}
}
| Java |
// Copyright 2012 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.services;
import android.app.Notification;
import android.app.Service;
import android.test.ServiceTestCase;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* A {@link TrackRecordingService} that can be used with {@link ServiceTestCase}.
* {@link ServiceTestCase} throws a null pointer exception when the service
* calls {@link Service#startForeground(int, android.app.Notification)} and
* {@link Service#stopForeground(boolean)}.
* <p>
* See http://code.google.com/p/android/issues/detail?id=12122
* <p>
* Wrap these two methods in wrappers and override them.
*
* @author Jimmy Shih
*/
public class TestRecordingService extends TrackRecordingService {
private static final String TAG = TestRecordingService.class.getSimpleName();
@Override
protected void startForegroundService(Notification notification) {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, true);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
@Override
protected void stopForegroundService() {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, false);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import android.test.AndroidTestCase;
import android.util.Pair;
/**
* Tests for {@link DescriptionGeneratorImpl}.
*
* @author Jimmy Shih
*/
public class DescriptionGeneratorImplTest extends AndroidTestCase {
private DescriptionGeneratorImpl descriptionGenerator;
@Override
protected void setUp() throws Exception {
descriptionGenerator = new DescriptionGeneratorImpl(getContext());
}
/**
* Tests {@link DescriptionGeneratorImpl#generateTrackDescription(Track,
* java.util.Vector, java.util.Vector)}.
*/
public void testGenerateTrackDescription() {
Track track = new Track();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(1288721514000L);
track.setStatistics(stats);
track.setCategory("hiking");
String expected = "Created by"
+ " <a href='http://www.google.com/mobile/mytracks'>My Tracks</a> on Android.<p>"
+ "Total distance: 20.00 km (12.4 mi)<br>"
+ "Total time: 10:00<br>"
+ "Moving time: 05:00<br>"
+ "Average speed: 120.00 km/h (74.6 mi/h)<br>"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)<br>"
+ "Max speed: 360.00 km/h (223.7 mi/h)<br>"
+ "Average pace: 0.50 min/km (0.8 min/mi)<br>"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)<br>"
+ "Min pace: 0.17 min/km (0.3 min/mi)<br>"
+ "Max elevation: 550 m (1804 ft)<br>"
+ "Min elevation: -500 m (-1640 ft)<br>"
+ "Elevation gain: 6000 m (19685 ft)<br>"
+ "Max grade: 42 %<br>"
+ "Min grade: 11 %<br>"
+ "Recorded: 11/2/2010 11:11 AM<br>"
+ "Activity type: hiking<br>";
assertEquals(expected, descriptionGenerator.generateTrackDescription(track, null, null));
}
/**
* Tests {@link DescriptionGeneratorImpl#generateWaypointDescription(Waypoint)}.
*/
public void testGenerateWaypointDescription() {
Waypoint waypoint = new Waypoint();
TripStatistics stats = new TripStatistics();
stats.setTotalDistance(20000);
stats.setTotalTime(600000);
stats.setMovingTime(300000);
stats.setMaxSpeed(100);
stats.setMaxElevation(550);
stats.setMinElevation(-500);
stats.setTotalElevationGain(6000);
stats.setMaxGrade(0.42);
stats.setMinGrade(0.11);
stats.setStartTime(1288721514000L);
waypoint.setStatistics(stats);
String expected = "Total distance: 20.00 km (12.4 mi)\n"
+ "Total time: 10:00\n"
+ "Moving time: 05:00\n"
+ "Average speed: 120.00 km/h (74.6 mi/h)\n"
+ "Average moving speed: 240.00 km/h (149.1 mi/h)\n"
+ "Max speed: 360.00 km/h (223.7 mi/h)\n"
+ "Average pace: 0.50 min/km (0.8 min/mi)\n"
+ "Average moving pace: 0.25 min/km (0.4 min/mi)\n"
+ "Min pace: 0.17 min/km (0.3 min/mi)\n"
+ "Max elevation: 550 m (1804 ft)\n"
+ "Min elevation: -500 m (-1640 ft)\n"
+ "Elevation gain: 6000 m (19685 ft)\n"
+ "Max grade: 42 %\n"
+ "Min grade: 11 %\n"
+ "Recorded: 11/2/2010 11:11 AM\n";
assertEquals(expected, descriptionGenerator.generateWaypointDescription(waypoint));
}
/**
* Tests {@link DescriptionGeneratorImpl#writeDistance(double, StringBuilder,
* int, String)}.
*/
public void testWriteDistance() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeDistance(1100, builder, R.string.description_total_distance, "<br>");
assertEquals("Total distance: 1.10 km (0.7 mi)<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeTime(long, StringBuilder, int,
* String)}.
*/
public void testWriteTime() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeTime(1000, builder, R.string.description_total_time, "<br>");
assertEquals("Total time: 00:01<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeSpeed(double, StringBuilder,
* int, String)}.
*/
public void testWriteSpeed() {
StringBuilder builder = new StringBuilder();
Pair<Double, Double> speed = descriptionGenerator.writeSpeed(
1.1, builder, R.string.description_average_speed, "\n");
assertEquals(3.96, speed.first);
assertEquals(3.96 * UnitConversions.KM_TO_MI, speed.second);
assertEquals("Average speed: 3.96 km/h (2.5 mi/h)\n", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeElevation(double, StringBuilder,
* int, String)}.
*/
public void testWriteElevation() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeElevation(4.2, builder, R.string.description_min_elevation, "<br>");
assertEquals("Min elevation: 4 m (14 ft)<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writePace(Pair, StringBuilder, int,
* String)}.
*/
public void testWritePace() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writePace(
new Pair<Double, Double>(1.1, 2.2), builder, R.string.description_average_pace, "\n");
assertEquals("Average pace: 54.55 min/km (27.3 min/mi)\n", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)}.
*/
public void testWriteGrade() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(.042, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 4 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)} with a NaN.
*/
public void testWriteGrade_nan() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(Double.NaN, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 0 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
* int, String)} with an infinite number.
*/
public void testWriteGrade_infinite() {
StringBuilder builder = new StringBuilder();
descriptionGenerator.writeGrade(
Double.POSITIVE_INFINITY, builder, R.string.description_max_grade, "<br>");
assertEquals("Max grade: 0 %<br>", builder.toString());
}
/**
* Tests {@link DescriptionGeneratorImpl#getPace(double)}.
*/
public void testGetPace() {
assertEquals(12.0, descriptionGenerator.getPace(5));
}
/**
* Tests {@link DescriptionGeneratorImpl#getPace(double)} with zero speed.
*/
public void testGetPace_zero() {
assertEquals(0.0, descriptionGenerator.getPace(0));
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.WaypointCreationRequest.WaypointType;
import android.os.Parcel;
import android.test.AndroidTestCase;
/**
* Tests for the WaypointCreationRequest class.
* {@link WaypointCreationRequest}
*
* @author Sandor Dornbush
*/
public class WaypointCreationRequestTest extends AndroidTestCase {
public void testTypeParceling() {
WaypointCreationRequest original = WaypointCreationRequest.DEFAULT_MARKER;
Parcel p = Parcel.obtain();
original.writeToParcel(p, 0);
p.setDataPosition(0);
WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p);
assertEquals(original.getType(), copy.getType());
assertNull(copy.getName());
assertNull(copy.getDescription());
assertNull(copy.getIconUrl());
}
public void testAllAttributesParceling() {
WaypointCreationRequest original =
new WaypointCreationRequest(WaypointType.MARKER, "name", "description", "img.png");
Parcel p = Parcel.obtain();
original.writeToParcel(p, 0);
p.setDataPosition(0);
WaypointCreationRequest copy = WaypointCreationRequest.CREATOR.createFromParcel(p);
assertEquals(original.getType(), copy.getType());
assertEquals("name", copy.getName());
assertEquals("description", copy.getDescription());
assertEquals("img.png", copy.getIconUrl());
}
}
| Java |
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import android.content.Context;
import android.location.Location;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A unit test for {@link MyTracksProviderUtilsImpl}.
*
* @author Bartlomiej Niechwiej
*/
public class MyTracksProviderUtilsImplTest extends AndroidTestCase {
private Context context;
private MyTracksProviderUtils providerUtils;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
}
public void testLocationIterator_noPoints() {
testIterator(1, 0, 1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_customFactory() {
final Location location = new Location("test_location");
final AtomicInteger counter = new AtomicInteger();
testIterator(1, 15, 4, false, new LocationFactory() {
@Override
public Location createLocation() {
counter.incrementAndGet();
return location;
}
});
// Make sure we were called exactly as many times as we had track points.
assertEquals(15, counter.get());
}
public void testLocationIterator_nullFactory() {
try {
testIterator(1, 15, 4, false, null);
fail("Expecting IllegalArgumentException");
} catch (IllegalArgumentException e) {
// Expected.
}
}
public void testLocationIterator_noBatchAscending() {
testIterator(1, 50, 100, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 50, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_noBatchDescending() {
testIterator(1, 50, 100, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 50, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_batchAscending() {
testIterator(1, 50, 11, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 25, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_batchDescending() {
testIterator(1, 50, 11, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
testIterator(2, 50, 25, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
public void testLocationIterator_largeTrack() {
testIterator(1, 20000, 2000, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
}
private List<Location> testIterator(long trackId, int numPoints, int batchSize,
boolean descending, LocationFactory locationFactory) {
long lastPointId = initializeTrack(trackId, numPoints);
((MyTracksProviderUtilsImpl) providerUtils).setDefaultCursorBatchSize(batchSize);
List<Location> locations = new ArrayList<Location>(numPoints);
LocationIterator it = providerUtils.getLocationIterator(trackId, -1, descending, locationFactory);
try {
while (it.hasNext()) {
Location loc = it.next();
assertNotNull(loc);
locations.add(loc);
// Make sure the IDs are returned in the right order.
assertEquals(descending ? lastPointId - locations.size() + 1
: lastPointId - numPoints + locations.size(), it.getLocationId());
}
assertEquals(numPoints, locations.size());
} finally {
it.close();
}
return locations;
}
private long initializeTrack(long id, int numPoints) {
Track track = new Track();
track.setId(id);
track.setName("Test: " + id);
track.setNumberOfPoints(numPoints);
providerUtils.insertTrack(track);
track = providerUtils.getTrack(id);
assertNotNull(track);
Location[] locations = new Location[numPoints];
for (int i = 0; i < numPoints; ++i) {
Location loc = new Location("test");
loc.setLatitude(37.0 + (double) i / 10000.0);
loc.setLongitude(57.0 - (double) i / 10000.0);
loc.setAccuracy((float) i / 100.0f);
loc.setAltitude(i * 2.5);
locations[i] = loc;
}
providerUtils.bulkInsertTrackPoints(locations, numPoints, id);
// Load all inserted locations.
long lastPointId = -1;
int counter = 0;
LocationIterator it = providerUtils.getLocationIterator(id, -1, false,
MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
try {
while (it.hasNext()) {
it.next();
lastPointId = it.getLocationId();
counter++;
}
} finally {
it.close();
}
assertTrue(numPoints == 0 || lastPointId > 0);
assertEquals(numPoints, track.getNumberOfPoints());
assertEquals(numPoints, counter);
return lastPointId;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.SearchEngine.ScoredResult;
import com.google.android.apps.mytracks.content.SearchEngine.SearchQuery;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.apps.mytracks.stats.TripStatistics;
import android.content.ContentUris;
import android.location.Location;
import android.net.Uri;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Tests for {@link SearchEngine}.
* These are not meant to be quality tests, but instead feature-by-feature tests
* (in other words, they don't test the mixing of different score boostings, just
* each boosting separately)
*
* @author Rodrigo Damazio
*/
public class SearchEngineTest extends AndroidTestCase {
private static final Location HERE = new Location("gps");
private static final long NOW = 1234567890000L; // After OLDEST_ALLOWED_TIMESTAMP
private MyTracksProviderUtils providerUtils;
private SearchEngine engine;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
MockContext context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider provider = new MyTracksProvider();
provider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
engine = new SearchEngine(providerUtils);
}
@Override
protected void tearDown() throws Exception {
providerUtils.deleteAllTracks();
super.tearDown();
}
private long insertTrack(String title, String description, String category, double distance, long hoursAgo) {
Track track = new Track();
track.setName(title);
track.setDescription(description);
track.setCategory(category);
TripStatistics stats = track.getStatistics();
if (hoursAgo > 0) {
// Started twice hoursAgo, so the average time is hoursAgo.
stats.setStartTime(NOW - hoursAgo * 1000L * 60L * 60L * 2);
stats.setStopTime(NOW);
}
int latitude = (int) ((HERE.getLatitude() + distance) * 1E6);
int longitude = (int) ((HERE.getLongitude() + distance) * 1E6);
stats.setBounds(latitude, longitude, latitude, longitude);
Uri uri = providerUtils.insertTrack(track);
return ContentUris.parseId(uri);
}
private long insertTrack(String title, String description, String category) {
return insertTrack(title, description, category, 0, -1);
}
private long insertTrack(String title, double distance) {
return insertTrack(title, "", "", distance, -1);
}
private long insertTrack(String title, long hoursAgo) {
return insertTrack(title, "", "", 0.0, hoursAgo);
}
private long insertWaypoint(String title, String description, String category, double distance, long hoursAgo, long trackId) {
Waypoint waypoint = new Waypoint();
waypoint.setName(title);
waypoint.setDescription(description);
waypoint.setCategory(category);
waypoint.setTrackId(trackId);
Location location = new Location(HERE);
location.setLatitude(location.getLatitude() + distance);
location.setLongitude(location.getLongitude() + distance);
if (hoursAgo >= 0) {
location.setTime(NOW - hoursAgo * 1000L * 60L * 60L);
}
waypoint.setLocation(location);
Uri uri = providerUtils.insertWaypoint(waypoint);
return ContentUris.parseId(uri);
}
private long insertWaypoint(String title, String description, String category) {
return insertWaypoint(title, description, category, 0.0, -1, -1);
}
private long insertWaypoint(String title, double distance) {
return insertWaypoint(title, "", "", distance, -1, -1);
}
private long insertWaypoint(String title, long hoursAgo) {
return insertWaypoint(title, "", "", 0.0, hoursAgo, -1);
}
private long insertWaypoint(String title, long hoursAgo, long trackId) {
return insertWaypoint(title, "", "", 0.0, hoursAgo, trackId);
}
public void testSearchText() {
// Insert 7 tracks (purposefully out of result order):
// - one which won't match
// - one which will match the description
// - one which will match the category
// - one which will match the title
// - one which will match in title and category
// - one which will match in title and description
// - one which will match in all fields
insertTrack("bb", "cc", "dd");
long descriptionMatchId = insertTrack("bb", "aa", "cc");
long categoryMatchId = insertTrack("bb", "cc", "aa");
long titleMatchId = insertTrack("aa", "bb", "cc");
long titleCategoryMatchId = insertTrack("aa", "bb", "ca");
long titleDescriptionMatchId = insertTrack("aa", "ba", "cc");
long allMatchId = insertTrack("aa", "ba", "ca");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertTrackResults(results,
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
categoryMatchId);
}
public void testSearchWaypointText() {
// Insert 7 waypoints (purposefully out of result order):
// - one which won't match
// - one which will match the description
// - one which will match the category
// - one which will match the title
// - one which will match in title and category
// - one which will match in title and description
// - one which will match in all fields
insertWaypoint("bb", "cc", "dd");
long descriptionMatchId = insertWaypoint("bb", "aa", "cc");
long categoryMatchId = insertWaypoint("bb", "cc", "aa");
long titleMatchId = insertWaypoint("aa", "bb", "cc");
long titleCategoryMatchId = insertWaypoint("aa", "bb", "ca");
long titleDescriptionMatchId = insertWaypoint("aa", "ba", "cc");
long allMatchId = insertWaypoint("aa", "ba", "ca");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertWaypointResults(results,
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
categoryMatchId);
}
public void testSearchMixedText() {
// Insert 5 entries (purposefully out of result order):
// - one waypoint which will match by description
// - one waypoint which won't match
// - one waypoint which will match by title
// - one track which won't match
// - one track which will match by title
long descriptionWaypointId = insertWaypoint("bb", "aa", "cc");
insertWaypoint("bb", "cc", "dd");
long titleWaypointId = insertWaypoint("aa", "bb", "cc");
insertTrack("bb", "cc", "dd");
long trackId = insertTrack("aa", "bb", "cc");
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Title > Description > Category.
assertEquals(results.toString(), 3, results.size());
assertTrackResult(trackId, results.get(0));
assertWaypointResult(titleWaypointId, results.get(1));
assertWaypointResult(descriptionWaypointId, results.get(2));
}
public void testSearchTrackDistance() {
// All results match text, but they're at difference distances from the user.
long farFarAwayId = insertTrack("aa", 0.3);
long nearId = insertTrack("ab", 0.1);
long farId = insertTrack("ac", 0.2);
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Distance order.
assertTrackResults(results, nearId, farId, farFarAwayId);
}
public void testSearchWaypointDistance() {
// All results match text, but they're at difference distances from the user.
long farFarAwayId = insertWaypoint("aa", 0.3);
long nearId = insertWaypoint("ab", 0.1);
long farId = insertWaypoint("ac", 0.2);
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Distance order.
assertWaypointResults(results, nearId, farId, farFarAwayId);
}
public void testSearchTrackRecent() {
// All results match text, but they're were recorded at different times.
long oldestId = insertTrack("aa", 3);
long recentId = insertTrack("ab", 1);
long oldId = insertTrack("ac", 2);
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Reverse time order.
assertTrackResults(results, recentId, oldId, oldestId);
}
public void testSearchWaypointRecent() {
// All results match text, but they're were recorded at different times.
long oldestId = insertWaypoint("aa", 2);
long recentId = insertWaypoint("ab", 0);
long oldId = insertWaypoint("ac", 1);
SearchQuery query = new SearchQuery("a", null, -1, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Reverse time order.
assertWaypointResults(results, recentId, oldId, oldestId);
}
public void testSearchCurrentTrack() {
// All results match text, but one of them is the current track.
long currentId = insertTrack("ab", 1);
long otherId = insertTrack("aa", 1);
SearchQuery query = new SearchQuery("a", null, currentId, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Current track should be demoted.
assertTrackResults(results, otherId, currentId);
}
public void testSearchCurrentTrackWaypoint() {
// All results match text, but one of them is in the current track.
long otherId = insertWaypoint("aa", 1, 456);
long currentId = insertWaypoint("ab", 1, 123);
SearchQuery query = new SearchQuery("a", null, 123, NOW);
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
// Waypoint in current track should be promoted.
assertWaypointResults(results, currentId, otherId);
}
private void assertTrackResult(long trackId, ScoredResult result) {
assertNotNull("Not a track", result.track);
assertNull("Ambiguous result", result.waypoint);
assertEquals(trackId, result.track.getId());
}
private void assertTrackResults(List<ScoredResult> results, long... trackIds) {
String errMsg = "Expected IDs=" + Arrays.toString(trackIds) + "; results=" + results;
assertEquals(results.size(), trackIds.length);
for (int i = 0; i < results.size(); i++) {
ScoredResult result = results.get(i);
assertNotNull(errMsg, result.track);
assertNull(errMsg, result.waypoint);
assertEquals(errMsg, trackIds[i], result.track.getId());
}
}
private void assertWaypointResult(long waypointId, ScoredResult result) {
assertNotNull("Not a waypoint", result.waypoint);
assertNull("Ambiguous result", result.track);
assertEquals(waypointId, result.waypoint.getId());
}
private void assertWaypointResults(List<ScoredResult> results, long... waypointIds) {
String errMsg = "Expected IDs=" + Arrays.toString(waypointIds) + "; results=" + results;
assertEquals(results.size(), waypointIds.length);
for (int i = 0; i < results.size(); i++) {
ScoredResult result = results.get(i);
assertNotNull(errMsg, result.waypoint);
assertNull(errMsg, result.track);
assertEquals(errMsg, waypointIds[i], result.waypoint.getId());
}
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.content;
import static com.google.android.testing.mocking.AndroidMock.anyInt;
import static com.google.android.testing.mocking.AndroidMock.capture;
import static com.google.android.testing.mocking.AndroidMock.eq;
import static com.google.android.testing.mocking.AndroidMock.expect;
import static com.google.android.testing.mocking.AndroidMock.isA;
import static com.google.android.testing.mocking.AndroidMock.leq;
import static com.google.android.testing.mocking.AndroidMock.same;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.content.TrackDataHub.ListenerDataType;
import com.google.android.apps.mytracks.content.TrackDataListener.ProviderState;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.maps.mytracks.R;
import com.google.android.testing.mocking.AndroidMock;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.location.Location;
import android.location.LocationListener;
import android.provider.BaseColumns;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.lang.reflect.Constructor;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;
import org.easymock.Capture;
import org.easymock.IAnswer;
/**
* Tests for {@link TrackDataHub}.
*
* @author Rodrigo Damazio
*/
public class TrackDataHubTest extends AndroidTestCase {
private static final long TRACK_ID = 42L;
private static final int TARGET_POINTS = 50;
private MyTracksProviderUtils providerUtils;
private TrackDataHub hub;
private TrackDataListeners listeners;
private DataSourcesWrapper dataSources;
private SharedPreferences prefs;
private TrackDataListener listener1;
private TrackDataListener listener2;
private Capture<OnSharedPreferenceChangeListener> preferenceListenerCapture =
new Capture<SharedPreferences.OnSharedPreferenceChangeListener>();
private MockContext context;
private float declination;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
context = new MockContext(mockContentResolver, targetContext);
prefs = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
providerUtils = AndroidMock.createMock("providerUtils", MyTracksProviderUtils.class);
dataSources = AndroidMock.createNiceMock("dataSources", DataSourcesWrapper.class);
listeners = new TrackDataListeners();
hub = new TrackDataHub(context, listeners, prefs, providerUtils, TARGET_POINTS) {
@Override
protected DataSourcesWrapper newDataSources() {
return dataSources;
}
@Override
protected void runInListenerThread(Runnable runnable) {
// Run everything in the same thread.
runnable.run();
}
@Override
protected float getDeclinationFor(Location location, long timestamp) {
return declination;
}
};
listener1 = AndroidMock.createStrictMock("listener1", TrackDataListener.class);
listener2 = AndroidMock.createStrictMock("listener2", TrackDataListener.class);
}
@Override
protected void tearDown() throws Exception {
AndroidMock.reset(dataSources);
// Expect everything to be unregistered.
if (preferenceListenerCapture.hasCaptured()) {
dataSources.unregisterOnSharedPreferenceChangeListener(preferenceListenerCapture.getValue());
}
dataSources.removeLocationUpdates(isA(LocationListener.class));
dataSources.unregisterSensorListener(isA(SensorEventListener.class));
dataSources.unregisterContentObserver(isA(ContentObserver.class));
AndroidMock.expectLastCall().times(3);
AndroidMock.replay(dataSources);
hub.stop();
hub = null;
super.tearDown();
}
public void testTrackListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
Track track = new Track();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
expectStart();
dataSources.registerContentObserver(
eq(TracksColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.TRACK_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.TRACK_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
// Now expect an update.
listener1.onTrackUpdated(track);
listener2.onTrackUpdated(track);
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getTrack(TRACK_ID)).andStubReturn(track);
listener2.onTrackUpdated(track);
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
private static class FixedSizeCursorAnswer implements IAnswer<Cursor> {
private final int size;
public FixedSizeCursorAnswer(int size) {
this.size = size;
}
@Override
public Cursor answer() throws Throwable {
MatrixCursor cursor = new MatrixCursor(new String[] { BaseColumns._ID });
for (long i = 1; i <= size; i++) {
cursor.addRow(new Object[] { i });
}
return cursor;
}
}
private static class FixedSizeLocationIterator implements LocationIterator {
private final long startId;
private final Location[] locs;
private final Set<Integer> splitIndexSet = new HashSet<Integer>();
private int currentIdx = -1;
public FixedSizeLocationIterator(long startId, int size) {
this(startId, size, null);
}
public FixedSizeLocationIterator(long startId, int size, int... splitIndices) {
this.startId = startId;
this.locs = new Location[size];
for (int i = 0; i < size; i++) {
Location loc = new Location("gps");
loc.setLatitude(-15.0 + i / 1000.0);
loc.setLongitude(37 + i / 1000.0);
loc.setAltitude(i);
locs[i] = loc;
}
if (splitIndices != null) {
for (int splitIdx : splitIndices) {
splitIndexSet.add(splitIdx);
Location splitLoc = locs[splitIdx];
splitLoc.setLatitude(100.0);
splitLoc.setLongitude(200.0);
}
}
}
public void expectLocationsDelivered(TrackDataListener listener) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else {
listener.onNewTrackPoint(locs[i]);
}
}
}
public void expectSampledLocationsDelivered(
TrackDataListener listener, int sampleFrequency, boolean includeSampledOut) {
for (int i = 0; i < locs.length; i++) {
if (splitIndexSet.contains(i)) {
listener.onSegmentSplit();
} else if (i % sampleFrequency == 0) {
listener.onNewTrackPoint(locs[i]);
} else if (includeSampledOut) {
listener.onSampledOutTrackPoint(locs[i]);
}
}
}
@Override
public boolean hasNext() {
return currentIdx < (locs.length - 1);
}
@Override
public Location next() {
currentIdx++;
return locs[currentIdx];
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public long getLocationId() {
return startId + currentIdx;
}
@Override
public void close() {
// Do nothing
}
}
public void testWaypointListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
Waypoint wpt1 = new Waypoint(),
wpt2 = new Waypoint(),
wpt3 = new Waypoint(),
wpt4 = new Waypoint();
Location loc = new Location("gps");
loc.setLatitude(10.0);
loc.setLongitude(8.0);
wpt1.setLocation(loc);
wpt2.setLocation(loc);
wpt3.setLocation(loc);
wpt4.setLocation(loc);
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(2));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt1)
.andReturn(wpt2);
expectStart();
dataSources.registerContentObserver(
eq(WaypointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Expect the initial loading.
// Both listeners (registered before and after start) should get the same data.
listener1.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener1.onNewWaypointsDone();
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.WAYPOINT_UPDATES));
verifyAndReset();
ContentObserver observer = observerCapture.getValue();
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(3));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3);
// Now expect an update.
listener1.clearWaypoints();
listener2.clearWaypoints();
listener1.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt1);
listener1.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt2);
listener1.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt3);
listener1.onNewWaypointsDone();
listener2.onNewWaypointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister one, get another update.
expect(providerUtils.getWaypointsCursor(
eq(TRACK_ID), leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS)))
.andStubAnswer(new FixedSizeCursorAnswer(4));
expect(providerUtils.createWaypoint(isA(Cursor.class)))
.andReturn(wpt1)
.andReturn(wpt2)
.andReturn(wpt3)
.andReturn(wpt4);
// Now expect an update.
listener2.clearWaypoints();
listener2.onNewWaypoint(wpt1);
listener2.onNewWaypoint(wpt2);
listener2.onNewWaypoint(wpt3);
listener2.onNewWaypoint(wpt4);
listener2.onNewWaypointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
observer.onChange(false);
verifyAndReset();
// Unregister the other, expect internal unregistration
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener2);
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Register a second listener - it will get the same points as the previous one
locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should go to both listeners, without clearing.
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(11, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
locationIterator.expectLocationsDelivered(listener2);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Unregister listener1, switch tracks to ensure data is cleared/reloaded.
locationIterator = new FixedSizeLocationIterator(101, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(110L);
listener2.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener2);
listener2.onNewTrackPointsDone();
replay();
hub.unregisterTrackDataListener(listener1);
hub.loadTrack(TRACK_ID + 1);
verifyAndReset();
}
public void testPointsListen_beforeStart() {
}
public void testPointsListen_reRegister() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again, except only points since unregistered.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(11, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(20L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Deliver more points - should still be incremental.
locationIterator = new FixedSizeLocationIterator(21, 10, 1);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(21L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testPointsListen_reRegisterTrackChanged() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Unregister
ContentObserver observer = observerCapture.getValue();
dataSources.unregisterContentObserver(observer);
replay();
hub.unregisterTrackDataListener(listener1);
verifyAndReset();
// Register again after track changed, expect all points.
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
locationIterator = new FixedSizeLocationIterator(1, 10);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID + 1)).andReturn(10L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.loadTrack(TRACK_ID + 1);
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
}
public void testPointsListen_largeTrackSampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 200, 4, 25, 71, 120);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(200L);
listener1.clearTrackPoints();
listener2.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 4, false);
locationIterator.expectSampledLocationsDelivered(listener2, 4, true);
listener1.onNewTrackPointsDone();
listener2.onNewTrackPointsDone();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.POINT_UPDATES));
hub.registerTrackDataListener(listener2,
EnumSet.of(ListenerDataType.POINT_UPDATES, ListenerDataType.SAMPLED_OUT_POINT_UPDATES));
hub.start();
verifyAndReset();
}
public void testPointsListen_resampling() {
Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
prefs.edit().putLong("recordingTrack", TRACK_ID)
.putLong("selectedTrack", TRACK_ID).apply();
expectStart();
dataSources.registerContentObserver(
eq(TrackPointsColumns.CONTENT_URI), eq(false), capture(observerCapture));
// Deliver 30 points (no sampling happens)
FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 30, 5);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(30L);
listener1.clearTrackPoints();
locationIterator.expectLocationsDelivered(listener1);
listener1.onNewTrackPointsDone();
replay();
hub.start();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.POINT_UPDATES));
verifyAndReset();
// Now deliver 30 more (incrementally sampled)
ContentObserver observer = observerCapture.getValue();
locationIterator = new FixedSizeLocationIterator(31, 30);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(31L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(60L);
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
// Now another 30 (triggers resampling)
locationIterator = new FixedSizeLocationIterator(1, 90);
expect(providerUtils.getLocationIterator(
eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class)))
.andReturn(locationIterator);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(90L);
listener1.clearTrackPoints();
locationIterator.expectSampledLocationsDelivered(listener1, 2, false);
listener1.onNewTrackPointsDone();
replay();
observer.onChange(false);
verifyAndReset();
}
public void testLocationListen() {
// TODO
}
public void testCompassListen() throws Exception {
AndroidMock.resetToDefault(listener1);
Sensor compass = newSensor();
expect(dataSources.getSensor(Sensor.TYPE_ORIENTATION)).andReturn(compass);
Capture<SensorEventListener> listenerCapture = new Capture<SensorEventListener>();
dataSources.registerSensorListener(capture(listenerCapture), same(compass), anyInt());
Capture<LocationListener> locationListenerCapture = new Capture<LocationListener>();
dataSources.requestLocationUpdates(capture(locationListenerCapture));
SensorEvent event = newSensorEvent();
event.sensor = compass;
// First, get a dummy heading update.
listener1.onCurrentHeadingChanged(0.0);
// Then, get a heading update without a known location (thus can't calculate declination).
listener1.onCurrentHeadingChanged(42.0f);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
replay();
hub.registerTrackDataListener(listener1,
EnumSet.of(ListenerDataType.COMPASS_UPDATES, ListenerDataType.LOCATION_UPDATES));
hub.start();
SensorEventListener sensorListener = listenerCapture.getValue();
LocationListener locationListener = locationListenerCapture.getValue();
event.values[0] = 42.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
// Expect the heading update to include declination.
listener1.onCurrentHeadingChanged(52.0);
// Also expect location updates which are not relevant to us.
listener1.onProviderStateChange(isA(ProviderState.class));
AndroidMock.expectLastCall().anyTimes();
listener1.onCurrentLocationChanged(isA(Location.class));
AndroidMock.expectLastCall().anyTimes();
replay();
// Now try injecting a location update, triggering a declination update.
Location location = new Location("gps");
location.setLatitude(10.0);
location.setLongitude(20.0);
location.setAltitude(30.0);
declination = 10.0f;
locationListener.onLocationChanged(location);
sensorListener.onSensorChanged(event);
verifyAndReset();
listener1.onCurrentHeadingChanged(52.0);
replay();
// Now try changing the known declination - it should still return the old declination, since
// updates only happen sparsely.
declination = 20.0f;
sensorListener.onSensorChanged(event);
verifyAndReset();
}
private Sensor newSensor() throws Exception {
Constructor<Sensor> constructor = Sensor.class.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
}
private SensorEvent newSensorEvent() throws Exception {
Constructor<SensorEvent> constructor = SensorEvent.class.getDeclaredConstructor(int.class);
constructor.setAccessible(true);
return constructor.newInstance(3);
}
public void testDisplayPreferencesListen() throws Exception {
String metricUnitsKey = context.getString(R.string.metric_units_key);
String speedKey = context.getString(R.string.report_speed_key);
prefs.edit()
.putBoolean(metricUnitsKey, true)
.putBoolean(speedKey, true)
.apply();
Capture<OnSharedPreferenceChangeListener> listenerCapture =
new Capture<OnSharedPreferenceChangeListener>();
dataSources.registerOnSharedPreferenceChangeListener(capture(listenerCapture));
expect(listener1.onUnitsChanged(true)).andReturn(false);
expect(listener2.onUnitsChanged(true)).andReturn(false);
expect(listener1.onReportSpeedChanged(true)).andReturn(false);
expect(listener2.onReportSpeedChanged(true)).andReturn(false);
replay();
hub.registerTrackDataListener(listener1, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
hub.start();
hub.registerTrackDataListener(listener2, EnumSet.of(ListenerDataType.DISPLAY_PREFERENCES));
verifyAndReset();
expect(listener1.onReportSpeedChanged(false)).andReturn(false);
expect(listener2.onReportSpeedChanged(false)).andReturn(false);
replay();
prefs.edit()
.putBoolean(speedKey, false)
.apply();
OnSharedPreferenceChangeListener listener = listenerCapture.getValue();
listener.onSharedPreferenceChanged(prefs, speedKey);
AndroidMock.verify(dataSources, providerUtils, listener1, listener2);
AndroidMock.reset(dataSources, providerUtils, listener1, listener2);
expect(listener1.onUnitsChanged(false)).andReturn(false);
expect(listener2.onUnitsChanged(false)).andReturn(false);
replay();
prefs.edit()
.putBoolean(metricUnitsKey, false)
.apply();
listener.onSharedPreferenceChanged(prefs, metricUnitsKey);
verifyAndReset();
}
private void expectStart() {
dataSources.registerOnSharedPreferenceChangeListener(capture(preferenceListenerCapture));
}
private void replay() {
AndroidMock.replay(dataSources, providerUtils, listener1, listener2);
}
private void verifyAndReset() {
AndroidMock.verify(listener1, listener2, dataSources, providerUtils);
AndroidMock.reset(listener1, listener2, dataSources, providerUtils);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import android.graphics.Path;
import android.graphics.PointF;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import junit.framework.Assert;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock class that intercepts {@code Path}'s and records calls to
* {@code #moveTo()} and {@code #lineTo()}.
*/
public class MockPath extends Path {
/** A list of disjoined path segments. */
public final List<List<PointF>> segments = new LinkedList<List<PointF>>();
/** The total number of points in this path. */
public int totalPoints;
private List<PointF> currentSegment;
@Override
public void lineTo(float x, float y) {
super.lineTo(x, y);
Assert.assertNotNull(currentSegment);
currentSegment.add(new PointF(x, y));
totalPoints++;
}
@Override
public void moveTo(float x, float y) {
super.moveTo(x, y);
segments.add(currentSegment =
new ArrayList<PointF>(Arrays.asList(new PointF(x, y))));
totalPoints++;
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Projection;
import android.graphics.Point;
/**
* Elements for Tests for the MyTracks map overlay.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock {@code Projection} that acts as the identity matrix.
*/
public class MockProjection implements Projection {
@Override
public Point toPixels(GeoPoint in, Point out) {
return out;
}
@Override
public float metersToEquatorPixels(float meters) {
return meters;
}
@Override
public GeoPoint fromPixels(int x, int y) {
return new GeoPoint(y, x);
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathDescriptorDynamicSpeedTest extends TrackPathPainterTestCase {
public void testDynamicSpeedTrackPathDescriptor() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new DynamicSpeedTrackPathPainter(
getContext(), new DynamicSpeedTrackPathDescriptor(getContext()));
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import com.google.android.apps.mytracks.Constants;
import com.google.android.maps.mytracks.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.test.AndroidTestCase;
/**
* Tests for the {@link DynamicSpeedTrackPathDescriptor}.
*
* @author Youtao Liu
*/
public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
private Context context;
private SharedPreferences sharedPreferences;
private Editor sharedPreferencesEditor;
@Override
protected void setUp() throws Exception {
super.setUp();
context = getContext();
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
sharedPreferencesEditor = sharedPreferences.edit();
}
/**
* Tests the method {@link DynamicSpeedTrackPathDescriptor#getSpeedMargin()}
* with zero, normal and illegal value.
*/
public void testGetSpeedMargin() {
String[] actuals = { "0", "50", "99", "" };
// The default value of speedMargin is 25.
int[] expectations = { 0, 50, 99, 25 };
// Test
for (int i = 0; i < expectations.length; i++) {
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), actuals[i]);
sharedPreferencesEditor.commit();
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(expectations[i],
dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences));
}
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is null.
*/
public void testOnSharedPreferenceChanged_nullKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null);
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is not null, and not trackColorModeDynamicVariation.
*/
public void testOnSharedPreferenceChanged_otherKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is trackColorModeDynamicVariation.
*/
public void testOnSharedPreferenceChanged_trackColorModeDynamicVariationKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
// Change value in shared preferences.
sharedPreferencesEditor.putString(
"trackColorModeDynamicVariation",
Integer.toString(speedMargin + 2));
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
"trackColorModeDynamicVariation");
assertEquals(speedMargin + 2, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the values of speedMargin is "".
*/
public void testOnSharedPreferenceChanged_emptyValue() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
// Change value in shared preferences
sharedPreferencesEditor.putString(
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "");
sharedPreferencesEditor.commit();
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
context.getString(R.string.track_color_mode_dynamic_speed_variation_key));
// The default value of speedMargin is 25.
assertEquals(25, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by wrong track
* id.
*/
public void testNeedsRedraw_WrongTrackId() {
long trackId = -1;
sharedPreferencesEditor.putLong(context.getString(R.string.selected_track_key), trackId);
sharedPreferencesEditor.commit();
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(false, dynamicSpeedTrackPathDescriptor.needsRedraw());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by different
* averageMovingSpeed.
*/
public void testIsDiffereceSignificant() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
double[] averageMovingSpeeds = { 0, 30, 30, 30 };
double[] newAverageMovingSpeed = { 20, 30,
// Difference is less than CRITICAL_DIFFERENCE_PERCENTAGE
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100) / 2),
// Difference is more than CRITICAL_DIFFERENCE_PERCENTAGE
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
boolean[] expectedValues = { true, false, false, true };
double[] expectedAverageMovingSpeed = { 20, 30, 30,
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
// Test
for (int i = 0; i < newAverageMovingSpeed.length; i++) {
dynamicSpeedTrackPathDescriptor.setAverageMovingSpeed(averageMovingSpeeds[i]);
assertEquals(expectedValues[i], dynamicSpeedTrackPathDescriptor.isDifferenceSignificant(
averageMovingSpeeds[i], newAverageMovingSpeed[i]));
assertEquals(expectedAverageMovingSpeed[i],
dynamicSpeedTrackPathDescriptor.getAverageMovingSpeed());
}
}
} | Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathDescriptorFixedSpeedTest extends TrackPathPainterTestCase {
public void testFixedSpeedTrackPathDescriptor() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new DynamicSpeedTrackPathPainter(
getContext(), new FixedSpeedTrackPathDescriptor(getContext()));
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.maps;
import android.location.Location;
/**
* Tests for the MyTracks track path descriptors and painters.
*
* @author Vangelis S.
*/
public class TrackPathPainterSingleColorTest extends TrackPathPainterTestCase {
public void testSimpeColorTrackPathPainter() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
}
TrackPathPainter painter = new SingleColorTrackPathPainter(getContext());
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.