code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/* 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 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 2008 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.Badge;
import com.joelapenna.foursquared.R;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* @author jlapenna
*/
public class BadgeListAdapter extends BaseBadgeAdapter {
private LayoutInflater mInflater;
private int mLayoutToInflate;
public BadgeListAdapter(Context context) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = R.layout.badge_item;
}
public BadgeListAdapter(Context context, int layoutResource) {
super(context);
mInflater = LayoutInflater.from(context);
mLayoutToInflate = layoutResource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unnecessary
// calls to findViewById() on each row.
ViewHolder holder;
// When convertView is not null, we can reuse it directly, there is no
// need to re-inflate it. We only inflate a new View when the
// convertView supplied by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(mLayoutToInflate, null);
// Creates a ViewHolder and store references to the two children
// views we want to bind data to.
holder = new ViewHolder();
holder.icon = (ImageView)convertView.findViewById(R.id.icon);
holder.name = (TextView)convertView.findViewById(R.id.name);
holder.description = (TextView)convertView.findViewById(R.id.description);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder)convertView.getTag();
}
Badge badge = (Badge)getItem(position);
holder.name.setText(badge.getName());
if (holder.description != null) {
if (!TextUtils.isEmpty(badge.getDescription())) {
holder.description.setText(badge.getDescription());
} else {
holder.description.setText("");
}
}
return convertView;
}
static class ViewHolder {
ImageView icon;
TextView name;
TextView description;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.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 |
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.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 2008 Joe LaPenna
*/
package com.joelapenna.foursquared.widget;
import com.joelapenna.foursquare.types.User;
import android.content.Context;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public abstract class BaseUserAdapter extends BaseGroupAdapter<User> {
public BaseUserAdapter(Context context) {
super(context);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.app.LoadableListActivity;
import com.joelapenna.foursquared.util.UserUtils;
import com.joelapenna.foursquared.widget.CheckinListAdapter;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -refactored for display of straight checkins list (September 16, 2010).
*
*/
public class VenueCheckinsActivity extends LoadableListActivity {
public static final String TAG = "VenueCheckinsActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".VenueCheckinsActivity.INTENT_EXTRA_VENUE";
private SeparatedListAdapter mListAdapter;
private StateHolder mStateHolder;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
} else {
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder = new StateHolder(
(Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE),
((Foursquared) getApplication()).getUserId());
} else {
Log.e(TAG, "VenueCheckinsActivity requires a venue parcel its intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
return mStateHolder;
}
private void ensureUi() {
mListAdapter = new SeparatedListAdapter(this);
if (mStateHolder.getCheckinsYou().size() > 0) {
String title = getResources().getString(R.string.venue_activity_people_count_you);
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(mStateHolder.getCheckinsYou());
mListAdapter.addSection(title, adapter);
}
if (mStateHolder.getCheckinsFriends().size() > 0) {
String title = getResources().getString(
mStateHolder.getCheckinsOthers().size() == 1 ?
R.string.venue_activity_checkins_count_friends_single :
R.string.venue_activity_checkins_count_friends_plural,
mStateHolder.getCheckinsFriends().size());
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(mStateHolder.getCheckinsFriends());
mListAdapter.addSection(title, adapter);
}
if (mStateHolder.getCheckinsOthers().size() > 0) {
boolean others = mStateHolder.getCheckinsYou().size() +
mStateHolder.getCheckinsFriends().size() > 0;
String title = getResources().getString(
mStateHolder.getCheckinsOthers().size() == 1 ?
(others ? R.string.venue_activity_checkins_count_others_single :
R.string.venue_activity_checkins_count_others_alone_single) :
(others ? R.string.venue_activity_checkins_count_others_plural :
R.string.venue_activity_checkins_count_others_alone_plural),
mStateHolder.getCheckinsOthers().size());
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(mStateHolder.getCheckinsOthers());
mListAdapter.addSection(title, adapter);
}
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(true);
listView.setDividerHeight(0);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Checkin checkin = (Checkin) parent.getAdapter().getItem(position);
Intent intent = new Intent(VenueCheckinsActivity.this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, checkin.getUser());
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
startActivity(intent);
}
});
setTitle(getString(R.string.venue_checkins_activity_title, mStateHolder.getVenueName()));
}
private static class StateHolder {
private String mVenueName;
private Group<Checkin> mYou;
private Group<Checkin> mFriends;
private Group<Checkin> mOthers;
public StateHolder(Venue venue, String loggedInUserId) {
mVenueName = venue.getName();
mYou = new Group<Checkin>();
mFriends = new Group<Checkin>();
mOthers = new Group<Checkin>();
mYou.clear();
mFriends.clear();
mOthers.clear();
for (Checkin it : venue.getCheckins()) {
User user = it.getUser();
if (UserUtils.isFriend(user)) {
mFriends.add(it);
} else if (loggedInUserId.equals(user.getId())) {
mYou.add(it);
} else {
mOthers.add(it);
}
}
}
public String getVenueName() {
return mVenueName;
}
public Group<Checkin> getCheckinsYou() {
return mYou;
}
public Group<Checkin> getCheckinsFriends() {
return mFriends;
}
public Group<Checkin> getCheckinsOthers() {
return mOthers;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import 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.foursquare.types.Todo;
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.util.TipUtils;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.joelapenna.foursquared.widget.TodosListAdapter;
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 a user's todos. We can operate on the logged-in user,
* or a friend user, specified through the intent extras.
*
* If operating on the logged-in user, we remove items from the todo list
* if they mark a todo as done or un-mark it. If operating on another user,
* we do not remove them from the list.
*
* @date September 12, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TodosActivity extends LoadableListActivityWithViewAndHeader {
static final String TAG = "TodosActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_USER_ID = Foursquared.PACKAGE_NAME
+ ".TodosActivity.INTENT_EXTRA_USER_ID";
public static final String INTENT_EXTRA_USER_NAME = Foursquared.PACKAGE_NAME
+ ".TodosActivity.INTENT_EXTRA_USER_NAME";
private static final int ACTIVITY_TIP = 500;
private StateHolder mStateHolder;
private TodosListAdapter 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 {
// Optional user id and username, if not present, will be null and default to
// logged-in user.
mStateHolder = new StateHolder(
getIntent().getStringExtra(INTENT_EXTRA_USER_ID),
getIntent().getStringExtra(INTENT_EXTRA_USER_NAME));
mStateHolder.setRecentOnly(false);
}
ensureUi();
// Nearby todos is shown first by default so auto-fetch it if necessary.
// Nearby is the right button, not the left one, which is a bit strange
// but this was a design req.
if (!mStateHolder.getRanOnceTodosNearby()) {
mStateHolder.startTaskTodos(this, false);
}
}
@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);
setTitle(getString(R.string.todos_activity_title, mStateHolder.getUsername()));
mLayoutEmpty = inflater.inflate(
R.layout.todos_activity_empty, null);
mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
mListAdapter = new TodosListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
if (mStateHolder.getRecentOnly()) {
mListAdapter.setGroup(mStateHolder.getTodosRecent());
if (mStateHolder.getTodosRecent().size() == 0) {
if (mStateHolder.getRanOnceTodosRecent()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
} else {
mListAdapter.setGroup(mStateHolder.getTodosNearby());
if (mStateHolder.getTodosNearby().size() == 0) {
if (mStateHolder.getRanOnceTodosNearby()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
}
SegmentedButton buttons = getHeaderButton();
buttons.clearButtons();
buttons.addButtons(
getString(R.string.todos_activity_btn_recent),
getString(R.string.todos_activity_btn_nearby));
if (mStateHolder.getRecentOnly()) {
buttons.setPushedButtonIndex(0);
} else {
buttons.setPushedButtonIndex(1);
}
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
if (index == 0) {
mStateHolder.setRecentOnly(true);
mListAdapter.setGroup(mStateHolder.getTodosRecent());
if (mStateHolder.getTodosRecent().size() < 1) {
if (mStateHolder.getRanOnceTodosRecent()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTodos(TodosActivity.this, true);
}
}
} else {
mStateHolder.setRecentOnly(false);
mListAdapter.setGroup(mStateHolder.getTodosNearby());
if (mStateHolder.getTodosNearby().size() < 1) {
if (mStateHolder.getRanOnceTodosNearby()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTodos(TodosActivity.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) {
Todo todo = (Todo) parent.getAdapter().getItem(position);
if (todo.getTip() != null) {
Intent intent = new Intent(TodosActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, todo.getTip());
startActivityForResult(intent, ACTIVITY_TIP);
}
}
});
if (mStateHolder.getIsRunningTaskTodosRecent() ||
mStateHolder.getIsRunningTaskTodosNearby()) {
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.startTaskTodos(this, mStateHolder.getRecentOnly());
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// We ignore the returned to-do (if any). We search for any to-dos in our
// state holder by the linked tip ID for update.
if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) {
if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) {
updateTodo((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED));
}
}
}
private void updateTodo(Tip tip) {
mStateHolder.updateTodo(tip);
mListAdapter.notifyDataSetInvalidated();
}
private void onStartTaskTodos() {
if (mListAdapter != null) {
if (mStateHolder.getRecentOnly()) {
mStateHolder.setIsRunningTaskTodosRecent(true);
mListAdapter.setGroup(mStateHolder.getTodosRecent());
} else {
mStateHolder.setIsRunningTaskTodosNearby(true);
mListAdapter.setGroup(mStateHolder.getTodosNearby());
}
mListAdapter.notifyDataSetChanged();
}
setProgressBarIndeterminateVisibility(true);
setLoadingView();
}
private void onTaskTodosComplete(Group<Todo> group, boolean recentOnly, Exception ex) {
SegmentedButton buttons = getHeaderButton();
boolean update = false;
if (group != null) {
if (recentOnly) {
mStateHolder.setTodosRecent(group);
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTodosRecent());
update = true;
}
} else {
mStateHolder.setTodosNearby(group);
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTodosNearby());
update = true;
}
}
}
else {
if (recentOnly) {
mStateHolder.setTodosRecent(new Group<Todo>());
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTodosRecent());
update = true;
}
} else {
mStateHolder.setTodosNearby(new Group<Todo>());
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTodosNearby());
update = true;
}
}
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (recentOnly) {
mStateHolder.setIsRunningTaskTodosRecent(false);
mStateHolder.setRanOnceTodosRecent(true);
if (mStateHolder.getTodosRecent().size() == 0 &&
buttons.getSelectedButtonIndex() == 0) {
setEmptyView(mLayoutEmpty);
}
} else {
mStateHolder.setIsRunningTaskTodosNearby(false);
mStateHolder.setRanOnceTodosNearby(true);
if (mStateHolder.getTodosNearby().size() == 0 &&
buttons.getSelectedButtonIndex() == 1) {
setEmptyView(mLayoutEmpty);
}
}
if (update) {
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
if (!mStateHolder.getIsRunningTaskTodosRecent() &&
!mStateHolder.getIsRunningTaskTodosNearby()) {
setProgressBarIndeterminateVisibility(false);
}
}
/**
* Gets friends of the current user we're working for.
*/
private static class TaskTodos extends AsyncTask<Void, Void, Group<Todo>> {
private String mUserId;
private TodosActivity mActivity;
private boolean mRecentOnly;
private Exception mReason;
public TaskTodos(TodosActivity activity, String userId, boolean friendsOnly) {
mActivity = activity;
mUserId = userId;
mRecentOnly = friendsOnly;
}
@Override
protected void onPreExecute() {
mActivity.onStartTaskTodos();
}
@Override
protected Group<Todo> 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.todos(
LocationUtils.createFoursquareLocation(loc),
mUserId,
mRecentOnly,
!mRecentOnly,
30);
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Todo> todos) {
if (mActivity != null) {
mActivity.onTaskTodosComplete(todos, mRecentOnly, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskTodosComplete(null, mRecentOnly, mReason);
}
}
public void setActivity(TodosActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private Group<Todo> mTodosRecent;
private Group<Todo> mTodosNearby;
private boolean mIsRunningTaskTodosRecent;
private boolean mIsRunningTaskTodosNearby;
private boolean mRecentOnly;
private boolean mRanOnceTodosRecent;
private boolean mRanOnceTodosNearby;
private TaskTodos mTaskTodosRecent;
private TaskTodos mTaskTodosNearby;
private String mUserId;
private String mUsername;
public StateHolder(String userId, String username) {
mIsRunningTaskTodosRecent = false;
mIsRunningTaskTodosNearby = false;
mRanOnceTodosRecent = false;
mRanOnceTodosNearby = false;
mTodosRecent = new Group<Todo>();
mTodosNearby = new Group<Todo>();
mRecentOnly = false;
mUserId = userId;
mUsername = username;
}
public String getUsername() {
return mUsername;
}
public Group<Todo> getTodosRecent() {
return mTodosRecent;
}
public void setTodosRecent(Group<Todo> todosRecent) {
mTodosRecent = todosRecent;
}
public Group<Todo> getTodosNearby() {
return mTodosNearby;
}
public void setTodosNearby(Group<Todo> todosNearby) {
mTodosNearby = todosNearby;
}
public void startTaskTodos(TodosActivity activity,
boolean recentOnly) {
if (recentOnly) {
if (mIsRunningTaskTodosRecent) {
return;
}
mIsRunningTaskTodosRecent = true;
mTaskTodosRecent = new TaskTodos(activity, mUserId, recentOnly);
mTaskTodosRecent.execute();
} else {
if (mIsRunningTaskTodosNearby) {
return;
}
mIsRunningTaskTodosNearby = true;
mTaskTodosNearby = new TaskTodos(activity, mUserId, recentOnly);
mTaskTodosNearby.execute();
}
}
public void setActivity(TodosActivity activity) {
if (mTaskTodosRecent != null) {
mTaskTodosRecent.setActivity(activity);
}
if (mTaskTodosNearby != null) {
mTaskTodosNearby.setActivity(activity);
}
}
public boolean getIsRunningTaskTodosRecent() {
return mIsRunningTaskTodosRecent;
}
public void setIsRunningTaskTodosRecent(boolean isRunning) {
mIsRunningTaskTodosRecent = isRunning;
}
public boolean getIsRunningTaskTodosNearby() {
return mIsRunningTaskTodosNearby;
}
public void setIsRunningTaskTodosNearby(boolean isRunning) {
mIsRunningTaskTodosNearby = isRunning;
}
public void cancelTasks() {
if (mTaskTodosRecent != null) {
mTaskTodosRecent.setActivity(null);
mTaskTodosRecent.cancel(true);
}
if (mTaskTodosNearby != null) {
mTaskTodosNearby.setActivity(null);
mTaskTodosNearby.cancel(true);
}
}
public boolean getRecentOnly() {
return mRecentOnly;
}
public void setRecentOnly(boolean recentOnly) {
mRecentOnly = recentOnly;
}
public boolean getRanOnceTodosRecent() {
return mRanOnceTodosRecent;
}
public void setRanOnceTodosRecent(boolean ranOnce) {
mRanOnceTodosRecent = ranOnce;
}
public boolean getRanOnceTodosNearby() {
return mRanOnceTodosNearby;
}
public void setRanOnceTodosNearby(boolean ranOnce) {
mRanOnceTodosNearby = ranOnce;
}
public void updateTodo(Tip tip) {
updateTodoFromArray(tip, mTodosRecent);
updateTodoFromArray(tip, mTodosNearby);
}
private void updateTodoFromArray(Tip tip, Group<Todo> target) {
for (int i = 0, m = target.size(); i < m; i++) {
Todo todo = target.get(i);
if (todo.getTip() != null) { // Fix for old garbage todos/tips from the API.
if (todo.getTip().getId().equals(tip.getId())) {
if (mUserId == null) {
// Activity is operating on logged-in user, only removing todos
// from the list, don't have to worry about updating states.
if (!TipUtils.isTodo(tip)) {
target.remove(todo);
}
} else {
// Activity is operating on another user, so just update the status
// of the tip within the todo.
todo.getTip().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 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookUtil;
import com.facebook.android.FacebookWebViewActivity;
import com.facebook.android.Facebook.PreparedUrl;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.FriendInvitesResult;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.util.AddressBookEmailBuilder;
import com.joelapenna.foursquared.util.AddressBookUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.AddressBookEmailBuilder.ContactSimple;
import com.joelapenna.foursquared.widget.FriendSearchAddFriendAdapter;
import com.joelapenna.foursquared.widget.FriendSearchInviteNonFoursquareUserAdapter;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;
import java.util.ArrayList;
import java.util.List;
/**
* Lets the user search for friends via first+last name, phone number, or
* twitter names. Once a list of matching users is found, the user can click on
* elements in the list to send a friend request to them. When the request is
* successfully sent, that user is removed from the list. You can add the
* INPUT_TYPE key to the intent while launching the activity to control what
* type of friend search the activity will perform. Pass in one of the following
* values:
* <ul>
* <li>INPUT_TYPE_NAME_OR_PHONE</li>
* <li>INPUT_TYPE_TWITTERNAME</li>
* <li>INPUT_TYPE_ADDRESSBOOK</li>
* <li>INPUT_TYPE_ADDRESSBOOK_INVITE</li>
* </ul>
*
* @date February 11, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class AddFriendsByUserInputActivity extends Activity {
private static final String TAG = "AddFriendsByUserInputActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int DIALOG_ID_CONFIRM_INVITE_ALL = 1;
public static final String INPUT_TYPE = "com.joelapenna.foursquared.AddFriendsByUserInputActivity.INPUT_TYPE";
public static final int INPUT_TYPE_NAME_OR_PHONE = 0;
public static final int INPUT_TYPE_TWITTERNAME = 1;
public static final int INPUT_TYPE_ADDRESSBOOK = 2;
public static final int INPUT_TYPE_ADDRESSBOOK_INVITE = 3;
public static final int INPUT_TYPE_FACEBOOK = 4;
private static final int ACTIVITY_RESULT_FACEBOOK_WEBVIEW_ACTIVITY = 5;
private TextView mTextViewInstructions;
private TextView mTextViewAdditionalInstructions;
private EditText mEditInput;
private Button mBtnSearch;
private ListView mListView;
private ProgressDialog mDlgProgress;
private int mInputType;
private SeparatedListAdapter mListAdapter;
private StateHolder mStateHolder;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.add_friends_by_user_input_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
mTextViewInstructions = (TextView) findViewById(R.id.addFriendInstructionsTextView);
mTextViewAdditionalInstructions = (TextView) findViewById(R.id.addFriendInstructionsAdditionalTextView);
mEditInput = (EditText) findViewById(R.id.addFriendInputEditText);
mBtnSearch = (Button) findViewById(R.id.addFriendSearchButton);
mListView = (ListView) findViewById(R.id.addFriendResultsListView);
mListAdapter = new SeparatedListAdapter(this);
mListView.setAdapter(mListAdapter);
mListView.setItemsCanFocus(true);
mListView.setDividerHeight(0);
mBtnSearch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startSearch(mEditInput.getText().toString());
}
});
mEditInput.addTextChangedListener(mNamesFieldWatcher);
mEditInput.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL) {
startSearch(mEditInput.getText().toString());
}
return false;
}
});
mBtnSearch.setEnabled(false);
mInputType = getIntent().getIntExtra(INPUT_TYPE, INPUT_TYPE_NAME_OR_PHONE);
switch (mInputType) {
case INPUT_TYPE_TWITTERNAME:
mTextViewInstructions.setText(getResources().getString(
R.string.add_friends_by_twitter_instructions));
mEditInput.setHint(getResources().getString(R.string.add_friends_by_twitter_hint));
mEditInput.setInputType(InputType.TYPE_CLASS_TEXT);
break;
case INPUT_TYPE_ADDRESSBOOK:
mTextViewInstructions.setText(getResources().getString(
R.string.add_friends_by_addressbook_instructions));
mTextViewAdditionalInstructions.setText(getResources().getString(
R.string.add_friends_by_addressbook_additional_instructions));
mEditInput.setVisibility(View.GONE);
mBtnSearch.setVisibility(View.GONE);
break;
case INPUT_TYPE_ADDRESSBOOK_INVITE:
mTextViewInstructions.setText(getResources().getString(
R.string.add_friends_by_addressbook_instructions));
mTextViewAdditionalInstructions.setText(getResources().getString(
R.string.add_friends_by_addressbook_additional_instructions));
mEditInput.setVisibility(View.GONE);
mBtnSearch.setVisibility(View.GONE);
break;
case INPUT_TYPE_FACEBOOK:
mTextViewInstructions.setText(getResources().getString(
R.string.add_friends_by_facebook_instructions));
mTextViewAdditionalInstructions.setText(getResources().getString(
R.string.add_friends_by_facebook_additional_instructions));
mEditInput.setVisibility(View.GONE);
mBtnSearch.setVisibility(View.GONE);
break;
default:
mTextViewInstructions.setText(getResources().getString(
R.string.add_friends_by_name_or_phone_instructions));
mEditInput.setHint(getResources().getString(R.string.add_friends_by_name_or_phone_hint));
mEditInput.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
break;
}
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivityForTaskFindFriends(this);
mStateHolder.setActivityForTaskFriendRequest(this);
mStateHolder.setActivityForTaskSendInvite(this);
// If we have run before, restore matches divider.
if (mStateHolder.getRanOnce()) {
populateListFromStateHolder();
}
} else {
mStateHolder = new StateHolder();
// If we are scanning the address book, or a facebook search, we should
// kick off immediately.
switch (mInputType) {
case INPUT_TYPE_ADDRESSBOOK:
case INPUT_TYPE_ADDRESSBOOK_INVITE:
startSearch("");
break;
case INPUT_TYPE_FACEBOOK:
startFacebookWebViewActivity();
break;
}
}
}
@Override
public void onResume() {
super.onResume();
if (mStateHolder.getIsRunningTaskFindFriends()) {
startProgressBar(getResources().getString(R.string.add_friends_activity_label),
getResources().getString(R.string.add_friends_progress_bar_message_find));
} else if (mStateHolder.getIsRunningTaskSendFriendRequest()) {
startProgressBar(getResources().getString(R.string.add_friends_activity_label),
getResources()
.getString(R.string.add_friends_progress_bar_message_send_request));
} else if (mStateHolder.getIsRunningTaskSendInvite()) {
startProgressBar(getResources().getString(R.string.add_friends_activity_label),
getResources()
.getString(R.string.add_friends_progress_bar_message_send_invite));
}
}
@Override
public void onPause() {
super.onPause();
stopProgressBar();
if (isFinishing()) {
mListAdapter.removeObserver();
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTaskFindFriends(null);
mStateHolder.setActivityForTaskFriendRequest(null);
mStateHolder.setActivityForTaskSendInvite(null);
return mStateHolder;
}
private void userAdd(User user) {
startProgressBar(getResources().getString(R.string.add_friends_activity_label),
getResources().getString(R.string.add_friends_progress_bar_message_send_request));
mStateHolder.startTaskSendFriendRequest(AddFriendsByUserInputActivity.this, user.getId());
}
private void userInfo(User user) {
Intent intent = new Intent(AddFriendsByUserInputActivity.this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user);
startActivity(intent);
}
private void userInvite(ContactSimple contact) {
startProgressBar(getResources().getString(R.string.add_friends_activity_label),
getResources().getString(R.string.add_friends_progress_bar_message_send_invite));
mStateHolder.startTaskSendInvite(AddFriendsByUserInputActivity.this, contact.mEmail, false);
}
private void inviteAll() {
startProgressBar(getResources().getString(R.string.add_friends_activity_label),
getResources().getString(R.string.add_friends_progress_bar_message_send_invite));
mStateHolder.startTaskSendInvite(
AddFriendsByUserInputActivity.this, mStateHolder.getUsersNotOnFoursquareAsCommaSepString(), true);
}
private void startSearch(String input) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEditInput.getWindowToken(), 0);
mEditInput.setEnabled(false);
mBtnSearch.setEnabled(false);
startProgressBar(getResources().getString(R.string.add_friends_activity_label),
getResources().getString(R.string.add_friends_progress_bar_message_find));
mStateHolder.startTaskFindFriends(AddFriendsByUserInputActivity.this, input);
}
private void startFacebookWebViewActivity() {
Intent intent = new Intent(this, FacebookWebViewActivity.class);
intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_ACTION, Facebook.LOGIN);
intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_APP_ID,
getResources().getString(R.string.facebook_api_key));
intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_PERMISSIONS,
new String[] {}); //{"publish_stream", "read_stream", "offline_access"});
intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_DEBUG, false);
intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_CLEAR_COOKIES, true);
startActivityForResult(intent, ACTIVITY_RESULT_FACEBOOK_WEBVIEW_ACTIVITY);
}
private void startProgressBar(String title, String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, title, message);
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ID_CONFIRM_INVITE_ALL:
AlertDialog dlgInfo = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.add_friends_contacts_title_invite_all))
.setIcon(0)
.setPositiveButton(getResources().getString(R.string.yes),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
inviteAll();
}
})
.setNegativeButton(getResources().getString(R.string.no),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setMessage(getResources().getString(R.string.add_friends_contacts_message_invite_all,
String.valueOf(mStateHolder.getUsersNotOnFoursquare().size())))
.create();
dlgInfo.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
removeDialog(DIALOG_ID_CONFIRM_INVITE_ALL);
}
});
return dlgInfo;
}
return null;
}
/**
* Listen for FacebookWebViewActivity finishing, inspect success/failure and returned
* request parameters.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTIVITY_RESULT_FACEBOOK_WEBVIEW_ACTIVITY) {
// If RESULT_OK, means the request was attempted, but we still have to check the return status.
if (resultCode == RESULT_OK) {
// Check return status.
if (data.getBooleanExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_RESULT_STATUS, false)) {
// If ok, the result bundle will contain all data from the webview.
Bundle bundle = data.getBundleExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_RESULT_BUNDLE);
// We can switch on the action here, the activity echoes it back to us for convenience.
String suppliedAction = data.getStringExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_SUPPLIED_ACTION);
if (suppliedAction.equals(Facebook.LOGIN)) {
// We can now start a task to fetch foursquare friends using their facebook id.
mStateHolder.startTaskFindFriends(
AddFriendsByUserInputActivity.this, bundle.getString(Facebook.TOKEN));
}
} else {
// Error running the operation, report to user perhaps.
String error = data.getStringExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_ERROR);
Log.e(TAG, error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
finish();
}
} else {
// If the user cancelled enterting their facebook credentials, exit here too.
finish();
}
}
}
private void populateListFromStateHolder() {
mListAdapter.removeObserver();
mListAdapter = new SeparatedListAdapter(this);
if (mStateHolder.getUsersOnFoursquare().size() + mStateHolder.getUsersNotOnFoursquare().size() > 0) {
if (mStateHolder.getUsersOnFoursquare().size() > 0) {
FriendSearchAddFriendAdapter adapter =
new FriendSearchAddFriendAdapter(
this,
mButtonRowClickHandler,
((Foursquared)getApplication()).getRemoteResourceManager());
adapter.setGroup(mStateHolder.getUsersOnFoursquare());
mListAdapter.addSection(
getResources().getString(R.string.add_friends_contacts_found_on_foursqare),
adapter);
}
if (mStateHolder.getUsersNotOnFoursquare().size() > 0) {
FriendSearchInviteNonFoursquareUserAdapter adapter =
new FriendSearchInviteNonFoursquareUserAdapter(
this,
mAdapterListenerInvites);
adapter.setContacts(mStateHolder.getUsersNotOnFoursquare());
mListAdapter.addSection(
getResources().getString(R.string.add_friends_contacts_not_found_on_foursqare),
adapter);
}
} else {
Toast.makeText(this, getResources().getString(R.string.add_friends_no_matches),
Toast.LENGTH_SHORT).show();
}
mListView.setAdapter(mListAdapter);
}
private void onFindFriendsTaskComplete(FindFriendsResult result, Exception ex) {
if (result != null) {
mStateHolder.setUsersOnFoursquare(result.getUsersOnFoursquare());
mStateHolder.setUsersNotOnFoursquare(result.getUsersNotOnFoursquare());
if (result.getUsersOnFoursquare().size() + result.getUsersNotOnFoursquare().size() < 1) {
Toast.makeText(this, getResources().getString(R.string.add_friends_no_matches),
Toast.LENGTH_SHORT).show();
}
} else {
NotificationsUtil.ToastReasonForFailure(AddFriendsByUserInputActivity.this, ex);
}
populateListFromStateHolder();
mEditInput.setEnabled(true);
mBtnSearch.setEnabled(true);
mStateHolder.setIsRunningTaskFindFriends(false);
stopProgressBar();
}
private void onSendFriendRequestTaskComplete(User friendRequestRecipient, Exception ex) {
if (friendRequestRecipient != null) {
// We do a linear search to find the row to remove, ouch.
int position = 0;
for (User it : mStateHolder.getUsersOnFoursquare()) {
if (it.getId().equals(friendRequestRecipient.getId())) {
mStateHolder.getUsersOnFoursquare().remove(position);
break;
}
position++;
}
mListAdapter.notifyDataSetChanged();
Toast.makeText(AddFriendsByUserInputActivity.this,
getResources().getString(R.string.add_friends_request_sent_ok),
Toast.LENGTH_SHORT).show();
} else {
NotificationsUtil.ToastReasonForFailure(AddFriendsByUserInputActivity.this, ex);
}
mEditInput.setEnabled(true);
mBtnSearch.setEnabled(true);
mStateHolder.setIsRunningTaskSendFriendRequest(false);
stopProgressBar();
}
private void onSendInviteTaskComplete(String email, boolean isAllEmails, Exception ex) {
if (email != null) {
if (isAllEmails) {
mStateHolder.getUsersNotOnFoursquare().clear();
Toast.makeText(AddFriendsByUserInputActivity.this,
getResources().getString(R.string.add_friends_invites_sent_ok),
Toast.LENGTH_SHORT).show();
} else {
// We do a linear search to find the row to remove, ouch.
int position = 0;
for (ContactSimple it : mStateHolder.getUsersNotOnFoursquare()) {
if (it.mEmail.equals(email)) {
mStateHolder.getUsersNotOnFoursquare().remove(position);
break;
}
position++;
}
Toast.makeText(AddFriendsByUserInputActivity.this,
getResources().getString(R.string.add_friends_invite_sent_ok),
Toast.LENGTH_SHORT).show();
}
mListAdapter.notifyDataSetChanged();
} else {
NotificationsUtil.ToastReasonForFailure(AddFriendsByUserInputActivity.this, ex);
}
mEditInput.setEnabled(true);
mBtnSearch.setEnabled(true);
mStateHolder.setIsRunningTaskSendInvite(false);
stopProgressBar();
}
private static class FindFriendsTask extends AsyncTask<String, Void, FindFriendsResult> {
private AddFriendsByUserInputActivity mActivity;
private Exception mReason;
public FindFriendsTask(AddFriendsByUserInputActivity activity) {
mActivity = activity;
}
public void setActivity(AddFriendsByUserInputActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar(mActivity.getResources().getString(
R.string.add_friends_activity_label), mActivity.getResources().getString(
R.string.add_friends_progress_bar_message_find));
}
@Override
protected FindFriendsResult doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
FindFriendsResult result = new FindFriendsResult();
switch (mActivity.mInputType) {
case INPUT_TYPE_TWITTERNAME:
result.setUsersOnFoursquare(foursquare.findFriendsByTwitter(params[0]));
break;
case INPUT_TYPE_ADDRESSBOOK:
scanAddressBook(result, foursquare, foursquared, false);
break;
case INPUT_TYPE_ADDRESSBOOK_INVITE:
scanAddressBook(result, foursquare, foursquared, true);
break;
case INPUT_TYPE_FACEBOOK:
// For facebook, we need to first get all friend uids, then use that with the foursquare api.
String facebookFriendIds = getFacebookFriendIds(params[0]);
if (!TextUtils.isEmpty(facebookFriendIds)) {
result.setUsersOnFoursquare(foursquare.findFriendsByFacebook(facebookFriendIds));
} else {
result.setUsersOnFoursquare(new Group<User>());
}
break;
default:
// Combine searches for name/phone, results returned in one list.
Group<User> users = new Group<User>();
users.addAll(foursquare.findFriendsByPhone(params[0]));
users.addAll(foursquare.findFriendsByName(params[0]));
result.setUsersOnFoursquare(users);
break;
}
return result;
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "FindFriendsTask: Exception doing add friends by name", e);
mReason = e;
}
return null;
}
private String getFacebookFriendIds(String facebookToken) {
Facebook facebook = new Facebook();
facebook.setAccessToken(facebookToken);
String friendsAsJson = "";
try {
PreparedUrl purl = facebook.requestUrl("me/friends");
friendsAsJson = FacebookUtil.openUrl(purl.getUrl(), purl.getHttpMethod(), purl.getParameters());
} catch (Exception ex) {
Log.e(TAG, "Error getting facebook friends as json.", ex);
return friendsAsJson;
}
// {"data":[{"name":"Friends Name","id":"12345"}]}
StringBuilder sb = new StringBuilder(2048);
try {
JSONObject json = new JSONObject(friendsAsJson);
JSONArray friends = json.getJSONArray("data");
for (int i = 0, m = friends.length(); i < m; i++) {
JSONObject friend = friends.getJSONObject(i);
sb.append(friend.get("id"));
sb.append(",");
}
if (sb.length() > 0 && sb.charAt(sb.length()-1) == ',') {
sb.deleteCharAt(sb.length()-1);
}
}
catch (Exception ex) {
Log.e(TAG, "Error deserializing facebook friends json object.", ex);
}
return sb.toString();
}
private void scanAddressBook(FindFriendsResult result,
Foursquare foursquare,
Foursquared foursquared,
boolean invites)
throws Exception {
AddressBookUtils addr = AddressBookUtils.addressBookUtils();
AddressBookEmailBuilder bld = addr.getAllContactsEmailAddressesInfo(mActivity);
String phones = addr.getAllContactsPhoneNumbers(mActivity);
String emails = bld.getEmailsCommaSeparated();
if (!TextUtils.isEmpty(phones) || !TextUtils.isEmpty(emails)) {
FriendInvitesResult xml = foursquare.findFriendsByPhoneOrEmail(phones, emails);
result.setUsersOnFoursquare(xml.getContactsOnFoursquare());
if (invites) {
// Get a contact name for each email address we can send an invite to.
List<ContactSimple> contactsNotOnFoursquare = new ArrayList<ContactSimple>();
for (String it : xml.getContactEmailsNotOnFoursquare()) {
ContactSimple contact = new ContactSimple();
contact.mEmail = it;
contact.mName = bld.getNameForEmail(it);
contactsNotOnFoursquare.add(contact);
}
result.setUsersNotOnFoursquare(contactsNotOnFoursquare);
}
}
}
@Override
protected void onPostExecute(FindFriendsResult result) {
if (DEBUG) Log.d(TAG, "FindFriendsTask: onPostExecute()");
if (mActivity != null) {
mActivity.onFindFriendsTaskComplete(result, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onFindFriendsTaskComplete(
null, new Exception("Friend search cancelled."));
}
}
}
private static class SendFriendRequestTask extends AsyncTask<String, Void, User> {
private AddFriendsByUserInputActivity mActivity;
private Exception mReason;
public SendFriendRequestTask(AddFriendsByUserInputActivity activity) {
mActivity = activity;
}
public void setActivity(AddFriendsByUserInputActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar(mActivity.getResources().getString(
R.string.add_friends_activity_label), mActivity.getResources().getString(
R.string.add_friends_progress_bar_message_send_request));
}
@Override
protected User doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
User user = foursquare.friendSendrequest(params[0]);
return user;
} catch (Exception e) {
if (DEBUG)
Log.d(TAG, "SendFriendRequestTask: Exception doing send friend request.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(User user) {
if (DEBUG) Log.d(TAG, "SendFriendRequestTask: onPostExecute()");
if (mActivity != null) {
mActivity.onSendFriendRequestTaskComplete(user, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onSendFriendRequestTaskComplete(null, new Exception(
"Friend invitation cancelled."));
}
}
}
private static class SendInviteTask extends AsyncTask<String, Void, String> {
private AddFriendsByUserInputActivity mActivity;
private boolean mIsAllEmails;
private Exception mReason;
public SendInviteTask(AddFriendsByUserInputActivity activity, boolean isAllEmails) {
mActivity = activity;
mIsAllEmails = isAllEmails;
}
public void setActivity(AddFriendsByUserInputActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar(mActivity.getResources().getString(
R.string.add_friends_activity_label), mActivity.getResources().getString(
R.string.add_friends_progress_bar_message_send_invite));
}
@Override
protected String doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
foursquare.inviteByEmail(params[0]);
return params[0];
} catch (Exception e) {
Log.e(TAG, "SendInviteTask: Exception sending invite.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(String email) {
if (DEBUG) Log.d(TAG, "SendInviteTask: onPostExecute()");
if (mActivity != null) {
mActivity.onSendInviteTaskComplete(email, mIsAllEmails, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onSendInviteTaskComplete(null, mIsAllEmails,
new Exception("Invite send cancelled."));
}
}
}
private static class StateHolder {
FindFriendsTask mTaskFindFriends;
SendFriendRequestTask mTaskSendFriendRequest;
SendInviteTask mTaskSendInvite;
Group<User> mUsersOnFoursquare;
List<ContactSimple> mUsersNotOnFoursquare;
boolean mIsRunningTaskFindFriends;
boolean mIsRunningTaskSendFriendRequest;
boolean mIsRunningTaskSendInvite;
boolean mRanOnce;
public StateHolder() {
mUsersOnFoursquare = new Group<User>();
mUsersNotOnFoursquare = new ArrayList<ContactSimple>();
mIsRunningTaskFindFriends = false;
mIsRunningTaskSendFriendRequest = false;
mIsRunningTaskSendInvite = false;
mRanOnce = false;
}
public Group<User> getUsersOnFoursquare() {
return mUsersOnFoursquare;
}
public void setUsersOnFoursquare(Group<User> usersOnFoursquare) {
mUsersOnFoursquare = usersOnFoursquare;
mRanOnce = true;
}
public List<ContactSimple> getUsersNotOnFoursquare() {
return mUsersNotOnFoursquare;
}
public void setUsersNotOnFoursquare(List<ContactSimple> usersNotOnFoursquare) {
mUsersNotOnFoursquare = usersNotOnFoursquare;
}
public void startTaskFindFriends(AddFriendsByUserInputActivity activity, String input) {
mIsRunningTaskFindFriends = true;
mTaskFindFriends = new FindFriendsTask(activity);
mTaskFindFriends.execute(input);
}
public void startTaskSendFriendRequest(AddFriendsByUserInputActivity activity, String userId) {
mIsRunningTaskSendFriendRequest = true;
mTaskSendFriendRequest = new SendFriendRequestTask(activity);
mTaskSendFriendRequest.execute(userId);
}
public void startTaskSendInvite(AddFriendsByUserInputActivity activity, String email, boolean isAllEmails) {
mIsRunningTaskSendInvite = true;
mTaskSendInvite = new SendInviteTask(activity, isAllEmails);
mTaskSendInvite.execute(email);
}
public void setActivityForTaskFindFriends(AddFriendsByUserInputActivity activity) {
if (mTaskFindFriends != null) {
mTaskFindFriends.setActivity(activity);
}
}
public void setActivityForTaskFriendRequest(AddFriendsByUserInputActivity activity) {
if (mTaskSendFriendRequest != null) {
mTaskSendFriendRequest.setActivity(activity);
}
}
public void setActivityForTaskSendInvite(AddFriendsByUserInputActivity activity) {
if (mTaskSendInvite != null) {
mTaskSendInvite.setActivity(activity);
}
}
public void setIsRunningTaskFindFriends(boolean isRunning) {
mIsRunningTaskFindFriends = isRunning;
}
public void setIsRunningTaskSendFriendRequest(boolean isRunning) {
mIsRunningTaskSendFriendRequest = isRunning;
}
public void setIsRunningTaskSendInvite(boolean isRunning) {
mIsRunningTaskSendInvite = isRunning;
}
public boolean getIsRunningTaskFindFriends() {
return mIsRunningTaskFindFriends;
}
public boolean getIsRunningTaskSendFriendRequest() {
return mIsRunningTaskSendFriendRequest;
}
public boolean getIsRunningTaskSendInvite() {
return mIsRunningTaskSendInvite;
}
public boolean getRanOnce() {
return mRanOnce;
}
public String getUsersNotOnFoursquareAsCommaSepString() {
StringBuilder sb = new StringBuilder(2048);
for (ContactSimple it : mUsersNotOnFoursquare) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(it.mEmail);
}
return sb.toString();
}
}
private TextWatcher mNamesFieldWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mBtnSearch.setEnabled(!TextUtils.isEmpty(s));
}
};
/**
* This handler will be called when the user clicks on buttons in one of the
* listview's rows.
*/
private FriendSearchAddFriendAdapter.ButtonRowClickHandler mButtonRowClickHandler =
new FriendSearchAddFriendAdapter.ButtonRowClickHandler() {
@Override
public void onBtnClickAdd(User user) {
userAdd(user);
}
@Override
public void onInfoAreaClick(User user) {
userInfo(user);
}
};
private FriendSearchInviteNonFoursquareUserAdapter.AdapterListener mAdapterListenerInvites =
new FriendSearchInviteNonFoursquareUserAdapter.AdapterListener() {
@Override
public void onBtnClickInvite(ContactSimple contact) {
userInvite(contact);
}
@Override
public void onInfoAreaClick(ContactSimple contact) {
// We could popup an intent for this contact so they can see
// who we're talking about?
}
@Override
public void onInviteAll() {
showDialog(DIALOG_ID_CONFIRM_INVITE_ALL);
}
};
private static class FindFriendsResult {
private Group<User> mUsersOnFoursquare;
private List<ContactSimple> mUsersNotOnFoursquare;
public FindFriendsResult() {
mUsersOnFoursquare = new Group<User>();
mUsersNotOnFoursquare = new ArrayList<ContactSimple>();
}
public Group<User> getUsersOnFoursquare() {
return mUsersOnFoursquare;
}
public void setUsersOnFoursquare(Group<User> users) {
if (users != null) {
mUsersOnFoursquare = users;
}
}
public List<ContactSimple> getUsersNotOnFoursquare() {
return mUsersNotOnFoursquare;
}
public void setUsersNotOnFoursquare(List<ContactSimple> usersNotOnFoursquare) {
if (usersNotOnFoursquare != null) {
mUsersNotOnFoursquare = usersNotOnFoursquare;
}
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
class FoursquaredException extends Exception {
private static final long serialVersionUID = 1L;
public FoursquaredException(String message) {
super(message);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class LocationException extends FoursquaredException {
public LocationException() {
super("Unable to determine your location.");
}
public LocationException(String message) {
super(message);
}
private static final long serialVersionUID = 1L;
}
| Java |
/*
* Copyright (C) 2010 Mark Wyszomierski
*
* Portions Copyright (C) 2009 Xtralogic, Inc.
*/
package com.joelapenna.foursquared;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* This is taken from the android-log-collector project here:
*
* http://code.google.com/p/android-log-collector/
*
* so as we can dump the last set of system logs from the user's device at the
* bottom of their feedback email. If they are reporting a crash, the logs
* might show exceptions etc. Android 2.2+ reports this directly to the marketplace
* for us so this will be phased out eventually.
*
* @date July 8, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class SendLogActivity extends Activity
{
public final static String TAG = "com.xtralogic.android.logcollector";//$NON-NLS-1$
private static final String FEEDBACK_EMAIL_ADDRESS = "crashreport-android@foursquare.com";
public static final String ACTION_SEND_LOG = "com.xtralogic.logcollector.intent.action.SEND_LOG";//$NON-NLS-1$
public static final String EXTRA_SEND_INTENT_ACTION = "com.xtralogic.logcollector.intent.extra.SEND_INTENT_ACTION";//$NON-NLS-1$
public static final String EXTRA_DATA = "com.xtralogic.logcollector.intent.extra.DATA";//$NON-NLS-1$
public static final String EXTRA_ADDITIONAL_INFO = "com.xtralogic.logcollector.intent.extra.ADDITIONAL_INFO";//$NON-NLS-1$
public static final String EXTRA_SHOW_UI = "com.xtralogic.logcollector.intent.extra.SHOW_UI";//$NON-NLS-1$
public static final String EXTRA_FILTER_SPECS = "com.xtralogic.logcollector.intent.extra.FILTER_SPECS";//$NON-NLS-1$
public static final String EXTRA_FORMAT = "com.xtralogic.logcollector.intent.extra.FORMAT";//$NON-NLS-1$
public static final String EXTRA_BUFFER = "com.xtralogic.logcollector.intent.extra.BUFFER";//$NON-NLS-1$
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
final int MAX_LOG_MESSAGE_LENGTH = 100000;
private AlertDialog mMainDialog;
private Intent mSendIntent;
private CollectLogTask mCollectLogTask;
private ProgressDialog mProgressDialog;
private String mAdditonalInfo;
private String[] mFilterSpecs;
private String mFormat;
private String mBuffer;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mSendIntent = new Intent(Intent.ACTION_SEND);
mSendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.send_log_message_subject));
mSendIntent.setType("text/plain");
Foursquared foursquared = (Foursquared)getApplication();
StringBuilder body = new StringBuilder();
Resources res = getResources();
body.append(res.getString(R.string.feedback_more));
body.append(LINE_SEPARATOR);
body.append(res.getString(R.string.feedback_question_how_to_reproduce));
body.append(LINE_SEPARATOR);
body.append(LINE_SEPARATOR);
body.append(res.getString(R.string.feedback_question_expected_output));
body.append(LINE_SEPARATOR);
body.append(LINE_SEPARATOR);
body.append(res.getString(R.string.feedback_question_additional_information));
body.append(LINE_SEPARATOR);
body.append(LINE_SEPARATOR);
body.append("--------------------------------------");
body.append(LINE_SEPARATOR);
body.append("ver: ");
body.append(foursquared.getVersion());
body.append(LINE_SEPARATOR);
body.append("user: ");
body.append(foursquared.getUserId());
body.append(LINE_SEPARATOR);
body.append("p: ");
body.append(Build.MODEL);
body.append(LINE_SEPARATOR);
body.append("os: ");
body.append(Build.VERSION.RELEASE);
body.append(LINE_SEPARATOR);
body.append("build#: ");
body.append(Build.DISPLAY);
body.append(LINE_SEPARATOR);
body.append(LINE_SEPARATOR);
mSendIntent.putExtra(Intent.EXTRA_SUBJECT, res.getString(R.string.feedback_subject));
mSendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { FEEDBACK_EMAIL_ADDRESS });
mSendIntent.setType("message/rfc822");
mAdditonalInfo = body.toString();
mFormat = "process";
collectAndSendLog();
}
@SuppressWarnings("unchecked")
void collectAndSendLog(){
/*Usage: logcat [options] [filterspecs]
options include:
-s Set default filter to silent.
Like specifying filterspec '*:s'
-f <filename> Log to file. Default to stdout
-r [<kbytes>] Rotate log every kbytes. (16 if unspecified). Requires -f
-n <count> Sets max number of rotated logs to <count>, default 4
-v <format> Sets the log print format, where <format> is one of:
brief process tag thread raw time threadtime long
-c clear (flush) the entire log and exit
-d dump the log and then exit (don't block)
-g get the size of the log's ring buffer and exit
-b <buffer> request alternate ring buffer
('main' (default), 'radio', 'events')
-B output the log in binary
filterspecs are a series of
<tag>[:priority]
where <tag> is a log component tag (or * for all) and priority is:
V Verbose
D Debug
I Info
W Warn
E Error
F Fatal
S Silent (supress all output)
'*' means '*:d' and <tag> by itself means <tag>:v
If not specified on the commandline, filterspec is set from ANDROID_LOG_TAGS.
If no filterspec is found, filter defaults to '*:I'
If not specified with -v, format is set from ANDROID_PRINTF_LOG
or defaults to "brief"*/
ArrayList<String> list = new ArrayList<String>();
if (mFormat != null){
list.add("-v");
list.add(mFormat);
}
if (mBuffer != null){
list.add("-b");
list.add(mBuffer);
}
if (mFilterSpecs != null){
for (String filterSpec : mFilterSpecs){
list.add(filterSpec);
}
}
mCollectLogTask = (CollectLogTask) new CollectLogTask().execute(list);
}
private class CollectLogTask extends AsyncTask<ArrayList<String>, Void, StringBuilder>{
@Override
protected void onPreExecute(){
showProgressDialog(getString(R.string.send_log_acquiring_log_progress_dialog_message));
}
@Override
protected StringBuilder doInBackground(ArrayList<String>... params){
final StringBuilder log = new StringBuilder();
try{
ArrayList<String> commandLine = new ArrayList<String>();
commandLine.add("logcat");//$NON-NLS-1$
commandLine.add("-d");//$NON-NLS-1$
ArrayList<String> arguments = ((params != null) && (params.length > 0)) ? params[0] : null;
if (null != arguments){
commandLine.addAll(arguments);
}
Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null){
log.append(line);
log.append(LINE_SEPARATOR);
}
}
catch (IOException e){
Log.e(TAG, "CollectLogTask.doInBackground failed", e);//$NON-NLS-1$
}
return log;
}
@Override
protected void onPostExecute(StringBuilder log){
if (null != log){
//truncate if necessary
int keepOffset = Math.max(log.length() - MAX_LOG_MESSAGE_LENGTH, 0);
if (keepOffset > 0){
log.delete(0, keepOffset);
}
if (mAdditonalInfo != null){
log.insert(0, mAdditonalInfo);
}
mSendIntent.putExtra(Intent.EXTRA_TEXT, log.toString());
startActivity(Intent.createChooser(mSendIntent, getString(R.string.send_log_chooser_title)));
dismissProgressDialog();
dismissMainDialog();
finish();
}
else{
dismissProgressDialog();
showErrorDialog(getString(R.string.send_log_failed_to_get_log_message));
}
}
}
void showErrorDialog(String errorMessage){
new AlertDialog.Builder(this)
.setTitle(getString(R.string.app_name))
.setMessage(errorMessage)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton){
finish();
}
})
.show();
}
void dismissMainDialog(){
if (null != mMainDialog && mMainDialog.isShowing()){
mMainDialog.dismiss();
mMainDialog = null;
}
}
void showProgressDialog(String message){
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setMessage(message);
mProgressDialog.setCancelable(true);
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog){
cancellCollectTask();
finish();
}
});
mProgressDialog.show();
}
private void dismissProgressDialog(){
if (null != mProgressDialog && mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
void cancellCollectTask(){
if (mCollectLogTask != null && mCollectLogTask.getStatus() == AsyncTask.Status.RUNNING)
{
mCollectLogTask.cancel(true);
mCollectLogTask = null;
}
}
@Override
protected void onPause(){
cancellCollectTask();
dismissProgressDialog();
dismissMainDialog();
super.onPause();
}
} | Java |
package com.joelapenna.foursquared;
import com.joelapenna.foursquared.providers.GlobalSearchProvider;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
/**
* Activity that gets intents from the Quick Search Box and starts the correct
* Activity depending on the type of the data.
*
* @author Tauno Talimaa (tauntz@gmail.com)
*/
public class GlobalSearchActivity extends Activity {
private static final String TAG = GlobalSearchProvider.class.getSimpleName();
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
String dataString = intent.getDataString();
if (!TextUtils.isEmpty(dataString)) {
Uri uri = Uri.parse(intent.getDataString());
String directory = uri.getPathSegments().get(0);
if (directory.equals(GlobalSearchProvider.VENUE_DIRECTORY)) {
if (DEBUG) {
Log.d(TAG, "Viewing venue details for venue id:" + uri.getLastPathSegment());
}
Intent i = new Intent(this, VenueActivity.class);
i.setAction(Intent.ACTION_VIEW);
i.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, uri.getLastPathSegment());
startActivity(i);
finish();
} else if (directory.equals(GlobalSearchProvider.FRIEND_DIRECTORY)) {
if (DEBUG) {
Log.d(TAG, "Viewing friend details for friend id:" + uri.getLastPathSegment());
// TODO: Implement
}
}
} else {
// For now just launch search activity and assume a venue search.
Intent intentSearch = new Intent(this, SearchVenuesActivity.class);
intentSearch.setAction(Intent.ACTION_SEARCH);
if (intent.hasExtra(SearchManager.QUERY)) {
intentSearch.putExtra(SearchManager.QUERY, intent.getStringExtra(SearchManager.QUERY));
}
startActivity(intentSearch);
finish();
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.ImageUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* Takes a path to an image, then displays it by filling all available space while
* retaining w/h ratio. This is meant to be a (poor) replacement to the native
* image viewer intent on some devices. For example, the nexus-one gallery viewer
* takes about 11 seconds to start up when using the following:
*
* Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
* intent.setDataAndType(uri, "image/" + extension);
* startActivity(intent);
*
* other devices might have their own issues.
*
* We can support zooming/panning later on if it's important to users.
*
* No attempt is made to check the size of the input image, for now we're trusting
* the foursquare api is keeping these images < 200kb.
*
* The INTENT_EXTRA_ALLOW_SET_NEW_PHOTO flag lets the user pick a new photo from
* their phone for their user profile.
*
* @date July 28, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class FullSizeImageActivity extends Activity {
private static final String TAG = "FullSizeImageActivity";
public static final String INTENT_EXTRA_IMAGE_PATH = Foursquared.PACKAGE_NAME
+ ".FullSizeImageActivity.INTENT_EXTRA_IMAGE_PATH";
public static final String INTENT_EXTRA_ALLOW_SET_NEW_PHOTO = Foursquared.PACKAGE_NAME
+ ".FullSizeImageActivity.INTENT_EXTRA_ALLOW_SET_NEW_PHOTO";
public static final String INTENT_RETURN_NEW_PHOTO_PATH_DISK = Foursquared.PACKAGE_NAME
+ ".FullSizeImageActivity.INTENT_RETURN_NEW_PHOTO_PATH_DISK";
public static final String INTENT_RETURN_NEW_PHOTO_URL = Foursquared.PACKAGE_NAME
+ ".FullSizeImageActivity.INTENT_RETURN_NEW_PHOTO_URL";
private static final int ACTIVITY_REQUEST_CODE_GALLERY = 500;
private static final int DIALOG_SET_USER_PHOTO_YES_NO = 500;
private StateHolder mStateHolder;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.full_size_image_activity);
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
setPreparedResultIntent();
} else {
String imagePath = getIntent().getStringExtra(INTENT_EXTRA_IMAGE_PATH);
if (!TextUtils.isEmpty(imagePath)) {
mStateHolder = new StateHolder();
mStateHolder.setImagePath(imagePath);
mStateHolder.setAllowSetPhoto(getIntent().getBooleanExtra(
INTENT_EXTRA_ALLOW_SET_NEW_PHOTO, false));
} else {
Log.e(TAG, TAG + " requires input image path as an intent extra.");
finish();
return;
}
}
ensureUi();
}
private void ensureUi() {
ImageView iv = (ImageView)findViewById(R.id.imageView);
try {
Bitmap bmp = BitmapFactory.decodeFile(mStateHolder.getImagePath());
iv.setImageBitmap(bmp);
} catch (Exception ex) {
Log.e(TAG, "Couldn't load supplied image.", ex);
finish();
return;
}
LinearLayout llSetPhoto = (LinearLayout)findViewById(R.id.setPhotoOption);
Button btnSetPhoto = (Button)findViewById(R.id.setPhotoOptionBtn);
if (mStateHolder.getAllowSetPhoto()) {
llSetPhoto.setVisibility(View.VISIBLE);
btnSetPhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
startGalleryIntent();
}
});
} else {
llSetPhoto.setVisibility(View.GONE);
}
if (mStateHolder.getIsRunningTaskSetPhoto()) {
setProgressBarIndeterminateVisibility(true);
btnSetPhoto.setEnabled(false);
} else {
setProgressBarIndeterminateVisibility(false);
btnSetPhoto.setEnabled(true);
}
}
private void startGalleryIntent() {
try {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, ACTIVITY_REQUEST_CODE_GALLERY);
}
catch (Exception ex) {
Toast.makeText(this, getResources().getString(R.string.user_details_activity_error_no_photo_gallery),
Toast.LENGTH_SHORT).show();
}
}
private void prepareResultIntent(String newPhotoUrl) {
Intent intent = new Intent();
intent.putExtra(INTENT_RETURN_NEW_PHOTO_PATH_DISK, mStateHolder.getImagePath());
intent.putExtra(INTENT_RETURN_NEW_PHOTO_URL, newPhotoUrl);
mStateHolder.setPreparedResult(intent);
setPreparedResultIntent();
}
private void setPreparedResultIntent() {
if (mStateHolder.getPreparedResult() != null) {
setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String pathInput = null;
switch (requestCode) {
case ACTIVITY_REQUEST_CODE_GALLERY:
if (resultCode == Activity.RESULT_OK) {
try {
String [] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
pathInput = cursor.getString(column_index);
}
catch (Exception ex) {
Toast.makeText(this, getResources().getString(R.string.user_details_activity_error_set_photo_load),
Toast.LENGTH_SHORT).show();
}
// If everything worked ok, ask the user if they're sure they want to upload?
try {
String pathOutput = Environment.getExternalStorageDirectory() + "/tmp_fsquare.jpg";
ImageUtils.resampleImageAndSaveToNewLocation(pathInput, pathOutput);
mStateHolder.setImagePath(pathOutput);
ensureUi();
showDialog(DIALOG_SET_USER_PHOTO_YES_NO);
}
catch (Exception ex) {
Toast.makeText(this, getResources().getString(R.string.user_details_activity_error_set_photo_resample),
Toast.LENGTH_SHORT).show();
}
}
else {
return;
}
break;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_SET_USER_PHOTO_YES_NO:
return new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.user_details_activity_set_photo_confirm_title))
.setMessage(getResources().getString(R.string.user_details_activity_set_photo_confirm_message))
.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(FullSizeImageActivity.this);
String username = sp.getString(Preferences.PREFERENCE_LOGIN, "");
String password = sp.getString(Preferences.PREFERENCE_PASSWORD, "");
mStateHolder.startTaskSetPhoto(
FullSizeImageActivity.this, mStateHolder.getImagePath(), username, password);
}
})
.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.create();
default:
return null;
}
}
private void onTaskSetPhotoCompleteStart() {
ensureUi();
}
private void onTaskSetPhotoComplete(User user, Exception ex) {
mStateHolder.setIsRunningTaskSetPhoto(false);
if (user != null) {
Toast.makeText(this, "Photo set ok!", Toast.LENGTH_SHORT).show();
prepareResultIntent(user.getPhoto());
} else {
NotificationsUtil.ToastReasonForFailure(this, ex);
}
ensureUi();
}
private static class TaskSetPhoto extends AsyncTask<String, Void, User> {
private FullSizeImageActivity mActivity;
private Exception mReason;
public TaskSetPhoto(FullSizeImageActivity activity) {
mActivity = activity;
}
public void setActivity(FullSizeImageActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.onTaskSetPhotoCompleteStart();
}
/** Params should be image path, username, password. */
@Override
protected User doInBackground(String... params) {
try {
return ((Foursquared) mActivity.getApplication()).getFoursquare().userUpdate(
params[0], params[1], params[2]);
} catch (Exception ex) {
Log.e(TAG, "Error submitting new profile photo.", ex);
mReason = ex;
}
return null;
}
@Override
protected void onPostExecute(User user) {
if (mActivity != null) {
mActivity.onTaskSetPhotoComplete(user, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskSetPhotoComplete(null, new FoursquareException(
mActivity.getResources().getString(R.string.user_details_activity_set_photo_cancel)));
}
}
}
private static class StateHolder {
private String mImagePath;
private boolean mAllowSetPhoto;
private boolean mIsRunningTaskSetPhoto;
private TaskSetPhoto mTaskSetPhoto;
private Intent mPreparedResult;
public StateHolder() {
mAllowSetPhoto = false;
mIsRunningTaskSetPhoto = false;
}
public String getImagePath() {
return mImagePath;
}
public void setImagePath(String imagePath) {
mImagePath = imagePath;
}
public boolean getAllowSetPhoto() {
return mAllowSetPhoto;
}
public void setAllowSetPhoto(boolean allowSetPhoto) {
mAllowSetPhoto = allowSetPhoto;
}
public boolean getIsRunningTaskSetPhoto() {
return mIsRunningTaskSetPhoto;
}
public void setIsRunningTaskSetPhoto(boolean isRunning) {
mIsRunningTaskSetPhoto = isRunning;
}
public void setActivity(FullSizeImageActivity activity) {
if (mTaskSetPhoto != null) {
mTaskSetPhoto.setActivity(activity);
}
}
public void startTaskSetPhoto(FullSizeImageActivity activity,
String pathImage, String username, String password) {
if (!mIsRunningTaskSetPhoto) {
mIsRunningTaskSetPhoto = true;
mTaskSetPhoto = new TaskSetPhoto(activity);
mTaskSetPhoto.execute(pathImage, username, password);
}
}
public Intent getPreparedResult() {
return mPreparedResult;
}
public void setPreparedResult(Intent intent) {
mPreparedResult = intent;
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.location;
import com.joelapenna.foursquare.Foursquare.Location;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class LocationUtils {
public static final Location createFoursquareLocation(android.location.Location location) {
if (location == null) {
return new Location(null, null, null, null, null);
}
String geolat = null;
if (location.getLatitude() != 0.0) {
geolat = String.valueOf(location.getLatitude());
}
String geolong = null;
if (location.getLongitude() != 0.0) {
geolong = String.valueOf(location.getLongitude());
}
String geohacc = null;
if (location.hasAccuracy()) {
geohacc = String.valueOf(location.getAccuracy());
}
String geoalt = null;
if (location.hasAccuracy()) {
geoalt = String.valueOf(location.hasAltitude());
}
return new Location(geolat, geolong, geohacc, null, geoalt);
}
}
| Java |
package com.joelapenna.foursquared.location;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import java.util.Date;
import java.util.List;
import java.util.Observable;
public class BestLocationListener extends Observable implements LocationListener {
private static final String TAG = "BestLocationListener";
private static final boolean DEBUG = FoursquaredSettings.LOCATION_DEBUG;
public static final long LOCATION_UPDATE_MIN_TIME = 0;
public static final long LOCATION_UPDATE_MIN_DISTANCE = 0;
public static final long SLOW_LOCATION_UPDATE_MIN_TIME = 1000 * 60 * 5;
public static final long SLOW_LOCATION_UPDATE_MIN_DISTANCE = 50;
public static final float REQUESTED_FIRST_SEARCH_ACCURACY_IN_METERS = 100.0f;
public static final int REQUESTED_FIRST_SEARCH_MAX_DELTA_THRESHOLD = 1000 * 60 * 5;
public static final long LOCATION_UPDATE_MAX_DELTA_THRESHOLD = 1000 * 60 * 5;
private Location mLastLocation;
public BestLocationListener() {
super();
}
@Override
public void onLocationChanged(Location location) {
if (DEBUG) Log.d(TAG, "onLocationChanged: " + location);
updateLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
// do nothing.
}
@Override
public void onProviderEnabled(String provider) {
// do nothing.
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// do nothing.
}
synchronized public void onBestLocationChanged(Location location) {
if (DEBUG) Log.d(TAG, "onBestLocationChanged: " + location);
mLastLocation = location;
setChanged();
notifyObservers(location);
}
synchronized public Location getLastKnownLocation() {
return mLastLocation;
}
synchronized public void clearLastKnownLocation() {
mLastLocation = null;
}
public void updateLocation(Location location) {
if (DEBUG) {
Log.d(TAG, "updateLocation: Old: " + mLastLocation);
Log.d(TAG, "updateLocation: New: " + location);
}
// Cases where we only have one or the other.
if (location != null && mLastLocation == null) {
if (DEBUG) Log.d(TAG, "updateLocation: Null last location");
onBestLocationChanged(location);
return;
} else if (location == null) {
if (DEBUG) Log.d(TAG, "updated location is null, doing nothing");
return;
}
long now = new Date().getTime();
long locationUpdateDelta = now - location.getTime();
long lastLocationUpdateDelta = now - mLastLocation.getTime();
boolean locationIsInTimeThreshold = locationUpdateDelta <= LOCATION_UPDATE_MAX_DELTA_THRESHOLD;
boolean lastLocationIsInTimeThreshold = lastLocationUpdateDelta <= LOCATION_UPDATE_MAX_DELTA_THRESHOLD;
boolean locationIsMostRecent = locationUpdateDelta <= lastLocationUpdateDelta;
boolean accuracyComparable = location.hasAccuracy() || mLastLocation.hasAccuracy();
boolean locationIsMostAccurate = false;
if (accuracyComparable) {
// If we have only one side of the accuracy, that one is more
// accurate.
if (location.hasAccuracy() && !mLastLocation.hasAccuracy()) {
locationIsMostAccurate = true;
} else if (!location.hasAccuracy() && mLastLocation.hasAccuracy()) {
locationIsMostAccurate = false;
} else {
// If we have both accuracies, do a real comparison.
locationIsMostAccurate = location.getAccuracy() <= mLastLocation.getAccuracy();
}
}
if (DEBUG) {
Log.d(TAG, "locationIsMostRecent:\t\t\t" + locationIsMostRecent);
Log.d(TAG, "locationUpdateDelta:\t\t\t" + locationUpdateDelta);
Log.d(TAG, "lastLocationUpdateDelta:\t\t" + lastLocationUpdateDelta);
Log.d(TAG, "locationIsInTimeThreshold:\t\t" + locationIsInTimeThreshold);
Log.d(TAG, "lastLocationIsInTimeThreshold:\t" + lastLocationIsInTimeThreshold);
Log.d(TAG, "accuracyComparable:\t\t\t" + accuracyComparable);
Log.d(TAG, "locationIsMostAccurate:\t\t" + locationIsMostAccurate);
}
// Update location if its more accurate and w/in time threshold or if
// the old location is
// too old and this update is newer.
if (accuracyComparable && locationIsMostAccurate && locationIsInTimeThreshold) {
onBestLocationChanged(location);
} else if (locationIsInTimeThreshold && !lastLocationIsInTimeThreshold) {
onBestLocationChanged(location);
}
}
public boolean isAccurateEnough(Location location) {
if (location != null && location.hasAccuracy()
&& location.getAccuracy() <= REQUESTED_FIRST_SEARCH_ACCURACY_IN_METERS) {
long locationUpdateDelta = new Date().getTime() - location.getTime();
if (locationUpdateDelta < REQUESTED_FIRST_SEARCH_MAX_DELTA_THRESHOLD) {
if (DEBUG) Log.d(TAG, "Location is accurate: " + location.toString());
return true;
}
}
if (DEBUG) Log.d(TAG, "Location is not accurate: " + String.valueOf(location));
return false;
}
public void register(LocationManager locationManager, boolean gps) {
if (DEBUG) Log.d(TAG, "Registering this location listener: " + this.toString());
long updateMinTime = SLOW_LOCATION_UPDATE_MIN_TIME;
long updateMinDistance = SLOW_LOCATION_UPDATE_MIN_DISTANCE;
if (gps) {
updateMinTime = LOCATION_UPDATE_MIN_TIME;
updateMinDistance = LOCATION_UPDATE_MIN_DISTANCE;
}
List<String> providers = locationManager.getProviders(true);
int providersCount = providers.size();
for (int i = 0; i < providersCount; i++) {
String providerName = providers.get(i);
if (locationManager.isProviderEnabled(providerName)) {
updateLocation(locationManager.getLastKnownLocation(providerName));
}
// Only register with GPS if we've explicitly allowed it.
if (gps || !LocationManager.GPS_PROVIDER.equals(providerName)) {
locationManager.requestLocationUpdates(providerName, updateMinTime,
updateMinDistance, this);
}
}
}
public void unregister(LocationManager locationManager) {
if (DEBUG) Log.d(TAG, "Unregistering this location listener: " + this.toString());
locationManager.removeUpdates(this);
}
/**
* Updates the current location with the last known location without
* registering any location listeners.
*
* @param locationManager the LocationManager instance from which to
* retrieve the latest known location
*/
synchronized public void updateLastKnownLocation(LocationManager locationManager) {
List<String> providers = locationManager.getProviders(true);
for (int i = 0, providersCount = providers.size(); i < providersCount; i++) {
String providerName = providers.get(i);
if (locationManager.isProviderEnabled(providerName)) {
updateLocation(locationManager.getLastKnownLocation(providerName));
}
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.appwidget;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.util.VenueUtils;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.MainActivity;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.UserDetailsActivity;
import com.joelapenna.foursquared.app.FoursquaredService;
import com.joelapenna.foursquared.util.DumpcatcherHelper;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.StringFormatters;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import java.io.IOException;
import java.util.Date;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FriendsAppWidgetProvider extends AppWidgetProvider {
private static final String TAG = "FriendsAppWidgetProvider";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int[][] WIDGET_VIEW_IDS = {
{
R.id.widgetItem0, R.id.photo0, R.id.user0, R.id.time0, R.id.location0
}, {
R.id.widgetItem1, R.id.photo1, R.id.user1, R.id.time1, R.id.location1
}, {
R.id.widgetItem2, R.id.photo2, R.id.user2, R.id.time2, R.id.location2
}, {
R.id.widgetItem3, R.id.photo3, R.id.user3, R.id.time3, R.id.location3
}, {
R.id.widgetItem4, R.id.photo4, R.id.user4, R.id.time4, R.id.location4
}
};
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
if (DEBUG) Log.d(TAG, "onUpdate()");
Intent intent = new Intent(context, FoursquaredService.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
context.startService(intent);
}
public static void updateAppWidget(Context context, RemoteResourceManager rrm,
AppWidgetManager appWidgetManager, Integer appWidgetId, Group<Checkin> checkins) {
if (DEBUG) Log.d(TAG, "updateAppWidget: " + String.valueOf(appWidgetId));
// Get the layout for the App Widget and attach an on-click listener to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.friends_appwidget);
if (DEBUG) Log.d(TAG, "adding header intent: " + String.valueOf(appWidgetId));
Intent baseIntent = new Intent(context, MainActivity.class);
views.setOnClickPendingIntent(R.id.widgetHeader, PendingIntent.getActivity(context, 0,
baseIntent, 0));
if (DEBUG) Log.d(TAG, "adding footer intent: " + String.valueOf(appWidgetId));
baseIntent = new Intent(context, FoursquaredService.class);
baseIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
views.setOnClickPendingIntent(R.id.widgetFooter, PendingIntent.getService(context, 0,
baseIntent, 0));
// Now hide all views if checkins is null (a sign of not being logged in), or populate the
// checkins.
if (checkins == null) {
if (DEBUG) Log.d(TAG, "checkins is null, hiding UI.");
views.setViewVisibility(R.id.widgetNotLoggedInTextView, View.VISIBLE);
for (int i = 0; i < WIDGET_VIEW_IDS.length; i++) {
hideCheckinView(views, WIDGET_VIEW_IDS[i]);
}
} else {
if (DEBUG) Log.d(TAG, "Displaying checkins");
views.setViewVisibility(R.id.widgetNotLoggedInTextView, View.GONE);
int numCheckins = checkins.size();
for (int i = 0; i < WIDGET_VIEW_IDS.length; i++) {
if (i < numCheckins) {
updateCheckinView(context, rrm, views, checkins.get(i), WIDGET_VIEW_IDS[i]);
} else {
hideCheckinView(views, WIDGET_VIEW_IDS[i]);
}
}
}
// Lastly, update the refresh timestamp
CharSequence timestamp = DateUtils.formatDateTime(context, new Date().getTime(),
DateUtils.FORMAT_SHOW_TIME);
views.setTextViewText(R.id.widgetFooter, context.getResources().getString(
R.string.friends_appwidget_footer_text, timestamp));
// Tell the AppWidgetManager to perform an update on the current App Widget
try {
appWidgetManager.updateAppWidget(appWidgetId, views);
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "updateAppWidget crashed: ", e);
DumpcatcherHelper.sendException(e);
}
}
private static void updateCheckinView(Context context, RemoteResourceManager rrm,
RemoteViews views, Checkin checkin, int[] viewIds) {
int viewId = viewIds[0];
int photoViewId = viewIds[1];
int userViewId = viewIds[2];
int timeViewId = viewIds[3];
int locationViewId = viewIds[4];
final User user = checkin.getUser();
final Uri photoUri = Uri.parse(user.getPhoto());
views.setViewVisibility(viewId, View.VISIBLE);
Intent baseIntent;
baseIntent = new Intent(context, UserDetailsActivity.class);
baseIntent.putExtra(UserDetailsActivity.EXTRA_USER_ID, checkin.getUser().getId());
baseIntent.setData(Uri.parse("https://foursquare.com/user/" + checkin.getUser().getId()));
views.setOnClickPendingIntent(viewId, PendingIntent.getActivity(context, 0, baseIntent, 0));
try {
Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(photoUri));
views.setImageViewBitmap(photoViewId, bitmap);
} catch (IOException e) {
if (Foursquare.MALE.equals(checkin.getUser().getGender())) {
views.setImageViewResource(photoViewId, R.drawable.blank_boy);
} else {
views.setImageViewResource(photoViewId, R.drawable.blank_girl);
}
}
views.setTextViewText(userViewId, StringFormatters.getUserAbbreviatedName(user));
views.setTextViewText(timeViewId, StringFormatters.getRelativeTimeSpanString(checkin
.getCreated()));
if (VenueUtils.isValid(checkin.getVenue())) {
views.setTextViewText(locationViewId, checkin.getVenue().getName());
} else {
views.setTextViewText(locationViewId, "");
}
}
private static void hideCheckinView(RemoteViews views, int[] viewIds) {
views.setViewVisibility(viewIds[0], View.GONE);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquared.preferences.Preferences;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
/**
* Used to show a prompt to the user before the app runs. Some new marketplace vendors have
* been asking this so they can prompt the user and tell them that the app uses internet
* connections, which is not unlimited usage under many plans. This really should be handled
* by the install screen which shows other permissions used.
*
* To enable this activity, just set it as the LAUNCHER in the manifest file. If the tag is
* not added in the manifest file, this activity is never used.
*
* You can modify these text items in strings.xml to modify the appearance of the activity:
* <ul>
* <li>prelaunch_text</li>
* <li>prelaunch_button</li>
* <li>prelaunch_checkbox_dont_show_again</li>
* </ul>
*
* @date May 15, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class PrelaunchActivity extends Activity {
public static final String TAG = "PrelaunchActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
setContentView(R.layout.prelaunch_activity);
// If user doesn't want to be reminded anymore, just go to main activity.
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
Preferences.PREFERENCE_SHOW_PRELAUNCH_ACTIVITY, false) == false) {
startMainActivity();
} else {
ensureUi();
}
}
private void ensureUi() {
Button buttonOk = (Button) findViewById(R.id.btnOk);
buttonOk.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
goToMain(false);
}
});
}
private void goToMain(boolean dontRemind) {
// Don't show this startup screen anymore.
CheckBox checkboxDontShowAgain = (CheckBox)findViewById(R.id.checkboxDontShowAgain);
if (checkboxDontShowAgain.isChecked()) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putBoolean(Preferences.PREFERENCE_SHOW_PRELAUNCH_ACTIVITY, false).commit();
}
startMainActivity();
}
private void startMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
} | Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.app.LoadableListActivity;
import com.joelapenna.foursquared.location.BestLocationListener;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.VenueUtils;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.VenueListAdapter;
import android.app.Activity;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Refactored to allow NearbyVenuesMapActivity to list to search results.
*/
public class NearbyVenuesActivity extends LoadableListActivity {
static final String TAG = "NearbyVenuesActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_STARTUP_GEOLOC_DELAY = Foursquared.PACKAGE_NAME
+ ".NearbyVenuesActivity.INTENT_EXTRA_STARTUP_GEOLOC_DELAY";
private static final int MENU_REFRESH = 0;
private static final int MENU_ADD_VENUE = 1;
private static final int MENU_SEARCH = 2;
private static final int MENU_MAP = 3;
private static final int RESULT_CODE_ACTIVITY_VENUE = 1;
private StateHolder mStateHolder = new StateHolder();
private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver();
private ListView mListView;
private SeparatedListAdapter mListAdapter;
private LinearLayout mFooterView;
private TextView mTextViewFooter;
private Handler mHandler;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
mHandler = new Handler();
mListView = getListView();
mListAdapter = new SeparatedListAdapter(this);
mListView.setAdapter(mListAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Venue venue = (Venue) parent.getAdapter().getItem(position);
startItemActivity(venue);
}
});
// We can dynamically add a footer to our loadable listview.
LayoutInflater inflater = LayoutInflater.from(this);
mFooterView = (LinearLayout)inflater.inflate(R.layout.geo_loc_address_view, null);
mTextViewFooter = (TextView)mFooterView.findViewById(R.id.footerTextView);
LinearLayout llMain = (LinearLayout)findViewById(R.id.main);
llMain.addView(mFooterView);
// Check if we're returning from a configuration change.
if (getLastNonConfigurationInstance() != null) {
if (DEBUG) Log.d(TAG, "Restoring state.");
mStateHolder = (StateHolder) getLastNonConfigurationInstance();
mStateHolder.setActivity(this);
} else {
mStateHolder = new StateHolder();
mStateHolder.setQuery("");
}
// Start a new search if one is not running or we have no results.
if (mStateHolder.getIsRunningTask()) {
setProgressBarIndeterminateVisibility(true);
putSearchResultsInAdapter(mStateHolder.getResults());
ensureTitle(false);
} else if (mStateHolder.getResults().size() == 0) {
long firstLocDelay = 0L;
if (getIntent().getExtras() != null) {
firstLocDelay = getIntent().getLongExtra(INTENT_EXTRA_STARTUP_GEOLOC_DELAY, 0L);
}
startTask(firstLocDelay);
} else {
onTaskComplete(mStateHolder.getResults(), mStateHolder.getReverseGeoLoc(), null);
}
populateFooter(mStateHolder.getReverseGeoLoc());
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public void onResume() {
super.onResume();
if (DEBUG) Log.d(TAG, "onResume");
((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver);
if (isFinishing()) {
mStateHolder.cancelAllTasks();
mListAdapter.removeObserver();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) //
.setIcon(R.drawable.ic_menu_refresh);
menu.add(Menu.NONE, MENU_SEARCH, Menu.NONE, R.string.search_label) //
.setIcon(R.drawable.ic_menu_search) //
.setAlphabeticShortcut(SearchManager.MENU_KEY);
menu.add(Menu.NONE, MENU_ADD_VENUE, Menu.NONE, R.string.nearby_menu_add_venue) //
.setIcon(R.drawable.ic_menu_add);
// Shows a map of all nearby venues, works but not going into this version.
//menu.add(Menu.NONE, MENU_MAP, Menu.NONE, "Map")
// .setIcon(R.drawable.ic_menu_places);
MenuUtils.addPreferencesToMenu(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
if (mStateHolder.getIsRunningTask() == false) {
startTask();
}
return true;
case MENU_SEARCH:
Intent intent = new Intent(NearbyVenuesActivity.this, SearchVenuesActivity.class);
intent.setAction(Intent.ACTION_SEARCH);
startActivity(intent);
return true;
case MENU_ADD_VENUE:
startActivity(new Intent(NearbyVenuesActivity.this, AddVenueActivity.class));
return true;
case MENU_MAP:
startActivity(new Intent(NearbyVenuesActivity.this, NearbyVenuesMapActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public int getNoSearchResultsStringId() {
return R.string.no_nearby_venues;
}
public void putSearchResultsInAdapter(Group<Group<Venue>> searchResults) {
if (DEBUG) Log.d(TAG, "putSearchResultsInAdapter");
mListAdapter.removeObserver();
mListAdapter = new SeparatedListAdapter(this);
if (searchResults != null && searchResults.size() > 0) {
int groupCount = searchResults.size();
for (int groupsIndex = 0; groupsIndex < groupCount; groupsIndex++) {
Group<Venue> group = searchResults.get(groupsIndex);
if (group.size() > 0) {
VenueListAdapter groupAdapter = new VenueListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
groupAdapter.setGroup(group);
if (DEBUG) Log.d(TAG, "Adding Section: " + group.getType());
mListAdapter.addSection(group.getType(), groupAdapter);
}
}
} else {
setEmptyView();
}
mListView.setAdapter(mListAdapter);
}
private void startItemActivity(Venue venue) {
Intent intent = new Intent(NearbyVenuesActivity.this, VenueActivity.class);
if (mStateHolder.isFullyLoadedVenue(venue.getId())) {
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE, venue);
} else {
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
}
startActivityForResult(intent, RESULT_CODE_ACTIVITY_VENUE);
}
private void ensureTitle(boolean finished) {
if (finished) {
setTitle(getString(R.string.title_search_finished_noquery));
} else {
setTitle(getString(R.string.title_search_inprogress_noquery));
}
}
private void populateFooter(String reverseGeoLoc) {
mFooterView.setVisibility(View.VISIBLE);
mTextViewFooter.setText(reverseGeoLoc);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_CODE_ACTIVITY_VENUE:
if (resultCode == Activity.RESULT_OK && data.hasExtra(VenueActivity.EXTRA_VENUE_RETURNED)) {
Venue venue = (Venue)data.getParcelableExtra(VenueActivity.EXTRA_VENUE_RETURNED);
mStateHolder.updateVenue(venue);
mListAdapter.notifyDataSetInvalidated();
}
break;
}
}
private long getClearGeolocationOnSearch() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean cacheGeolocation = settings.getBoolean(Preferences.PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES, true);
if (cacheGeolocation) {
return 0L;
} else {
Foursquared foursquared = ((Foursquared) getApplication());
foursquared.clearLastKnownLocation();
foursquared.removeLocationUpdates(mSearchLocationObserver);
foursquared.requestLocationUpdates(mSearchLocationObserver);
return 2000L;
}
}
/** If location changes, auto-start a nearby venues search. */
private class SearchLocationObserver implements Observer {
private boolean mRequestedFirstSearch = false;
@Override
public void update(Observable observable, Object data) {
Location location = (Location) data;
// Fire a search if we haven't done so yet.
if (!mRequestedFirstSearch
&& ((BestLocationListener) observable).isAccurateEnough(location)) {
mRequestedFirstSearch = true;
if (mStateHolder.getIsRunningTask() == false) {
// Since we were told by the system that location has changed, no need to make the
// task wait before grabbing the current location.
mHandler.post(new Runnable() {
public void run() {
startTask(0L);
}
});
}
}
}
}
private void startTask() {
startTask(getClearGeolocationOnSearch());
}
private void startTask(long geoLocDelayTimeInMs) {
if (mStateHolder.getIsRunningTask() == false) {
setProgressBarIndeterminateVisibility(true);
ensureTitle(false);
if (mStateHolder.getResults().size() == 0) {
setLoadingView("");
}
mStateHolder.startTask(this, mStateHolder.getQuery(), geoLocDelayTimeInMs);
}
}
private void onTaskComplete(Group<Group<Venue>> result, String reverseGeoLoc, Exception ex) {
if (result != null) {
mStateHolder.setResults(result);
mStateHolder.setReverseGeoLoc(reverseGeoLoc);
} else {
mStateHolder.setResults(new Group<Group<Venue>>());
NotificationsUtil.ToastReasonForFailure(NearbyVenuesActivity.this, ex);
}
populateFooter(mStateHolder.getReverseGeoLoc());
putSearchResultsInAdapter(mStateHolder.getResults());
setProgressBarIndeterminateVisibility(false);
ensureTitle(true);
mStateHolder.cancelAllTasks();
}
/** Handles the work of finding nearby venues. */
private static class SearchTask extends AsyncTask<Void, Void, Group<Group<Venue>>> {
private NearbyVenuesActivity mActivity;
private Exception mReason = null;
private String mQuery;
private long mSleepTimeInMs;
private Foursquare mFoursquare;
private String mReverseGeoLoc; // Filled in after execution.
private String mNoLocException;
private String mLabelNearby;
public SearchTask(NearbyVenuesActivity activity, String query, long sleepTimeInMs) {
super();
mActivity = activity;
mQuery = query;
mSleepTimeInMs = sleepTimeInMs;
mFoursquare = ((Foursquared)activity.getApplication()).getFoursquare();
mNoLocException = activity.getResources().getString(R.string.nearby_venues_no_location);
mLabelNearby = activity.getResources().getString(R.string.nearby_venues_label_nearby);
}
@Override
public void onPreExecute() {
}
@Override
public Group<Group<Venue>> doInBackground(Void... params) {
try {
// If the user has chosen to clear their geolocation on each search, wait briefly
// for a new fix to come in. The two-second wait time is arbitrary and can be
// changed to something more intelligent.
if (mSleepTimeInMs > 0L) {
Thread.sleep(mSleepTimeInMs);
}
// Get last known location.
Location location = ((Foursquared) mActivity.getApplication()).getLastKnownLocation();
if (location == null) {
throw new FoursquareException(mNoLocException);
}
// Get the venues.
Group<Group<Venue>> results = mFoursquare.venues(LocationUtils
.createFoursquareLocation(location), mQuery, 30);
// Try to get our reverse geolocation.
mReverseGeoLoc = getGeocode(mActivity, location);
return results;
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
public void onPostExecute(Group<Group<Venue>> groups) {
if (mActivity != null) {
mActivity.onTaskComplete(groups, mReverseGeoLoc, mReason);
}
}
private String getGeocode(Context context, Location location) {
Geocoder geocoded = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoded.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
StringBuilder sb = new StringBuilder(128);
sb.append(mLabelNearby);
sb.append(" ");
sb.append(address.getAddressLine(0));
if (addresses.size() > 1) {
sb.append(", ");
sb.append(address.getAddressLine(1));
}
if (addresses.size() > 2) {
sb.append(", ");
sb.append(address.getAddressLine(2));
}
if (!TextUtils.isEmpty(address.getLocality())) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(address.getLocality());
}
return sb.toString();
}
} catch (Exception ex) {
if (DEBUG) Log.d(TAG, "SearchTask: error geocoding current location.", ex);
}
return null;
}
public void setActivity(NearbyVenuesActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private Group<Group<Venue>> mResults;
private String mQuery;
private String mReverseGeoLoc;
private SearchTask mSearchTask;
private Set<String> mFullyLoadedVenueIds;
public StateHolder() {
mResults = new Group<Group<Venue>>();
mSearchTask = null;
mFullyLoadedVenueIds = new HashSet<String>();
}
public String getQuery() {
return mQuery;
}
public void setQuery(String query) {
mQuery = query;
}
public String getReverseGeoLoc() {
return mReverseGeoLoc;
}
public void setReverseGeoLoc(String reverseGeoLoc) {
mReverseGeoLoc = reverseGeoLoc;
}
public Group<Group<Venue>> getResults() {
return mResults;
}
public void setResults(Group<Group<Venue>> results) {
mResults = results;
}
public void startTask(NearbyVenuesActivity activity, String query, long sleepTimeInMs) {
mSearchTask = new SearchTask(activity, query, sleepTimeInMs);
mSearchTask.execute();
}
public boolean getIsRunningTask() {
return mSearchTask != null;
}
public void cancelAllTasks() {
if (mSearchTask != null) {
mSearchTask.cancel(true);
mSearchTask = null;
}
}
public void setActivity(NearbyVenuesActivity activity) {
if (mSearchTask != null) {
mSearchTask.setActivity(activity);
}
}
public void updateVenue(Venue venue) {
for (Group<Venue> it : mResults) {
for (int j = 0; j < it.size(); j++) {
if (it.get(j).getId().equals(venue.getId())) {
// The /venue api call does not supply the venue's distance value,
// so replace it manually here.
Venue replaced = it.get(j);
Venue replacer = VenueUtils.cloneVenue(venue);
replacer.setDistance(replaced.getDistance());
it.set(j, replacer);
mFullyLoadedVenueIds.add(replacer.getId());
}
}
}
}
public boolean isFullyLoadedVenue(String vid) {
return mFullyLoadedVenueIds.contains(vid);
}
}
}
| Java |
/**
* 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 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.types.Badge;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquared.widget.BadgeWithIconListAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
/**
* Shows a listing of all the badges the user has earned. Right not it shows only
* the earned badges, we can add an additional display flag to also display badges
* the user has yet to unlock as well. This will show them what they're missing
* which would be fun to see.
*
* @date March 10, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class BadgesActivity extends Activity {
private static final String TAG = "BadgesActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_BADGE_ARRAY_LIST_PARCEL = Foursquared.PACKAGE_NAME
+ ".BadgesActivity.EXTRA_BADGE_ARRAY_LIST_PARCEL";
public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME
+ ".BadgesActivity.EXTRA_USER_NAME";
private static final int DIALOG_ID_INFO = 1;
private GridView mBadgesGrid;
private BadgeWithIconListAdapter mListAdapter;
private StateHolder mStateHolder;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.badges_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
} else {
if (getIntent().hasExtra(EXTRA_BADGE_ARRAY_LIST_PARCEL) && getIntent().hasExtra(EXTRA_USER_NAME)) {
mStateHolder = new StateHolder(getIntent().getStringExtra(EXTRA_USER_NAME));
// Can't jump from ArrayList to Group, argh.
ArrayList<Badge> badges = getIntent().getExtras().getParcelableArrayList(
EXTRA_BADGE_ARRAY_LIST_PARCEL);
Group<Badge> group = new Group<Badge>();
for (Badge it : badges) {
group.add(it);
}
mStateHolder.setBadges(group);
} else {
Log.e(TAG, "BadgesActivity requires a badge ArrayList pareclable in its intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
return mStateHolder;
}
private void ensureUi() {
mBadgesGrid = (GridView)findViewById(R.id.badgesGrid);
mListAdapter = new BadgeWithIconListAdapter(this,
((Foursquared)getApplication()).getRemoteResourceManager());
mListAdapter.setGroup(mStateHolder.getBadges());
mBadgesGrid.setAdapter(mListAdapter);
mBadgesGrid.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
Badge badge = (Badge)mListAdapter.getItem(position);
showDialogInfo(badge.getName(), badge.getDescription(), badge.getIcon());
}
});
setTitle(getString(R.string.badges_activity_title, mStateHolder.getUsername()));
}
private void showDialogInfo(String title, String message, String badgeIconUrl) {
mStateHolder.setDlgInfoTitle(title);
mStateHolder.setDlgInfoMessage(message);
mStateHolder.setDlgInfoBadgeIconUrl(badgeIconUrl);
showDialog(DIALOG_ID_INFO);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_ID_INFO:
AlertDialog dlgInfo = new AlertDialog.Builder(this)
.setTitle(mStateHolder.getDlgInfoTitle())
.setIcon(0)
.setMessage(mStateHolder.getDlgInfoMessage()).create();
dlgInfo.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
removeDialog(DIALOG_ID_INFO);
}
});
try {
Uri icon = Uri.parse(mStateHolder.getDlgInfoBadgeIconUrl());
dlgInfo.setIcon(new BitmapDrawable(((Foursquared) getApplication())
.getRemoteResourceManager().getInputStream(icon)));
} catch (Exception e) {
Log.e(TAG, "Error loading badge dialog!", e);
dlgInfo.setIcon(R.drawable.default_on);
}
return dlgInfo;
}
return null;
}
private static class StateHolder {
private String mUsername;
private Group<Badge> mBadges;
private String mDlgInfoTitle;
private String mDlgInfoMessage;
private String mDlgInfoBadgeIconUrl;
public StateHolder(String username) {
mUsername = username;
mBadges = new Group<Badge>();
}
public String getUsername() {
return mUsername;
}
public Group<Badge> getBadges() {
return mBadges;
}
public void setBadges(Group<Badge> badges) {
mBadges = badges;
}
public String getDlgInfoTitle() {
return mDlgInfoTitle;
}
public void setDlgInfoTitle(String text) {
mDlgInfoTitle = text;
}
public String getDlgInfoMessage() {
return mDlgInfoMessage;
}
public void setDlgInfoMessage(String text) {
mDlgInfoMessage = text;
}
public String getDlgInfoBadgeIconUrl() {
return mDlgInfoBadgeIconUrl;
}
public void setDlgInfoBadgeIconUrl(String url) {
mDlgInfoBadgeIconUrl = url;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.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.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 tips of a user, but not the logged-in user. This is pretty much a copy-paste
* of TipsActivity, but there are enough small differences to put it in its own activity.
* The direction of this activity is unknown too, so separating i here.
*
* @date September 23, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserDetailsTipsActivity extends LoadableListActivityWithViewAndHeader {
static final String TAG = "UserDetailsTipsActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_USER_ID = Foursquared.PACKAGE_NAME
+ ".UserDetailsTipsActivity.INTENT_EXTRA_USER_ID";
public static final String INTENT_EXTRA_USER_NAME = Foursquared.PACKAGE_NAME
+ ".UserDetailsTipsActivity.INTENT_EXTRA_USER_NAME";
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 {
if (getIntent().hasExtra(INTENT_EXTRA_USER_ID) && getIntent().hasExtra(INTENT_EXTRA_USER_NAME)) {
mStateHolder = new StateHolder(
getIntent().getStringExtra(INTENT_EXTRA_USER_ID),
getIntent().getStringExtra(INTENT_EXTRA_USER_NAME));
mStateHolder.setRecentOnly(true);
} else {
Log.e(TAG, TAG + " requires user ID and name in intent extras.");
finish();
return;
}
}
ensureUi();
// Friend tips is shown first by default so auto-fetch it if necessary.
if (!mStateHolder.getRanOnceTipsRecent()) {
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_venue_list_item);
if (mStateHolder.getRecentOnly()) {
mListAdapter.setGroup(mStateHolder.getTipsRecent());
if (mStateHolder.getTipsRecent().size() == 0) {
if (mStateHolder.getRanOnceTipsRecent()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
} else {
mListAdapter.setGroup(mStateHolder.getTipsPopular());
if (mStateHolder.getTipsPopular().size() == 0) {
if (mStateHolder.getRanOnceTipsPopular()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
}
SegmentedButton buttons = getHeaderButton();
buttons.clearButtons();
buttons.addButtons(
getString(R.string.user_details_tips_activity_btn_recent),
getString(R.string.user_details_tips_activity_btn_popular));
if (mStateHolder.mRecentOnly) {
buttons.setPushedButtonIndex(0);
} else {
buttons.setPushedButtonIndex(1);
}
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
if (index == 0) {
mStateHolder.setRecentOnly(true);
mListAdapter.setGroup(mStateHolder.getTipsRecent());
if (mStateHolder.getTipsRecent().size() < 1) {
if (mStateHolder.getRanOnceTipsRecent()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(UserDetailsTipsActivity.this, true);
}
}
} else {
mStateHolder.setRecentOnly(false);
mListAdapter.setGroup(mStateHolder.getTipsPopular());
if (mStateHolder.getTipsPopular().size() < 1) {
if (mStateHolder.getRanOnceTipsPopular()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(UserDetailsTipsActivity.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(UserDetailsTipsActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip);
startActivityForResult(intent, ACTIVITY_TIP);
}
});
if (mStateHolder.getIsRunningTaskTipsRecent() ||
mStateHolder.getIsRunningTaskTipsPopular()) {
setProgressBarIndeterminateVisibility(true);
} else {
setProgressBarIndeterminateVisibility(false);
}
setTitle(getString(R.string.user_details_tips_activity_title, mStateHolder.getUsername()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh)
.setIcon(R.drawable.ic_menu_refresh);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
mStateHolder.startTaskTips(this, mStateHolder.getRecentOnly());
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.i(TAG, "onActivityResult(), return tip intent extra found, processing.");
updateTip((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED));
} else {
Log.i(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.getRecentOnly()) {
mStateHolder.setIsRunningTaskTipsRecent(true);
mListAdapter.setGroup(mStateHolder.getTipsRecent());
} else {
mStateHolder.setIsRunningTaskTipsPopular(true);
mListAdapter.setGroup(mStateHolder.getTipsPopular());
}
mListAdapter.notifyDataSetChanged();
}
setProgressBarIndeterminateVisibility(true);
setLoadingView();
}
private void onTaskTipsComplete(Group<Tip> group, boolean recentOnly, Exception ex) {
SegmentedButton buttons = getHeaderButton();
boolean update = false;
if (group != null) {
if (recentOnly) {
mStateHolder.setTipsRecent(group);
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsRecent());
update = true;
}
} else {
mStateHolder.setTipsPopular(group);
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsPopular());
update = true;
}
}
}
else {
if (recentOnly) {
mStateHolder.setTipsRecent(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsRecent());
update = true;
}
} else {
mStateHolder.setTipsPopular(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsPopular());
update = true;
}
}
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (recentOnly) {
mStateHolder.setIsRunningTaskTipsRecent(false);
mStateHolder.setRanOnceTipsRecent(true);
if (mStateHolder.getTipsRecent().size() == 0 &&
buttons.getSelectedButtonIndex() == 0) {
setEmptyView(mLayoutEmpty);
}
} else {
mStateHolder.setIsRunningTaskTipsPopular(false);
mStateHolder.setRanOnceTipsPopular(true);
if (mStateHolder.getTipsPopular().size() == 0 &&
buttons.getSelectedButtonIndex() == 1) {
setEmptyView(mLayoutEmpty);
}
}
if (update) {
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
if (!mStateHolder.getIsRunningTaskTipsRecent() &&
!mStateHolder.getIsRunningTaskTipsPopular()) {
setProgressBarIndeterminateVisibility(false);
}
}
private static class TaskTips extends AsyncTask<Void, Void, Group<Tip>> {
private String mUserId;
private UserDetailsTipsActivity mActivity;
private boolean mRecentOnly;
private Exception mReason;
public TaskTips(UserDetailsTipsActivity activity, String userId, boolean recentOnly) {
mActivity = activity;
mUserId = userId;
mRecentOnly = recentOnly;
}
@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),
mUserId,
"nearby",
mRecentOnly ? "recent" : "popular",
30);
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Tip> tips) {
if (mActivity != null) {
mActivity.onTaskTipsComplete(tips, mRecentOnly, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskTipsComplete(null, mRecentOnly, mReason);
}
}
public void setActivity(UserDetailsTipsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private String mUserId;
private String mUsername;
private Group<Tip> mTipsRecent;
private Group<Tip> mTipsPopular;
private TaskTips mTaskTipsRecent;
private TaskTips mTaskTipsPopular;
private boolean mIsRunningTaskTipsRecent;
private boolean mIsRunningTaskTipsPopular;
private boolean mRecentOnly;
private boolean mRanOnceTipsRecent;
private boolean mRanOnceTipsPopular;
public StateHolder(String userId, String username) {
mUserId = userId;
mUsername = username;
mIsRunningTaskTipsRecent = false;
mIsRunningTaskTipsPopular = false;
mRanOnceTipsRecent = false;
mRanOnceTipsPopular = false;
mTipsRecent = new Group<Tip>();
mTipsPopular = new Group<Tip>();
mRecentOnly = true;
}
public String getUsername() {
return mUsername;
}
public Group<Tip> getTipsRecent() {
return mTipsRecent;
}
public void setTipsRecent(Group<Tip> tipsRecent) {
mTipsRecent = tipsRecent;
}
public Group<Tip> getTipsPopular() {
return mTipsPopular;
}
public void setTipsPopular(Group<Tip> tipsPopular) {
mTipsPopular = tipsPopular;
}
public void startTaskTips(UserDetailsTipsActivity activity,
boolean recentOnly) {
if (recentOnly) {
if (mIsRunningTaskTipsRecent) {
return;
}
mIsRunningTaskTipsRecent = true;
mTaskTipsRecent = new TaskTips(activity, mUserId, recentOnly);
mTaskTipsRecent.execute();
} else {
if (mIsRunningTaskTipsPopular) {
return;
}
mIsRunningTaskTipsPopular = true;
mTaskTipsPopular = new TaskTips(activity, mUserId, recentOnly);
mTaskTipsPopular.execute();
}
}
public void setActivity(UserDetailsTipsActivity activity) {
if (mTaskTipsRecent != null) {
mTaskTipsRecent.setActivity(activity);
}
if (mTaskTipsPopular != null) {
mTaskTipsPopular.setActivity(activity);
}
}
public boolean getIsRunningTaskTipsRecent() {
return mIsRunningTaskTipsRecent;
}
public void setIsRunningTaskTipsRecent(boolean isRunning) {
mIsRunningTaskTipsRecent = isRunning;
}
public boolean getIsRunningTaskTipsPopular() {
return mIsRunningTaskTipsPopular;
}
public void setIsRunningTaskTipsPopular(boolean isRunning) {
mIsRunningTaskTipsPopular = isRunning;
}
public void cancelTasks() {
if (mTaskTipsRecent != null) {
mTaskTipsRecent.setActivity(null);
mTaskTipsRecent.cancel(true);
}
if (mTaskTipsPopular != null) {
mTaskTipsPopular.setActivity(null);
mTaskTipsPopular.cancel(true);
}
}
public boolean getRecentOnly() {
return mRecentOnly;
}
public void setRecentOnly(boolean recentOnly) {
mRecentOnly = recentOnly;
}
public boolean getRanOnceTipsRecent() {
return mRanOnceTipsRecent;
}
public void setRanOnceTipsRecent(boolean ranOnce) {
mRanOnceTipsRecent = ranOnce;
}
public boolean getRanOnceTipsPopular() {
return mRanOnceTipsPopular;
}
public void setRanOnceTipsPopular(boolean ranOnce) {
mRanOnceTipsPopular = ranOnce;
}
public void updateTip(Tip tip) {
updateTipFromArray(tip, mTipsRecent);
updateTipFromArray(tip, mTipsPopular);
}
private void updateTipFromArray(Tip tip, Group<Tip> target) {
for (Tip it : target) {
if (it.getId().equals(tip.getId())) {
it.setStatus(tip.getStatus());
break;
}
}
}
}
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.foursquared.preferences.Preferences;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
/**
* Can be presented as a dialog theme, collects data from the user for a checkin or a
* shout. The foursquare api is the same for checkins and shouts. A checkin should just
* contain a venue id.
*
* After the user has entered their data, this activity will finish itself and call
* either CheckinExecuteActivity or ShoutExecuteActivity. The only real difference
* between them is what's displayed at the conclusion of the execution.
*
* If doing a checkin, the user can also skip this activity and do a 'quick' checkin
* by launching CheckinExecuteActivity directly. This will just use their saved preferences
* to checkin at the specified venue, no optional shout message will be attached to
* the checkin.
*
* This dialog allows the user to supply the following information:
*
* <ul>
* <li>Tell my Friends [yes|no]</li>
* <li>Tell Twitter [yes|no]</li>
* <li>Tell Facebook [yes|no]</li>
* <li>EditField for freeform shout text.</li>
* </ul>
*
* @date March 2, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class CheckinOrShoutGatherInfoActivity extends Activity {
public static final String TAG = "CheckinOrShoutGatherInfoActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_IS_CHECKIN = Foursquared.PACKAGE_NAME
+ ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_CHECKIN";
public static final String INTENT_EXTRA_IS_SHOUT = Foursquared.PACKAGE_NAME
+ ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_SHOUT";
public static final String INTENT_EXTRA_VENUE_ID = Foursquared.PACKAGE_NAME
+ ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_ID";
public static final String INTENT_EXTRA_VENUE_NAME = Foursquared.PACKAGE_NAME
+ ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_NAME";
public static final String INTENT_EXTRA_TEXT_PREPOPULATE = Foursquared.PACKAGE_NAME
+ ".CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_TEXT_PREPOPULATE";
private StateHolder mStateHolder;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
setContentView(R.layout.checkin_or_shout_gather_info_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
} else {
if (getIntent().getExtras() != null) {
if (getIntent().getBooleanExtra(INTENT_EXTRA_IS_CHECKIN, false)) {
// If a checkin, we require venue id and name.
String venueId = null;
if (getIntent().getExtras().containsKey(INTENT_EXTRA_VENUE_ID)) {
venueId = getIntent().getExtras().getString(INTENT_EXTRA_VENUE_ID);
} else {
Log.e(TAG, "CheckinOrShoutGatherInfoActivity requires intent extra INTENT_EXTRA_VENUE_ID for action type checkin.");
finish();
return;
}
String venueName = null;
if (getIntent().getExtras().containsKey(INTENT_EXTRA_VENUE_NAME)) {
venueName = getIntent().getExtras().getString(INTENT_EXTRA_VENUE_NAME);
} else {
Log.e(TAG, "CheckinOrShoutGatherInfoActivity requires intent extra INTENT_EXTRA_VENUE_NAME for action type checkin.");
finish();
return;
}
mStateHolder = new StateHolder(true, venueId, venueName);
}
else if (getIntent().getBooleanExtra(INTENT_EXTRA_IS_SHOUT, false)) {
// If a shout, we don't require anything at all.
mStateHolder = new StateHolder(false, null, null);
}
else {
Log.e(TAG, "CheckinOrShoutGatherInfoActivity requires intent extra parameter for action type.");
finish();
return;
}
if (getIntent().hasExtra(INTENT_EXTRA_TEXT_PREPOPULATE)) {
EditText editShout = (EditText)findViewById(R.id.editTextShout);
editShout.setText(getIntent().getStringExtra(INTENT_EXTRA_TEXT_PREPOPULATE));
}
}
else {
Log.e(TAG, "CheckinOrShoutGatherInfoActivity requires intent extras parameters, none found.");
finish();
return;
}
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
return mStateHolder;
}
private void ensureUi() {
if (mStateHolder.getIsCheckin()) {
setTitle(getResources().getString(R.string.checkin_title_checking_in,
mStateHolder.getVenueName()));
} else {
setTitle(getResources().getString(R.string.shout_action_label));
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
CheckBox cbTellFriends = (CheckBox)findViewById(R.id.checkboxTellFriends);
cbTellFriends.setChecked(settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, true));
CheckBox cbTellFollowers = (CheckBox)findViewById(R.id.checkboxTellFollowers);
if (settings.getBoolean(Preferences.PREFERENCE_CAN_HAVE_FOLLOWERS, false)) {
cbTellFollowers.setVisibility(View.VISIBLE);
}
CheckBox cbTellTwitter = (CheckBox)findViewById(R.id.checkboxTellTwitter);
if (settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, false) &&
!TextUtils.isEmpty(settings.getString(Preferences.PREFERENCE_TWITTER_HANDLE, ""))) {
cbTellTwitter.setChecked(true);
}
CheckBox cbTellFacebook = (CheckBox)findViewById(R.id.checkboxTellFacebook);
if (settings.getBoolean(Preferences.PREFERENCE_FACEBOOK_CHECKIN, false) &&
!TextUtils.isEmpty(settings.getString(Preferences.PREFERENCE_FACEBOOK_HANDLE, ""))) {
cbTellFacebook.setChecked(true);
}
Button btnCheckin = (Button)findViewById(R.id.btnCheckin);
if (mStateHolder.getIsCheckin()) {
btnCheckin.setText(getResources().getString(R.string.checkin_action_label));
} else {
btnCheckin.setText(getResources().getString(R.string.shout_action_label));
}
btnCheckin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
checkin();
}
});
}
private void checkin() {
CheckBox cbTellFriends = (CheckBox)findViewById(R.id.checkboxTellFriends);
CheckBox cbTellFollowers = (CheckBox)findViewById(R.id.checkboxTellFollowers);
CheckBox cbTellTwitter = (CheckBox)findViewById(R.id.checkboxTellTwitter);
CheckBox cbTellFacebook = (CheckBox)findViewById(R.id.checkboxTellFacebook);
EditText editShout = (EditText)findViewById(R.id.editTextShout);
// After we start the activity, we don't have to stick around any longer.
// We want to forward the resultCode of CheckinExecuteActivity to our
// caller though, so add the FLAG_ACTIVITY_FORWARD_RESULT on the intent.
Intent intent = new Intent();
if (mStateHolder.getIsCheckin()) {
intent.setClass(this, CheckinExecuteActivity.class);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.getVenueId());
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_SHOUT, editShout.getText().toString());
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FRIENDS, cbTellFriends.isChecked());
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FOLLOWERS, cbTellFollowers.isChecked());
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_TWITTER, cbTellTwitter.isChecked());
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK, cbTellFacebook.isChecked());
}
else {
intent.setClass(this, ShoutExecuteActivity.class);
intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_SHOUT, editShout.getText().toString());
intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_TELL_FRIENDS, cbTellFriends.isChecked());
intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_TELL_FOLLOWERS, cbTellFollowers.isChecked());
intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_TELL_TWITTER, cbTellTwitter.isChecked());
intent.putExtra(ShoutExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK, cbTellFacebook.isChecked());
}
intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(intent);
finish();
}
private static class StateHolder {
private boolean mIsCheckin; // either a checkin, or a shout.
private String mVenueId;
private String mVenueName;
public StateHolder(boolean isCheckin, String venueId, String venueName) {
mIsCheckin = isCheckin;
mVenueId = venueId;
mVenueName = venueName;
}
public boolean getIsCheckin() {
return mIsCheckin;
}
public String getVenueId() {
return mVenueId;
}
public String getVenueName() {
return mVenueName;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.app.LoadableListActivity;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.VenueListAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
/**
* Shows a list of venues that the specified user is mayor of.
* We can fetch these ourselves given a userId, or work from
* a venue array parcel.
*
* @date March 15, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserMayorshipsActivity extends LoadableListActivity {
static final String TAG = "UserMayorshipsActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_USER_ID = Foursquared.PACKAGE_NAME
+ ".UserMayorshipsActivity.EXTRA_USER_ID";
public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME
+ ".UserMayorshipsActivity.EXTRA_USER_NAME";
public static final String EXTRA_VENUE_LIST_PARCEL = Foursquared.PACKAGE_NAME
+ ".UserMayorshipsActivity.EXTRA_VENUE_LIST_PARCEL";
private StateHolder mStateHolder;
private SeparatedListAdapter mListAdapter;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivityForTaskVenues(this);
} else {
if (getIntent().hasExtra(EXTRA_USER_ID) && getIntent().hasExtra(EXTRA_USER_NAME)) {
mStateHolder = new StateHolder(
getIntent().getStringExtra(EXTRA_USER_ID),
getIntent().getStringExtra(EXTRA_USER_NAME));
} else {
Log.e(TAG, "UserMayorships requires a userid in its intent extras.");
finish();
return;
}
if (getIntent().getExtras().containsKey(EXTRA_VENUE_LIST_PARCEL)) {
// Can't jump from ArrayList to Group, argh.
ArrayList<Venue> venues = getIntent().getExtras().getParcelableArrayList(
EXTRA_VENUE_LIST_PARCEL);
Group<Venue> group = new Group<Venue>();
for (Venue it : venues) {
group.add(it);
}
mStateHolder.setVenues(group);
} else {
mStateHolder.startTaskVenues(this);
}
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mStateHolder.cancelTasks();
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTaskVenues(null);
return mStateHolder;
}
private void ensureUi() {
mListAdapter = new SeparatedListAdapter(this);
VenueListAdapter adapter = new VenueListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
if (mStateHolder.getVenues().size() > 0) {
adapter.setGroup(mStateHolder.getVenues());
mListAdapter.addSection(
getResources().getString(R.string.user_mayorships_activity_adapter_title),
adapter);
}
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Venue venue = (Venue)mListAdapter.getItem(position);
Intent intent = new Intent(UserMayorshipsActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
startActivity(intent);
}
});
if (mStateHolder.getIsRunningVenuesTask()) {
setLoadingView();
} else if (mStateHolder.getFetchedVenuesOnce() && mStateHolder.getVenues().size() == 0) {
setEmptyView();
}
setTitle(getString(R.string.user_mayorships_activity_title, mStateHolder.getUsername()));
}
private void onVenuesTaskComplete(User user, Exception ex) {
mListAdapter.removeObserver();
mListAdapter = new SeparatedListAdapter(this);
if (user != null) {
mStateHolder.setVenues(user.getMayorships());
}
else {
mStateHolder.setVenues(new Group<Venue>());
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (mStateHolder.getVenues().size() > 0) {
VenueListAdapter adapter = new VenueListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(mStateHolder.getVenues());
mListAdapter.addSection(
getResources().getString(R.string.user_mayorships_activity_adapter_title),
adapter);
}
getListView().setAdapter(mListAdapter);
mStateHolder.setIsRunningVenuesTask(false);
mStateHolder.setFetchedVenuesOnce(true);
// TODO: We can probably tighten this up by just calling ensureUI() again.
if (mStateHolder.getVenues().size() == 0) {
setEmptyView();
}
}
@Override
public int getNoSearchResultsStringId() {
return R.string.user_mayorships_activity_no_info;
}
/**
* Gets venues that the current user is mayor of.
*/
private static class VenuesTask extends AsyncTask<String, Void, User> {
private UserMayorshipsActivity mActivity;
private Exception mReason;
public VenuesTask(UserMayorshipsActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.setLoadingView();
}
@Override
protected User doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.user(params[0], true, false, false,
LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(User user) {
if (mActivity != null) {
mActivity.onVenuesTaskComplete(user, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onVenuesTaskComplete(null, mReason);
}
}
public void setActivity(UserMayorshipsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private String mUserId;
private String mUsername;
private Group<Venue> mVenues;
private VenuesTask mTaskVenues;
private boolean mIsRunningVenuesTask;
private boolean mFetchedVenuesOnce;
public StateHolder(String userId, String username) {
mUserId = userId;
mUsername = username;
mIsRunningVenuesTask = false;
mFetchedVenuesOnce = false;
mVenues = new Group<Venue>();
}
public String getUsername() {
return mUsername;
}
public Group<Venue> getVenues() {
return mVenues;
}
public void setVenues(Group<Venue> venues) {
mVenues = venues;
}
public void startTaskVenues(UserMayorshipsActivity activity) {
mIsRunningVenuesTask = true;
mTaskVenues = new VenuesTask(activity);
mTaskVenues.execute(mUserId);
}
public void setActivityForTaskVenues(UserMayorshipsActivity activity) {
if (mTaskVenues != null) {
mTaskVenues.setActivity(activity);
}
}
public void setIsRunningVenuesTask(boolean isRunning) {
mIsRunningVenuesTask = isRunning;
}
public boolean getIsRunningVenuesTask() {
return mIsRunningVenuesTask;
}
public void setFetchedVenuesOnce(boolean fetchedOnce) {
mFetchedVenuesOnce = fetchedOnce;
}
public boolean getFetchedVenuesOnce() {
return mFetchedVenuesOnce;
}
public void cancelTasks() {
if (mTaskVenues != null) {
mTaskVenues.setActivity(null);
mTaskVenues.cancel(true);
}
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.widget.FriendListAdapter;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
/**
* To be used when a user has some friends in common. We show two lists, by default
* the first list is 'friends in common'. The second list is all friends. This is
* expected to be used with a fully-fetched user object, so the friends in common
* group should already be fetched. The full 'all friends' list is fetched separately
* within this activity.
*
* If the user has no friends in common, then just use UserDetailsFriendsActivity
* directly.
*
* @date September 23, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserDetailsFriendsInCommonActivity extends LoadableListActivityWithViewAndHeader {
static final String TAG = "UserDetailsFriendsInCommonActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME
+ ".UserDetailsFriendsInCommonActivity.EXTRA_USER_PARCEL";
private StateHolder mStateHolder;
private FriendListAdapter mListAdapter;
private ScrollView mLayoutEmpty;
private static final int MENU_REFRESH = 0;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(EXTRA_USER_PARCEL)) {
mStateHolder.setUser((User)getIntent().getParcelableExtra(EXTRA_USER_PARCEL));
if (mStateHolder.getUser().getFriendsInCommon() == null ||
mStateHolder.getUser().getFriendsInCommon().size() == 0) {
Log.e(TAG, TAG + " requires user parcel have friends in common size > 0.");
finish();
return;
}
} else {
Log.e(TAG, TAG + " requires user parcel in intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mStateHolder.cancelTasks();
mListAdapter.removeObserver();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void ensureUi() {
LayoutInflater inflater = LayoutInflater.from(this);
mLayoutEmpty = (ScrollView)inflater.inflate(R.layout.user_details_friends_activity_empty,
null);
mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
mListAdapter = new FriendListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
if (mStateHolder.getFriendsInCommonOnly()) {
mListAdapter.setGroup(mStateHolder.getUser().getFriendsInCommon());
} else {
mListAdapter.setGroup(mStateHolder.getAllFriends());
if (mStateHolder.getAllFriends().size() == 0) {
if (mStateHolder.getRanOnce()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
}
SegmentedButton buttons = getHeaderButton();
buttons.clearButtons();
buttons.addButtons(
getString(R.string.user_details_friends_in_common_common_friends),
getString(R.string.user_details_friends_in_common_all_friends));
if (mStateHolder.getFriendsInCommonOnly()) {
buttons.setPushedButtonIndex(0);
} else {
buttons.setPushedButtonIndex(1);
}
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
if (index == 0) {
mStateHolder.setFriendsInCommonOnly(true);
mListAdapter.setGroup(mStateHolder.getUser().getFriendsInCommon());
} else {
mStateHolder.setFriendsInCommonOnly(false);
mListAdapter.setGroup(mStateHolder.getAllFriends());
if (mStateHolder.getAllFriends().size() < 1) {
if (mStateHolder.getRanOnce()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskAllFriends(UserDetailsFriendsInCommonActivity.this);
}
}
}
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
});
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(false);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
User user = (User) parent.getAdapter().getItem(position);
Intent intent = new Intent(UserDetailsFriendsInCommonActivity.this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user);
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
startActivity(intent);
}
});
if (mStateHolder.getIsRunningTaskAllFriends()) {
setProgressBarIndeterminateVisibility(true);
} else {
setProgressBarIndeterminateVisibility(false);
}
setTitle(getString(R.string.user_details_friends_in_common_title, mStateHolder.getUser().getFirstname()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh)
.setIcon(R.drawable.ic_menu_refresh);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
if (!mStateHolder.getFriendsInCommonOnly()) {
mStateHolder.startTaskAllFriends(this);
}
return true;
}
return super.onOptionsItemSelected(item);
}
private void onStartTaskAllFriends() {
mStateHolder.setIsRunningTaskAllFriends(true);
setProgressBarIndeterminateVisibility(true);
setLoadingView();
}
private void onTaskAllFriendsComplete(Group<User> allFriends, Exception ex) {
setProgressBarIndeterminateVisibility(false);
mStateHolder.setRanOnce(true);
mStateHolder.setIsRunningTaskAllFriends(false);
if (allFriends != null) {
mStateHolder.setAllFriends(allFriends);
} else {
NotificationsUtil.ToastReasonForFailure(this, ex);
}
SegmentedButton buttons = getHeaderButton();
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getAllFriends());
if (mStateHolder.getAllFriends().size() == 0) {
if (mStateHolder.getRanOnce()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
}
}
/**
* Gets friends of the current user we're working for.
*/
private static class TaskAllFriends extends AsyncTask<Void, Void, Group<User>> {
private UserDetailsFriendsInCommonActivity mActivity;
private String mUserId;
private Exception mReason;
public TaskAllFriends(UserDetailsFriendsInCommonActivity activity, String userId) {
mActivity = activity;
mUserId = userId;
}
@Override
protected void onPreExecute() {
mActivity.onStartTaskAllFriends();
}
@Override
protected Group<User> doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.friends(
mUserId, LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<User> allFriends) {
if (mActivity != null) {
mActivity.onTaskAllFriendsComplete(allFriends, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskAllFriendsComplete(null, mReason);
}
}
public void setActivity(UserDetailsFriendsInCommonActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private User mUser;
private Group<User> mAllFriends;
private TaskAllFriends mTaskAllFriends;
private boolean mIsRunningTaskAllFriends;
private boolean mRanOnceTaskAllFriends;
private boolean mFriendsInCommonOnly;
public StateHolder() {
mAllFriends = new Group<User>();
mIsRunningTaskAllFriends = false;
mRanOnceTaskAllFriends = false;
mFriendsInCommonOnly = true;
}
public User getUser() {
return mUser;
}
public void setUser(User user) {
mUser = user;
}
public Group<User> getAllFriends() {
return mAllFriends;
}
public void setAllFriends(Group<User> allFriends) {
mAllFriends = allFriends;
}
public void startTaskAllFriends(UserDetailsFriendsInCommonActivity activity) {
if (!mIsRunningTaskAllFriends) {
mIsRunningTaskAllFriends = true;
mTaskAllFriends = new TaskAllFriends(activity, mUser.getId());
mTaskAllFriends.execute();
}
}
public void setActivity(UserDetailsFriendsInCommonActivity activity) {
if (mTaskAllFriends != null) {
mTaskAllFriends.setActivity(activity);
}
}
public boolean getIsRunningTaskAllFriends() {
return mIsRunningTaskAllFriends;
}
public void setIsRunningTaskAllFriends(boolean isRunning) {
mIsRunningTaskAllFriends = isRunning;
}
public void cancelTasks() {
if (mTaskAllFriends != null) {
mTaskAllFriends.setActivity(null);
mTaskAllFriends.cancel(true);
}
}
public boolean getRanOnce() {
return mRanOnceTaskAllFriends;
}
public void setRanOnce(boolean ranOnce) {
mRanOnceTaskAllFriends = ranOnce;
}
public boolean getFriendsInCommonOnly() {
return mFriendsInCommonOnly;
}
public void setFriendsInCommonOnly(boolean friendsInCommonOnly) {
mFriendsInCommonOnly = friendsInCommonOnly;
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquare.util.VenueUtils;
import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay;
import com.joelapenna.foursquared.maps.VenueItemizedOverlay;
import com.joelapenna.foursquared.util.UiUtil;
import android.os.Bundle;
import android.util.Log;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueMapActivity extends MapActivity {
public static final String TAG = "VenueMapActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".VenueMapActivity.INTENT_EXTRA_VENUE";
private MapView mMapView;
private MapController mMapController;
private VenueItemizedOverlay mOverlay = null;
private MyLocationOverlay mMyLocationOverlay = null;
private StateHolder mStateHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.venue_map_activity);
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE));
} else {
Log.e(TAG, "VenueMapActivity requires a venue parcel its intent extras.");
finish();
return;
}
}
ensureUi();
}
private void ensureUi() {
/*
Button mapsButton = (Button) findViewById(R.id.mapsButton);
mapsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse( //
"geo:0,0?q=" + mStateHolder.getVenue().getName() + " near " +
mStateHolder.getVenue().getCity()));
startActivity(intent);
}
});
if (FoursquaredSettings.SHOW_VENUE_MAP_BUTTON_MORE == false) {
mapsButton.setVisibility(View.GONE);
}
*/
setTitle(getString(R.string.venue_map_activity_title, mStateHolder.getVenue().getName()));
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mMyLocationOverlay);
mOverlay = new VenueItemizedOverlay(this.getResources().getDrawable(
R.drawable.map_marker_blue));
if (VenueUtils.hasValidLocation(mStateHolder.getVenue())) {
Group<Venue> venueGroup = new Group<Venue>();
venueGroup.setType("Current Venue");
venueGroup.add(mStateHolder.getVenue());
mOverlay.setGroup(venueGroup);
mMapView.getOverlays().add(mOverlay);
}
updateMap();
}
@Override
public void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
if (UiUtil.sdkVersion() > 3) {
mMyLocationOverlay.enableCompass();
}
}
@Override
public void onPause() {
super.onPause();
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
private void updateMap() {
if (mOverlay != null && mOverlay.size() > 0) {
GeoPoint center = mOverlay.getCenter();
mMapController.animateTo(center);
mMapController.setZoom(17);
}
}
private static class StateHolder {
private Venue mVenue;
public StateHolder() {
}
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import 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 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Settings;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.app.PingsService;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.NotificationsUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* @date June 2, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class PingsSettingsActivity extends Activity {
private static final String TAG = "PingsSettingsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private SharedPreferences mPrefs;
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
private CheckBox mCheckBoxPings;
private Spinner mSpinnerInterval;
private CheckBox mCheckBoxVibrate;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pings_settings_activity);
setTitle(getResources().getString(R.string.pings_settings_title));
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
ensureUi();
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
if (mStateHolder.getIsRunningTaskNotifications()) {
startProgressBar(
getResources().getString(
R.string.pings_settings_progressbar_title_pings),
getResources().getString(
R.string.pings_settings_progressbar_message_pings));
}
} else {
// Get a fresh copy of the user object in an attempt to keep the notification
// setting in sync.
mStateHolder = new StateHolder(this);
mStateHolder.startTaskUpdateUser(this);
}
}
private void ensureUi() {
mCheckBoxPings = (CheckBox)findViewById(R.id.pings_on);
mCheckBoxPings.setChecked(mPrefs.getBoolean(Preferences.PREFERENCE_PINGS, false));
mCheckBoxPings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mStateHolder.startTaskNotifications(
PingsSettingsActivity.this, mCheckBoxPings.isChecked());
}
});
mSpinnerInterval = (Spinner)findViewById(R.id.pings_interval);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.pings_refresh_interval_in_minutes,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerInterval.setAdapter(adapter);
mSpinnerInterval.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) {
String[] values = PingsSettingsActivity.this.getResources().getStringArray(
R.array.pings_refresh_interval_in_minutes_values);
mPrefs.edit().putString(
Preferences.PREFERENCE_PINGS_INTERVAL, values[position]).commit();
restartNotifications();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
setIntervalSpinnerFromSettings();
mCheckBoxVibrate = (CheckBox)findViewById(R.id.pings_vibrate);
mCheckBoxVibrate.setChecked(mPrefs.getBoolean(Preferences.PREFERENCE_PINGS_VIBRATE, false));
mCheckBoxVibrate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mPrefs.edit().putBoolean(
Preferences.PREFERENCE_PINGS_VIBRATE, mCheckBoxVibrate.isChecked()).commit();
}
});
}
private void setIntervalSpinnerFromSettings() {
String selected = mPrefs.getString(Preferences.PREFERENCE_PINGS_INTERVAL, "30");
String[] values = getResources().getStringArray(
R.array.pings_refresh_interval_in_minutes_values);
for (int i = 0; i < values.length; i++) {
if (values[i].equals(selected)) {
mSpinnerInterval.setSelection(i);
return;
}
}
mSpinnerInterval.setSelection(1);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public void onResume() {
super.onResume();
if (mStateHolder.getIsRunningTaskNotifications()) {
startProgressBar(
getResources().getString(
R.string.pings_settings_progressbar_title_pings),
getResources().getString(
R.string.pings_settings_progressbar_message_pings));
} else if (mStateHolder.getIsRunningTaskUpdateUser()) {
startProgressBar(
getResources().getString(
R.string.pings_settings_progressbar_title_updateuser),
getResources().getString(
R.string.pings_settings_progressbar_message_updateuser));
}
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
stopProgressBar();
mStateHolder.cancelTasks();
}
}
private void startProgressBar(String title, String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, title, message);
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
private void onPostTaskPings(Settings settings, boolean changeToState, Exception reason) {
if (settings == null) {
NotificationsUtil.ToastReasonForFailure(this, reason);
// Reset the checkbox.
mCheckBoxPings.setChecked(!changeToState);
} else {
Toast.makeText(
this,
getResources().getString(R.string.pings_settings_result, settings.getPings()),
Toast.LENGTH_SHORT).show();
if (settings.getPings().equals("on")) {
PingsService.setupPings(this);
mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, true).commit();
} else {
PingsService.cancelPings(this);
mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit();
}
restartNotifications();
}
mStateHolder.setIsRunningTaskNotifications(false);
stopProgressBar();
}
private void onPostTaskUserUpdate(User user, Exception reason) {
if (user == null) {
NotificationsUtil.ToastReasonForFailure(this, reason);
finish();
} else {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(
PingsSettingsActivity.this);
Editor editor = prefs.edit();
Preferences.storeUser(editor, user);
if (!editor.commit()) {
Log.e(TAG, "Error storing user object.");
}
if (user.getSettings().getPings().equals("on")) {
mCheckBoxPings.setChecked(true);
mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, true).commit();
} else {
mCheckBoxPings.setChecked(false);
mPrefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit();
}
restartNotifications();
}
mStateHolder.setIsRunningTaskUpdateUser(false);
stopProgressBar();
}
private static class UpdatePingsTask extends AsyncTask<Void, Void, Settings> {
private static final String TAG = "UpdatePingsTask";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Exception mReason;
private boolean mPingsOn;
private PingsSettingsActivity mActivity;
public UpdatePingsTask(PingsSettingsActivity activity, boolean on) {
mActivity = activity;
mPingsOn = on;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar(
mActivity.getResources().getString(
R.string.pings_settings_progressbar_title_pings),
mActivity.getResources().getString(
R.string.pings_settings_progressbar_message_pings));
}
@Override
protected Settings doInBackground(Void... params) {
if (DEBUG) Log.d(TAG, "doInBackground()");
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.setpings(mPingsOn);
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Settings settings) {
if (mActivity != null) {
mActivity.onPostTaskPings(settings, mPingsOn, mReason);
}
}
public void setActivity(PingsSettingsActivity activity) {
mActivity = activity;
}
}
private static class UpdateUserTask extends AsyncTask<Void, Void, User> {
private PingsSettingsActivity mActivity;
private Exception mReason;
public UpdateUserTask(PingsSettingsActivity activity) {
mActivity = activity;
}
@Override
protected User doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
Location location = foursquared.getLastKnownLocation();
return foursquare.user(
null, false, false, false, LocationUtils
.createFoursquareLocation(location));
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(User user) {
if (mActivity != null) {
mActivity.onPostTaskUserUpdate(user, mReason);
}
}
public void setActivity(PingsSettingsActivity activity) {
mActivity = activity;
}
}
private void restartNotifications() {
PingsService.cancelPings(this);
PingsService.setupPings(this);
}
private static class StateHolder {
private UpdatePingsTask mTaskNotifications;
private UpdateUserTask mTaskUpdateUser;
private boolean mIsRunningTaskNotifications;
private boolean mIsRunningTaskUpdateUser;
public StateHolder(Context context) {
mTaskNotifications = null;
mTaskUpdateUser = null;
mIsRunningTaskNotifications = false;
mIsRunningTaskUpdateUser = false;
}
public void startTaskNotifications(PingsSettingsActivity activity, boolean on) {
mIsRunningTaskNotifications = true;
mTaskNotifications = new UpdatePingsTask(activity, on);
mTaskNotifications.execute();
}
public void startTaskUpdateUser(PingsSettingsActivity activity) {
mIsRunningTaskUpdateUser = true;
mTaskUpdateUser = new UpdateUserTask(activity);
mTaskUpdateUser.execute();
}
public void setActivity(PingsSettingsActivity activity) {
if (mTaskNotifications != null) {
mTaskNotifications.setActivity(activity);
}
if (mTaskUpdateUser != null) {
mTaskUpdateUser.setActivity(activity);
}
}
public boolean getIsRunningTaskNotifications() {
return mIsRunningTaskNotifications;
}
public boolean getIsRunningTaskUpdateUser() {
return mIsRunningTaskUpdateUser;
}
public void setIsRunningTaskNotifications(boolean isRunningTaskNotifications) {
mIsRunningTaskNotifications = isRunningTaskNotifications;
}
public void setIsRunningTaskUpdateUser(boolean isRunningTaskUpdateUser) {
mIsRunningTaskUpdateUser = isRunningTaskUpdateUser;
}
public void cancelTasks() {
if (mTaskNotifications != null && mIsRunningTaskNotifications) {
mTaskNotifications.setActivity(null);
mTaskNotifications.cancel(true);
}
if (mTaskUpdateUser != null && mIsRunningTaskUpdateUser) {
mTaskUpdateUser.setActivity(null);
mTaskUpdateUser.cancel(true);
}
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.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 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.maps;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.graphics.drawable.Drawable;
import android.util.Log;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
abstract class BaseGroupItemizedOverlay<T extends FoursquareType> extends ItemizedOverlay<OverlayItem> {
public static final String TAG = "BaseGroupItemizedOverlay";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
Group<T> group = null;
public BaseGroupItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
@Override
public int size() {
if (group == null) {
return 0;
}
return group.size();
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (DEBUG) Log.d(TAG, "onTap: " + group.getType() + " " + p);
return super.onTap(p, mapView);
}
@Override
protected boolean onTap(int i) {
if (DEBUG) Log.d(TAG, "onTap: " + group.getType() + " " + i);
return super.onTap(i);
}
public void setGroup(Group<T> g) {
assert g.getType() != null;
group = g;
super.populate();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.maps;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.graphics.drawable.Drawable;
import android.util.Log;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class CheckinItemizedOverlay extends BaseGroupItemizedOverlay<Checkin> {
public static final String TAG = "CheckinItemizedOverlay";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public CheckinItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
}
@Override
protected OverlayItem createItem(int i) {
Checkin checkin = (Checkin)group.get(i);
if (DEBUG) Log.d(TAG, "creating checkin overlayItem: " + checkin.getVenue().getName());
int lat = (int)(Double.parseDouble(checkin.getVenue().getGeolat()) * 1E6);
int lng = (int)(Double.parseDouble(checkin.getVenue().getGeolong()) * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
return new CheckinOverlayItem(point, checkin);
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (DEBUG) Log.d(TAG, "onTap: " + p);
return super.onTap(p, mapView);
}
public static class CheckinOverlayItem extends OverlayItem {
private Checkin mCheckin;
public CheckinOverlayItem(GeoPoint point, Checkin checkin) {
super(point, checkin.getVenue().getName(), checkin.getVenue().getAddress());
mCheckin = checkin;
}
public Checkin getCheckin() {
return mCheckin;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.maps;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.GeoUtils;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import java.io.IOException;
/**
* @date June 30, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class VenueItemizedOverlayWithIcons extends BaseGroupItemizedOverlay<Venue> {
public static final String TAG = "VenueItemizedOverlay2";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Context mContext;
private RemoteResourceManager mRrm;
private OverlayItem mLastSelected;
private VenueItemizedOverlayTapListener mTapListener;
public VenueItemizedOverlayWithIcons(Context context, RemoteResourceManager rrm,
Drawable defaultMarker, VenueItemizedOverlayTapListener tapListener) {
super(defaultMarker);
mContext = context;
mRrm = rrm;
mTapListener = tapListener;
mLastSelected = null;
}
@Override
protected OverlayItem createItem(int i) {
Venue venue = (Venue)group.get(i);
GeoPoint point = GeoUtils.stringLocationToGeoPoint(
venue.getGeolat(), venue.getGeolong());
return new VenueOverlayItem(point, venue, mContext, mRrm);
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (mTapListener != null) {
mTapListener.onTap(p, mapView);
}
return super.onTap(p, mapView);
}
@Override
public boolean onTap(int i) {
if (mTapListener != null) {
mTapListener.onTap(getItem(i), mLastSelected, group.get(i));
}
mLastSelected = getItem(i);
return true;
}
@Override
public void draw(android.graphics.Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, false);
}
public static class VenueOverlayItem extends OverlayItem {
private Venue mVenue;
public VenueOverlayItem(GeoPoint point, Venue venue, Context context,
RemoteResourceManager rrm) {
super(point, venue.getName(), venue.getAddress());
mVenue = venue;
constructPinDrawable(venue, context, rrm);
}
public Venue getVenue() {
return mVenue;
}
private static int dddi(int dd, float screenDensity) {
return (int)(dd * screenDensity + 0.5f);
}
private void constructPinDrawable(Venue venue, Context context, RemoteResourceManager rrm) {
float screenDensity = context.getResources().getDisplayMetrics().density;
int cx = dddi(32, screenDensity);
int cy = dddi(32, screenDensity);
Bitmap bmp = Bitmap.createBitmap(cx, cy, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
boolean laodedPin = false;
if (venue.getCategory() != null) {
Uri photoUri = Uri.parse(venue.getCategory().getIconUrl());
try {
Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(photoUri));
canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()),
new Rect(0, 0, cx, cy), paint);
laodedPin = true;
} catch (IOException e) {
}
}
if (!laodedPin) {
Drawable drw = context.getResources().getDrawable(R.drawable.category_none);
drw.draw(canvas);
}
Drawable bd = new BitmapDrawable(bmp);
bd.setBounds(-cx / 2, -cy, cx / 2, 0);
setMarker(bd);
}
}
public interface VenueItemizedOverlayTapListener
{
public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, Venue venue);
public void onTap(GeoPoint p, MapView mapView);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.maps;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.graphics.drawable.Drawable;
import android.util.Log;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class TipItemizedOverlay extends BaseGroupItemizedOverlay<Tip> {
public static final String TAG = "TipItemizedOverlay";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public TipItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
}
@Override
protected OverlayItem createItem(int i) {
Tip tip = (Tip)group.get(i);
if (DEBUG) Log.d(TAG, "creating tip overlayItem: " + tip.getVenue().getName());
int lat = (int)(Double.parseDouble(tip.getVenue().getGeolat()) * 1E6);
int lng = (int)(Double.parseDouble(tip.getVenue().getGeolong()) * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
return new TipOverlayItem(point, tip);
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (DEBUG) Log.d(TAG, "onTap: " + p);
mapView.getController().animateTo(p);
return super.onTap(p, mapView);
}
public static class TipOverlayItem extends OverlayItem {
private Tip mTip;
public TipOverlayItem(GeoPoint point, Tip tip) {
super(point, tip.getVenue().getName(), tip.getVenue().getAddress());
mTip = tip;
}
public Tip getTip() {
return mTip;
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.maps;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.util.DumpcatcherHelper;
import android.content.Context;
import android.graphics.Canvas;
import android.util.Log;
/**
* See: <a href="http://groups.google.com/group/android-developers/browse_thread/thread/43615742f462bbf1/8918ddfc92808c42?"
* >MyLocationOverlay causing crash in 1.6 (Donut)</a>
*
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class CrashFixMyLocationOverlay extends MyLocationOverlay {
static final String TAG = "CrashFixMyLocationOverlay";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public CrashFixMyLocationOverlay(Context context, MapView mapView) {
super(context, mapView);
}
@Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
try {
return super.draw(canvas, mapView, shadow, when);
} catch (ClassCastException e) {
if (DEBUG) Log.d(TAG, "Encountered overlay crash bug", e);
DumpcatcherHelper.sendException(e);
return false;
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.maps;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquare.util.VenueUtils;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.graphics.drawable.Drawable;
import android.util.Log;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueItemizedOverlay extends BaseGroupItemizedOverlay<Venue> {
public static final String TAG = "VenueItemizedOverlay";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private boolean mPopulatedSpans = false;
private SpanHolder mSpanHolder = new SpanHolder();
public VenueItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
}
@Override
protected OverlayItem createItem(int i) {
Venue venue = (Venue)group.get(i);
if (DEBUG) Log.d(TAG, "creating venue overlayItem: " + venue.getName());
int lat = (int)(Double.parseDouble(venue.getGeolat()) * 1E6);
int lng = (int)(Double.parseDouble(venue.getGeolong()) * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
return new VenueOverlayItem(point, venue);
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (DEBUG) Log.d(TAG, "onTap: " + p);
mapView.getController().animateTo(p);
return super.onTap(p, mapView);
}
@Override
public int getLatSpanE6() {
if (!mPopulatedSpans) {
populateSpans();
}
return mSpanHolder.latSpanE6;
}
@Override
public int getLonSpanE6() {
if (!mPopulatedSpans) {
populateSpans();
}
return mSpanHolder.lonSpanE6;
}
private void populateSpans() {
int maxLat = 0;
int minLat = 0;
int maxLon = 0;
int minLon = 0;
for (int i = 0; i < group.size(); i++) {
Venue venue = (Venue)group.get(i);
if (VenueUtils.hasValidLocation(venue)) {
int lat = (int)(Double.parseDouble(venue.getGeolat()) * 1E6);
int lon = (int)(Double.parseDouble(venue.getGeolong()) * 1E6);
// LatSpan
if (lat > maxLat || maxLat == 0) {
maxLat = lat;
}
if (lat < minLat || minLat == 0) {
minLat = lat;
}
// LonSpan
if (lon < minLon || minLon == 0) {
minLon = lon;
}
if (lon > maxLon || maxLon == 0) {
maxLon = lon;
}
}
}
mSpanHolder.latSpanE6 = maxLat - minLat;
mSpanHolder.lonSpanE6 = maxLon - minLon;
}
public static class VenueOverlayItem extends OverlayItem {
private Venue mVenue;
public VenueOverlayItem(GeoPoint point, Venue venue) {
super(point, venue.getName(), venue.getAddress());
mVenue = venue;
}
public Venue getVenue() {
return mVenue;
}
}
public static final class SpanHolder {
int latSpanE6 = 0;
int lonSpanE6 = 0;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.maps;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.R;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import java.io.IOException;
/**
* @date June 18, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class CheckinGroupItemizedOverlay extends BaseGroupItemizedOverlay<CheckinGroup> {
public static final String TAG = "CheckinItemizedGroupOverlay";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Context mContext;
private RemoteResourceManager mRrm;
private Bitmap mBmpPinSingle;
private Bitmap mBmpPinMultiple;
private OverlayItem mLastSelected;
private CheckinGroupOverlayTapListener mTapListener;
public CheckinGroupItemizedOverlay(Context context, RemoteResourceManager rrm,
Drawable defaultMarker, CheckinGroupOverlayTapListener tapListener) {
super(defaultMarker);
mContext = context;
mRrm = rrm;
mTapListener = tapListener;
mLastSelected = null;
constructScaledPinBackgrounds(context);
}
@Override
protected OverlayItem createItem(int i) {
CheckinGroup cg = (CheckinGroup)group.get(i);
GeoPoint point = new GeoPoint(cg.getLatE6(), cg.getLonE6());
return new CheckinGroupOverlayItem(point, cg, mContext, mRrm, mBmpPinSingle, mBmpPinMultiple);
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (mTapListener != null) {
mTapListener.onTap(p, mapView);
}
return super.onTap(p, mapView);
}
@Override
public boolean onTap(int i) {
if (mTapListener != null) {
mTapListener.onTap(getItem(i), mLastSelected, group.get(i));
}
mLastSelected = getItem(i);
return true;
}
@Override
public void draw(android.graphics.Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, false);
}
private void constructScaledPinBackgrounds(Context context) {
Drawable drwSingle = context.getResources().getDrawable(R.drawable.pin_checkin_single);
Drawable drwMultiple = context.getResources().getDrawable(R.drawable.pin_checkin_multiple);
drwSingle.setBounds(0, 0, drwSingle.getIntrinsicWidth(), drwSingle.getIntrinsicHeight());
drwMultiple.setBounds(0, 0, drwMultiple.getIntrinsicWidth(), drwMultiple.getIntrinsicHeight());
mBmpPinSingle = drawableToBitmap(drwSingle);
mBmpPinMultiple = drawableToBitmap(drwMultiple);
}
private Bitmap drawableToBitmap(Drawable drw) {
Bitmap bmp = Bitmap.createBitmap(
drw.getIntrinsicWidth(), drw.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
drw.draw(canvas);
return bmp;
}
private static int dddi(int dd, float screenDensity) {
return (int)(dd * screenDensity + 0.5f);
}
public static class CheckinGroupOverlayItem extends OverlayItem {
private CheckinGroup mCheckinGroup;
public CheckinGroupOverlayItem(GeoPoint point, CheckinGroup cg, Context context,
RemoteResourceManager rrm, Bitmap bmpPinSingle, Bitmap bmpPinMultiple) {
super(point, cg.getVenue().getName(), cg.getVenue().getAddress());
mCheckinGroup = cg;
constructPinDrawable(cg, context, rrm, bmpPinSingle, bmpPinMultiple);
}
public CheckinGroup getCheckin() {
return mCheckinGroup;
}
private void constructPinDrawable(CheckinGroup cg, Context context, RemoteResourceManager rrm,
Bitmap bmpPinSingle, Bitmap bmpPinMultiple) {
// The mdpi size of the photo background is 52 x 58.
// The user's photo should begin at origin (9, 12).
// The user's photo should be 34 x 34.
float screenDensity = context.getResources().getDisplayMetrics().density;
int cx = dddi(52, screenDensity);
int cy = dddi(58, screenDensity);
int pox = dddi(9, screenDensity);
int poy = dddi(12, screenDensity);
int pcx = cx - (pox * 2);
int pcy = cy - (poy * 2);
Bitmap bmp = Bitmap.createBitmap(cx, cy, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
// Draw the correct background pin image.
if (cg.getCheckinCount() < 2) {
canvas.drawBitmap(bmpPinSingle,
new Rect(0, 0, bmpPinSingle.getWidth(), bmpPinSingle.getHeight()),
new Rect(0, 0, cx, cy), paint);
} else {
canvas.drawBitmap(bmpPinMultiple,
new Rect(0, 0, bmpPinMultiple.getWidth(), bmpPinMultiple.getHeight()),
new Rect(0, 0, cx, cy), paint);
}
// Put the user's photo on top.
Uri photoUri = Uri.parse(cg.getPhotoUrl());
try {
Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(photoUri));
canvas.drawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()),
new Rect(pox, poy, pox + pcx, poy + pcy), paint);
} catch (IOException e) {
// If the user's photo isn't already in the cache, don't try loading it,
// use a default user pin.
Drawable drw2 = null;
if (Foursquare.MALE.equals(cg.getGender())) {
drw2 = context.getResources().getDrawable(R.drawable.blank_boy);
} else {
drw2 = context.getResources().getDrawable(R.drawable.blank_girl);
}
drw2.draw(canvas);
}
Drawable bd = new BitmapDrawable(bmp);
bd.setBounds(-cx / 2, -cy, cx / 2, 0);
setMarker(bd);
}
}
public interface CheckinGroupOverlayTapListener
{
public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, CheckinGroup cg);
public void onTap(GeoPoint p, MapView mapView);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.maps;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.util.StringFormatters;
/**
*
* @date June 18, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class CheckinGroup implements FoursquareType {
private Venue mVenue;
private String mDescription;
private String mPhotoUrl;
private String mGender;
private int mCheckinCount;
private int mLatE6;
private int mLonE6;
public CheckinGroup() {
mVenue = null;
mDescription = "";
mPhotoUrl = "";
mCheckinCount = 0;
mGender = Foursquare.MALE;
}
public void appendCheckin(Checkin checkin) {
User user = checkin.getUser();
if (mCheckinCount == 0) {
mPhotoUrl = user.getPhoto();
mGender = user.getGender();
mDescription += StringFormatters.getUserAbbreviatedName(user);
Venue venue = checkin.getVenue();
mVenue = venue;
mLatE6 = (int)(Double.parseDouble(venue.getGeolat()) * 1E6);
mLonE6 = (int)(Double.parseDouble(venue.getGeolong()) * 1E6);
} else {
mDescription += ", " + StringFormatters.getUserAbbreviatedName(user);
}
mCheckinCount++;
}
public Venue getVenue() {
return mVenue;
}
public int getLatE6() {
return mLatE6;
}
public int getLonE6() {
return mLonE6;
}
public String getDescription() {
return mDescription;
}
public String getPhotoUrl() {
return mPhotoUrl;
}
public String getGender() {
return mGender;
}
public int getCheckinCount() {
return mCheckinCount;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.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 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 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 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.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 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 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.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.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 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.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.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 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 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 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.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 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.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 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 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 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 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.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.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 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.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 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 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Badge;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Mayor;
import com.joelapenna.foursquare.types.Score;
import com.joelapenna.foursquare.types.Special;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.util.Base64Coder;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.widget.BadgeWithIconListAdapter;
import com.joelapenna.foursquared.widget.ScoreListAdapter;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.SpecialListAdapter;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* 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 CheckinResultDialog extends Dialog
{
private static final String TAG = "CheckinResultDialog";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private CheckinResult mCheckinResult;
private Handler mHandler;
private RemoteResourceManagerObserver mObserverMayorPhoto;
private Foursquared mApplication;
private String mExtrasDecoded;
private WebViewDialog mDlgWebViewExtras;
public CheckinResultDialog(Context context, CheckinResult result, Foursquared application) {
super(context, R.style.ThemeCustomDlgBase_ThemeCustomDlg);
mCheckinResult = result;
mApplication = application;
mHandler = new Handler();
mObserverMayorPhoto = null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkin_result_dialog);
setTitle(getContext().getResources().getString(R.string.checkin_title_result));
TextView tvMessage = (TextView)findViewById(R.id.textViewCheckinMessage);
if (mCheckinResult != null) {
tvMessage.setText(mCheckinResult.getMessage());
SeparatedListAdapter adapter = new SeparatedListAdapter(getContext());
// Add any badges the user unlocked as a result of this checkin.
addBadges(mCheckinResult.getBadges(), adapter, mApplication.getRemoteResourceManager());
// Add whatever points they got as a result of this checkin.
addScores(mCheckinResult.getScoring(), adapter, mApplication.getRemoteResourceManager());
// Add any specials that are nearby.
addSpecials(mCheckinResult.getSpecials(), adapter);
// Add a button below the mayor section which will launch a new webview if
// we have additional content from the server. This is base64 encoded and
// is supposed to be just dumped into a webview.
addExtras(mCheckinResult.getMarkup());
// List items construction complete.
ListView listview = (ListView)findViewById(R.id.listViewCheckinBadgesAndScores);
listview.setAdapter(adapter);
listview.setOnItemClickListener(mOnItemClickListener);
// Show mayor info if any.
addMayor(mCheckinResult.getMayor(), mApplication.getRemoteResourceManager());
} else {
// This shouldn't be possible but we've gotten a few crash reports showing that
// mCheckinResult is null on entry of this method.
Log.e(TAG, "Checkin result object was null on dialog creation.");
tvMessage.setText("Checked-in!");
}
}
@Override
protected void onStop() {
super.onStop();
if (mDlgWebViewExtras != null && mDlgWebViewExtras.isShowing()) {
mDlgWebViewExtras.dismiss();
}
if (mObserverMayorPhoto != null) {
mApplication.getRemoteResourceManager().deleteObserver(mObserverMayorPhoto);
}
}
private void addBadges(Group<Badge> badges, SeparatedListAdapter adapterMain, RemoteResourceManager rrm) {
if (badges == null || badges.size() < 1) {
return;
}
BadgeWithIconListAdapter adapter = new BadgeWithIconListAdapter(
getContext(), rrm, R.layout.badge_list_item);
adapter.setGroup(badges);
adapterMain.addSection(getContext().getResources().getString(R.string.checkin_result_dialog_badges),
adapter);
}
private void addScores(Group<Score> scores,
SeparatedListAdapter adapterMain,
RemoteResourceManager rrm) {
if (scores == null || scores.size() < 1) {
return;
}
// We make our own local score group because we'll inject the total as
// a new dummy score element.
Group<Score> scoresWithTotal = new Group<Score>();
// Total up the scoring.
int total = 0;
for (Score score : scores) {
total += Integer.parseInt(score.getPoints());
scoresWithTotal.add(score);
}
// Add a dummy score element to the group which is just the total.
Score scoreTotal = new Score();
scoreTotal.setIcon("");
scoreTotal.setMessage(getContext().getResources().getString(
R.string.checkin_result_dialog_score_total));
scoreTotal.setPoints(String.valueOf(total));
scoresWithTotal.add(scoreTotal);
// Give it all to the adapter now.
ScoreListAdapter adapter = new ScoreListAdapter(getContext(), rrm);
adapter.setGroup(scoresWithTotal);
adapterMain.addSection(getContext().getResources().getString(R.string.checkin_score), adapter);
}
private void addMayor(Mayor mayor, RemoteResourceManager rrm) {
LinearLayout llMayor = (LinearLayout)findViewById(R.id.llCheckinMayorInfo);
if (mayor == null) {
llMayor.setVisibility(View.GONE);
return;
} else {
llMayor.setVisibility(View.VISIBLE);
}
// Set the mayor message.
TextView tvMayorMessage = (TextView)findViewById(R.id.textViewCheckinMayorMessage);
tvMayorMessage.setText(mayor.getMessage());
// A few cases here for the image to display.
ImageView ivMayor = (ImageView)findViewById(R.id.imageViewCheckinMayor);
if (mCheckinResult.getMayor().getUser() == null) {
// I am still the mayor.
// Just show the crown icon.
ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown));
}
else if (mCheckinResult.getMayor().getType().equals("nochange")) {
// Someone else is mayor.
// Show that user's photo from the network. If not already on disk,
// we need to start a fetch for it.
Uri photoUri = populateMayorImageFromNetwork();
if (photoUri != null) {
mApplication.getRemoteResourceManager().request(photoUri);
mObserverMayorPhoto = new RemoteResourceManagerObserver();
rrm.addObserver(mObserverMayorPhoto);
}
addClickHandlerForMayorImage(ivMayor, mayor.getUser().getId());
}
else if (mCheckinResult.getMayor().getType().equals("new")) {
// I just became the new mayor as a result of this checkin.
// Just show the crown icon.
ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown));
}
else if (mCheckinResult.getMayor().getType().equals("stolen")) {
// I stole mayorship from someone else as a result of this checkin.
// Just show the crown icon.
ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown));
}
}
private void addSpecials(Group<Special> specials,
SeparatedListAdapter adapterMain) {
if (specials == null || specials.size() < 1) {
return;
}
// For now, get rid of specials not tied to the current venue. If the special is
// tied to this venue, then there would be no <venue> block associated with the
// special. If there is a <venue> block associated with the special, it means it
// belongs to another venue and we won't show it.
Group<Special> localSpecials = new Group<Special>();
for (Special it : specials) {
if (it.getVenue() == null) {
localSpecials.add(it);
}
}
if (localSpecials.size() < 1) {
return;
}
SpecialListAdapter adapter = new SpecialListAdapter(getContext());
adapter.setGroup(localSpecials);
adapterMain.addSection(
getContext().getResources().getString(R.string.checkin_specials), adapter);
}
private void addExtras(String extras) {
LinearLayout llExtras = (LinearLayout)findViewById(R.id.llCheckinExtras);
if (TextUtils.isEmpty(extras)) {
llExtras.setVisibility(View.GONE);
return;
} else {
llExtras.setVisibility(View.VISIBLE);
}
// The server sent us additional content, it is base64 encoded, so decode it now.
mExtrasDecoded = Base64Coder.decodeString(extras);
// TODO: Replace with generic extras method.
// Now when the user clicks this 'button' pop up yet another dialog dedicated
// to showing just the webview and the decoded content. This is not ideal but
// having problems putting a webview directly inline with the rest of the
// checkin content, we can improve this later.
llExtras.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDlgWebViewExtras = new WebViewDialog(getContext(), "SXSW Stats", mExtrasDecoded);
mDlgWebViewExtras.show();
}
});
}
private void addClickHandlerForMayorImage(View view, final String userId) {
// Show a user detail activity when the user clicks on the mayor's image.
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, userId);
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
v.getContext().startActivity(intent);
}
});
}
/**
* If we have to download the user's photo from the net (wasn't already in cache)
* will return the uri to launch.
*/
private Uri populateMayorImageFromNetwork() {
User user = mCheckinResult.getMayor().getUser();
ImageView ivMayor = (ImageView)findViewById(R.id.imageViewCheckinMayor);
if (user != null) {
Uri photoUri = Uri.parse(user.getPhoto());
try {
Bitmap bitmap = BitmapFactory.decodeStream(
mApplication.getRemoteResourceManager().getInputStream(photoUri));
ivMayor.setImageBitmap(bitmap);
return null;
} catch (IOException e) {
// User's image wasn't already in the cache, have to start a request for it.
if (Foursquare.MALE.equals(user.getGender())) {
ivMayor.setImageResource(R.drawable.blank_boy);
} else {
ivMayor.setImageResource(R.drawable.blank_girl);
}
return photoUri;
}
}
return null;
}
/**
* Called if the remote resource manager downloads the mayor's photo.
* If the photo is already on disk, this observer will never be used.
*/
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() {
populateMayorImageFromNetwork();
}
});
}
}
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Object obj = adapter.getItemAtPosition(position);
if (obj != null) {
if (obj instanceof Special) {
// When the user clicks on a special, if the venue is different than
// the venue the user checked in at (already being viewed) then show
// a new venue activity for that special.
Venue venue = ((Special)obj).getVenue();
if (venue != null) {
Intent intent = new Intent(getContext(), VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
getContext().startActivity(intent);
}
}
}
}
};
}
| 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.types.Category;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.widget.CategoryPickerAdapter;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
/**
* Presents the user with a list of all available categories from foursquare
* that they can use to label a new venue.
*
* @date March 7, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class CategoryPickerDialog extends Dialog {
private static final String TAG = "FriendRequestsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Foursquared mApplication;
private Group<Category> mCategories;
private ViewFlipper mViewFlipper;
private Category mChosenCategory;
private int mFirstDialogHeight;
public CategoryPickerDialog(Context context, Group<Category> categories, Foursquared application) {
super(context);
mApplication = application;
mCategories = categories;
mChosenCategory = null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_picker_dialog);
setTitle(getContext().getResources().getString(R.string.category_picket_dialog_title));
mViewFlipper = (ViewFlipper) findViewById(R.id.categoryPickerViewFlipper);
mFirstDialogHeight = -1;
// By default we always have a top-level page.
Category root = new Category();
root.setNodeName("root");
root.setChildCategories(mCategories);
mViewFlipper.addView(makePage(root));
}
private View makePage(Category category) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.category_picker_page, null);
CategoryPickerPage page = new CategoryPickerPage();
page.ensureUI(view, mPageListItemSelected, category, mApplication
.getRemoteResourceManager());
view.setTag(page);
if (mViewFlipper.getChildCount() == 1 && mFirstDialogHeight == -1) {
mFirstDialogHeight = mViewFlipper.getChildAt(0).getHeight();
}
if (mViewFlipper.getChildCount() > 0) {
view.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, mFirstDialogHeight));
}
return view;
}
@Override
protected void onStop() {
super.onStop();
cleanupPageAdapters();
}
private void cleanupPageAdapters() {
for (int i = 0; i < mViewFlipper.getChildCount(); i++) {
CategoryPickerPage page = (CategoryPickerPage) mViewFlipper.getChildAt(i).getTag();
page.cleanup();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mViewFlipper.getChildCount() > 1) {
mViewFlipper.removeViewAt(mViewFlipper.getChildCount() - 1);
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/**
* After the user has dismissed the dialog, the parent activity can use this
* to see which category they picked, if any. Will return null if no
* category was picked.
*/
public Category getChosenCategory() {
return mChosenCategory;
}
private static class CategoryPickerPage {
private CategoryPickerAdapter mListAdapter;
private Category mCategory;
private PageListItemSelected mClickListener;
public void ensureUI(View view, PageListItemSelected clickListener, Category category,
RemoteResourceManager rrm) {
mCategory = category;
mClickListener = clickListener;
mListAdapter = new CategoryPickerAdapter(view.getContext(), rrm, category);
ListView listview = (ListView) view.findViewById(R.id.categoryPickerListView);
listview.setAdapter(mListAdapter);
listview.setOnItemClickListener(mOnItemClickListener);
LinearLayout llRootCategory = (LinearLayout) view
.findViewById(R.id.categoryPickerRootCategoryButton);
if (category.getNodeName().equals("root") == false) {
ImageView iv = (ImageView) view.findViewById(R.id.categoryPickerIcon);
try {
Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(Uri
.parse(category.getIconUrl())));
iv.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.e(TAG, "Error loading category icon from disk.", e);
}
TextView tv = (TextView) view.findViewById(R.id.categoryPickerName);
tv.setText(category.getNodeName());
llRootCategory.setClickable(true);
llRootCategory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mClickListener.onCategorySelected(mCategory);
}
});
} else {
llRootCategory.setVisibility(View.GONE);
}
}
public void cleanup() {
mListAdapter.removeObserver();
}
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
mClickListener.onPageListItemSelcected((Category) mListAdapter.getItem(position));
}
};
}
private PageListItemSelected mPageListItemSelected = new PageListItemSelected() {
@Override
public void onPageListItemSelcected(Category category) {
// If the item has children, create a new page for it.
if (category.getChildCategories() != null && category.getChildCategories().size() > 0) {
mViewFlipper.addView(makePage(category));
mViewFlipper.showNext();
} else {
// This is a leaf node, finally the user's selection. Record the
// category
// then cancel ourselves, parent activity should pick us up
// after that.
mChosenCategory = category;
cancel();
}
}
@Override
public void onCategorySelected(Category category) {
// The user has chosen the category parent listed at the top of the
// current page.
mChosenCategory = category;
cancel();
}
};
private interface PageListItemSelected {
public void onPageListItemSelcected(Category category);
public void onCategorySelected(Category category);
}
}
| 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.types.Response;
import com.joelapenna.foursquare.types.Venue;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
/**
* Gives the user the option to correct some info about a venue:
* <ul>
* <li>Edit venue info</li>
* <li>Flag as closed</li>
* <li>Mislocated (but don't know the right address)</li>
* <li>Flag as duplicate</li>
* </ul>
*
* @date June 7, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class EditVenueOptionsActivity extends Activity {
public static final String EXTRA_VENUE_PARCELABLE = "com.joelapenna.foursquared.VenueParcelable";
private static final String TAG = "EditVenueOptionsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int REQUEST_CODE_ACTIVITY_ADD_VENUE = 15;
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.edit_venue_options_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
ensureUi();
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey(EXTRA_VENUE_PARCELABLE)) {
Venue venue = (Venue)getIntent().getExtras().getParcelable(EXTRA_VENUE_PARCELABLE);
if (venue != null) {
mStateHolder = new StateHolder(venue);
} else {
Log.e(TAG, "EditVenueOptionsActivity supplied with null venue parcelable.");
finish();
}
} else {
Log.e(TAG, "EditVenueOptionsActivity requires venue parcelable in extras.");
finish();
}
} else {
Log.e(TAG, "EditVenueOptionsActivity requires venueid in extras.");
finish();
}
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(true);
if (mStateHolder.getIsRunningTaskVenue()) {
startProgressBar();
}
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates();
stopProgressBar();
if (isFinishing()) {
mStateHolder.cancelTasks();
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void ensureUi() {
Button btnEditVenue = (Button)findViewById(R.id.btnEditVenue);
btnEditVenue.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(EditVenueOptionsActivity.this, AddVenueActivity.class);
intent.putExtra(AddVenueActivity.EXTRA_VENUE_TO_EDIT, mStateHolder.getVenue());
startActivityForResult(intent, REQUEST_CODE_ACTIVITY_ADD_VENUE);
}
});
Button btnFlagAsClosed = (Button)findViewById(R.id.btnFlagAsClosed);
btnFlagAsClosed.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mStateHolder.startTaskVenue(
EditVenueOptionsActivity.this, VenueTask.ACTION_FLAG_AS_CLOSED);
}
});
Button btnFlagAsMislocated = (Button)findViewById(R.id.btnFlagAsMislocated);
btnFlagAsMislocated.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mStateHolder.startTaskVenue(
EditVenueOptionsActivity.this, VenueTask.ACTION_FLAG_AS_MISLOCATED);
}
});
Button btnFlagAsDuplicate = (Button)findViewById(R.id.btnFlagAsDuplicate);
btnFlagAsDuplicate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mStateHolder.startTaskVenue(
EditVenueOptionsActivity.this, VenueTask.ACTION_FLAG_AS_DUPLICATE);
}
});
}
private void startProgressBar() {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this,
null,
getResources().getString(R.string.edit_venue_options_progress_message));
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
private void onVenueTaskComplete(Response response, Exception ex) {
stopProgressBar();
mStateHolder.setIsRunningTaskVenue(false);
if (response != null) {
if (!TextUtils.isEmpty(response.getValue()) && response.getValue().equals("ok")) {
Toast.makeText(this, getResources().getString(R.string.edit_venue_options_thankyou),
Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(this, getResources().getString(R.string.edit_venue_options_error),
Toast.LENGTH_SHORT).show();
}
} else {
// The API is returning an incorrect response object here, it should look like:
// { response: { "response": "ok" }}
// Instead it's just returning:
// { "response": "ok" }
// So the parser framework will fail on it. This should be fixed with api v2,
// just going to assume success here.
//NotificationsUtil.ToastReasonForFailure(this, ex);
Toast.makeText(this, getResources().getString(R.string.edit_venue_options_thankyou),
Toast.LENGTH_SHORT).show();
}
}
private static class VenueTask extends AsyncTask<Void, Void, Response> {
public static final int ACTION_FLAG_AS_CLOSED = 0;
public static final int ACTION_FLAG_AS_MISLOCATED = 1;
public static final int ACTION_FLAG_AS_DUPLICATE = 2;
private EditVenueOptionsActivity mActivity;
private Exception mReason;
private int mAction;
private String mVenueId;
public VenueTask(EditVenueOptionsActivity activity, int action, String venueId) {
mActivity = activity;
mAction = action;
mVenueId = venueId;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected Response doInBackground(Void... params) {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
try {
switch (mAction) {
case ACTION_FLAG_AS_CLOSED:
return foursquare.flagclosed(mVenueId);
case ACTION_FLAG_AS_MISLOCATED:
return foursquare.flagmislocated(mVenueId);
case ACTION_FLAG_AS_DUPLICATE:
return foursquare.flagduplicate(mVenueId);
}
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Response response) {
if (mActivity != null) {
mActivity.onVenueTaskComplete(response, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onVenueTaskComplete(null, mReason);
}
}
public void setActivity(EditVenueOptionsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private Venue mVenue;
private VenueTask mTaskVenue;
private boolean mIsRunningTaskVenue;
public StateHolder(Venue venue) {
mVenue = venue;
mIsRunningTaskVenue = false;
}
public Venue getVenue() {
return mVenue;
}
public void startTaskVenue(EditVenueOptionsActivity activity, int action) {
mIsRunningTaskVenue = true;
mTaskVenue = new VenueTask(activity, action, mVenue.getId());
mTaskVenue.execute();
}
public void setActivity(EditVenueOptionsActivity activity) {
if (mTaskVenue != null) {
mTaskVenue.setActivity(activity);
}
}
public boolean getIsRunningTaskVenue() {
return mIsRunningTaskVenue;
}
public void setIsRunningTaskVenue(boolean isRunning) {
mIsRunningTaskVenue = isRunning;
}
public void cancelTasks() {
if (mTaskVenue != null) {
mTaskVenue.setActivity(null);
mTaskVenue.cancel(true);
mIsRunningTaskVenue = false;
}
}
}
}
| Java |
/*
* Copyright 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
* 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 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 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 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 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquared.Foursquared;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
public FoursquaredAppTestCase() {
super(Foursquared.class);
}
@MediumTest
public void testLocationMethods() {
createApplication();
getApplication().getLastKnownLocation();
getApplication().getLocationListener();
}
@SmallTest
public void testPreferences() {
createApplication();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.VenueActivity;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueActivityInstrumentationTestCase extends
ActivityInstrumentationTestCase2<VenueActivity> {
public VenueActivityInstrumentationTestCase() {
super("com.joelapenna.foursquared", VenueActivity.class);
}
@SmallTest
public void testOnCreate() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra(Foursquared.EXTRA_VENUE_ID, "40450");
setActivityIntent(intent);
VenueActivity activity = getActivity();
activity.openOptionsMenu();
activity.closeOptionsMenu();
}
}
| Java |
package mbi;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JApplet;
import org.jgraph.JGraph;
import org.jgraph.graph.DefaultGraphCell;
import org.jgraph.graph.GraphConstants;
import org.jgrapht.Graph;
import org.jgrapht.ext.JGraphModelAdapter;
public class GrApphlet extends JApplet {
private static final long serialVersionUID = 1L;
private static final Color DEFAULT_BG_COLOR = Color.decode("#FAFBFF");
private static final Dimension DEFAULT_SIZE = new Dimension(1200, 900);
private DeBruijnGraph graph;
public DeBruijnGraph getGraph() {
return graph;
}
public void setGraph(DeBruijnGraph graph) {
this.graph = graph;
}
public void init() {
JGraphModelAdapter<String, String> jGraphAdapter = new JGraphModelAdapter<String, String>(
graph);
JGraph jGraph = new JGraph(jGraphAdapter);
adjustDisplaySettings(jGraph);
getContentPane().add(jGraph);
setSize(DEFAULT_SIZE);
distributeVertices(jGraphAdapter, graph);
}
private void adjustDisplaySettings(JGraph jg) {
jg.setPreferredSize(DEFAULT_SIZE);
Color c = DEFAULT_BG_COLOR;
String colorStr = null;
try {
colorStr = getParameter("bgcolor");
} catch (Exception e) {
}
if (colorStr != null) {
c = Color.decode(colorStr);
}
jg.setBackground(c);
}
private void positionVertexAt(Object vertex, int x, int y,
JGraphModelAdapter<String, String> m_jgAdapter) {
DefaultGraphCell cell = m_jgAdapter.getVertexCell(vertex);
Map attr = cell.getAttributes();
Rectangle2D b = GraphConstants.getBounds(attr);
GraphConstants.setBounds(attr, new Rectangle(x, y, (int) b.getWidth(),
(int) b.getHeight()));
Map cellAttr = new HashMap();
cellAttr.put(cell, attr);
m_jgAdapter.edit(cellAttr, null, null, null);
}
private void distributeVertices(JGraphModelAdapter<String, String> ga,
Graph<String, String> g) {
int vertices = g.vertexSet().size();
double step = 2 * Math.PI / vertices;
double counter = 0;
double stdSpan = 400;
for (String vertex : g.vertexSet()) {
positionVertexAt(vertex, DEFAULT_SIZE.width / 2
+ (int) (stdSpan * Math.cos(counter)), DEFAULT_SIZE.height
/ 2 + (int) (stdSpan * Math.sin(counter)), ga);
counter += step;
}
}
}
| Java |
package mbi;
import java.util.Set;
import org.jgrapht.EdgeFactory;
import org.jgrapht.graph.DirectedMultigraph;
public class DeBruijnEdgeFactory implements EdgeFactory<String, String> {
private DirectedMultigraph<String, String> graph;
public void setGraph(DirectedMultigraph<String, String> graph){
this.graph = graph;
}
@Override
public String createEdge(String v1, String v2) {
if(v1.substring(1).equals(v2.substring(0, v2.length()-1)) || v1.length() != v2.length()){
String suffix="";
if(graph.containsEdge(v1, v2)){
Set<String> fromV1 = graph.outgoingEdgesOf(v1);
Set<String> intoV2 = graph.incomingEdgesOf(v2);
int nextNo=1;
for(String fv1:fromV1){
if(intoV2.contains(fv1)){
++nextNo;
}
}
suffix="("+nextNo+")";
}
if(v1.length()>v2.length()){
return v1+v2.substring(v2.length()-1, v2.length())+suffix;
}else{
return v1.substring(0,1)+v2+suffix;
}
}else{
return null;
}
}
}
| Java |
package mbi;
public class MbiException extends Exception {
private static final long serialVersionUID = 1L;
public MbiException(String msg) {
super(msg);
}
}
| Java |
package mbi;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
/**
* Just a wrapper class for commonly
*/
public class AssemblerDNA {
/**
* generates
*/
public static String generateSequence(int length) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; ++i) {
double rand = Math.random();
if (rand > 0.75) {
builder.append("C");
} else if (rand > 0.5) {
builder.append("G");
} else if (rand > 0.25) {
builder.append("T");
} else {
builder.append("A");
}
}
return builder.toString();
}
/**
* @param dna
* input sequence
* @param readLength
* length of desired k-mer
* @param number
* number of reads
* @return
*/
public static Set<String> shotgun(String dna, int readLength, int number) {
Set<String> results = new HashSet<String>();
for (int i = 0; i < number; ++i) {
int startIndex = (int) (Math.random() * dna.length());
String sample = (dna.substring(startIndex,
Math.min(startIndex + readLength, dna.length())));
if (sample != null && sample.length() >= readLength) {
results.add(sample);
}
}
return results;
}
/**
* Shotgun with limited overlaps
*/
public static Set<String> safeShotgun(String dna, int readLength) {
Set<String> results = new HashSet<String>();
for (int startIndex = 0, endIndex = readLength; startIndex < dna
.length() - readLength; startIndex += (int) (Math.random()
* readLength / 2), endIndex = startIndex + readLength) {
results.add(dna.substring(startIndex, endIndex));
}
results.add(dna.substring(dna.length() - readLength, dna.length()));
return results;
}
public static List<String> extractKmers(Set<String> reads, int k) {
List<String> kmers = new LinkedList<String>();
for (String read : reads) {
if (k > read.length()) {
continue;
} else {
for (int s = 0, e = k; e <= read.length(); ++s, ++e) {
kmers.add(read.substring(s, e));
}
}
}
Collections.shuffle(kmers);
return kmers;
}
/**
* No random overlaps, shotgun with ideal step (1). Returns a shuffled list
* of k-mers
*
* @param dna
* @param k
* @return
*/
public static List<String> idealShotgun(String dna, int k) {
List<String> results = new LinkedList<String>();
for (int i = 0; i <= dna.length() - k; ++i) {
results.add(dna.substring(i, i + k));
}
Collections.shuffle(results);
return results;
}
/**
*
* @param str
* Collection of reads to print
*/
public static void printAll(Collection<String> str) {
for (String k : str) {
System.out.println(k);
}
}
public static DeBruijnGraph getDeBruijnGraph(Collection<String> kmers,
boolean allowRepeatedEdges) {
DeBruijnGraph graph = new DeBruijnGraph(new DeBruijnEdgeFactory());
for (String kmer : kmers) {
int s = 0;
int e = kmer.length();
String lo = kmer.substring(s, e - 1);
String ld = kmer.substring(s + 1, e);
if (!graph.containsVertex(lo)) {
graph.addVertex(lo);
}
if (!graph.containsVertex(ld)) {
graph.addVertex(ld);
}
if (!graph.containsEdge(lo, ld) || allowRepeatedEdges) {
graph.addEdge(lo, ld);
}
}
return graph;
}
public static String assemble(List<String> kmers, boolean verbose)
throws MbiException {
DeBruijnGraph graph = getDeBruijnGraph(kmers, true);
List<String> path = graph.findEulerPath(verbose);
if (path != null && path.size() > 0) {
return pathToGenome(path);
} else {
throw new MbiException("Returned empty or null Euler path!");
}
}
public static String pathToGenome(List<String> path) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < path.size() - 1; ++i) {
sb.append(path.get(i).substring(0, 1));
}
sb.append(path.get(path.size() - 1));
return sb.toString();
}
public static String readSequenceFromFile(String fileName) {
String subStr = "";
try {
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
subStr += strLine;
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
return subStr.trim();
}
/**
* replace source vertex in chain with new vertex
*
* @param graph
* @param vertOld
* @param vertNew
* @return
*/
private static DeBruijnGraph replaceSourceVertex(DeBruijnGraph graph,
String vertOld, String vertNew) {
Set<String> inEdgV1 = graph.incomingEdgesOf(vertOld);
graph.addVertex(vertNew);
String vertArr[] = new String[inEdgV1.size()];
int i = 0;
for (String e : inEdgV1) {
vertArr[i++] = graph.getEdgeSource(e);
}
// copy all edges to new vertex
for (String v : vertArr) {
graph.addEdge(v, vertNew);
}
graph.removeVertex(vertOld);
return graph;
}
/**
* replace target vertex in chain with new vertex
*
* @param graph
* @param vertOld
* @param vertNew
* @return
*/
private static DeBruijnGraph replaceTargetVertex(DeBruijnGraph graph,
String vertOld, String vertNew) {
Set<String> outEdgV1 = graph.outgoingEdgesOf(vertOld);
String vertArr[] = new String[outEdgV1.size()];
int i = 0;
for (String e : outEdgV1) {
vertArr[i++] = graph.getEdgeTarget(e);
}
// copy all edges to new vertex
for (String v : vertArr) {
graph.addEdge(vertNew, v);
}
graph.removeVertex(vertOld);
return graph;
}
/**
* contact two vertexes to one
*
* @param v1
* @param v2
* @return
*/
private static String contactVertexes(String v1, String v2) {
String newVert = "";
if (v1.length() > v2.length()) {
newVert = v1.concat(v2.substring(v2.length() - 1));
} else {
newVert = v1.substring(0, 1).concat(v2.substring(0, v2.length()));
}
return newVert;
}
/**
* Function transforms "chains" of vertexes to one longer vertex. Chains
* consitst vertexex with only one outgoingn and one ingoing edges.
*
* @param graph
* @return simplified graph
*/
public static DeBruijnGraph simplify(DeBruijnGraph graph) {
// System.out.println(graph.vertexSet().toString());
// System.out.println(graph.edgeSet().toString());
boolean wasNewVert = true;
while (wasNewVert) {
wasNewVert = false;
Set<String> tmpVert = graph.vertexSet();
String certArr[] = new String[tmpVert.size()];
int i = 0;
for (String tV : tmpVert) {
certArr[i++] = tV;
}
for (String v1 : certArr) {
// check if vertex is still in graph
if (graph.containsVertex(v1)) {
Set<String> edgs = graph.outgoingEdgesOf(v1);
if (edgs.size() == 1) { // check if vertex has only one
// outgoing edge
String e = (String) edgs.iterator().next();
String v2 = graph.getEdgeTarget(e);
Set<String> edgs2 = graph.incomingEdgesOf(v2);
if (edgs2.size() == 1) { // check if vertes on the end
// of that edge, has only
// one ingoing vertex
String newVert = contactVertexes(v1, v2); // create
// longer
// vertex
// from
// two
// vertexes
graph = replaceSourceVertex(graph, v1, newVert);
graph = replaceTargetVertex(graph, v2, newVert);
wasNewVert = true;
}
}
}
}
}
return graph;
}
}
| Java |
package mbi;
import java.awt.BorderLayout;
import java.util.Arrays;
import java.util.List;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class Main {
public static void printUsage() {
System.out
.println("Please provide one of the following sets of parameters:");
System.out.println("-f <PATH> -k <K> - to read sequence form PATH");
System.out
.println("-r <LENGTH> -k <K> - to generate a random sequence of length <LENGTH>");
System.out
.println("benchmark (yes, just one word) - run some built-in tests");
System.out
.println("#######################################################################");
System.out
.println("PATH - path to read the file containing the sequence fro");
System.out.println("LENGTH - length of the sequence to be generated");
}
/**
* @param args
*/
public static void main(String[] args) {
if (args.length == 0) {
printUsage();
System.exit(1);
}
String path = null;
int randLength = -1;
String sequence = "ABRAKADABRA";
int k = 5;
for (int i = 0; i < args.length - 1; ++i) {
if (args[i].equals("-f")) {
path = args[i + 1];
} else if (args[i].equals("-r")) {
randLength = Integer.parseInt(args[i + 1]);
} else if (args[i].equals("-k")) {
k = Integer.parseInt(args[i + 1]);
}
}
if (Arrays.binarySearch(args, "benchmark") >= 0) {
benchmark();
return;
}
if (randLength > 0) {
sequence = AssemblerDNA.generateSequence(randLength);
} else {
sequence = AssemblerDNA.readSequenceFromFile(path);
}
List<String> kmers = AssemblerDNA.idealShotgun(sequence, k);
DeBruijnGraph graph = AssemblerDNA.getDeBruijnGraph(kmers, true);
// graph = AssemblerDNA.simplify(graph);
JApplet grApphlet = new GrApphlet();
((GrApphlet) grApphlet).setGraph(graph);
JFrame mainFrame = new JFrame("12l-mbi");
grApphlet.init();
mainFrame.add(grApphlet, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("K-MERS: " + kmers.toString());
System.out.println("input: " + sequence);
try {
String result = AssemblerDNA.assemble(kmers, true);
System.out.println("INPUT "
+ (sequence.equals(result) ? "equals" : "differs from")
+ " RESULT");
System.out.println("result: " + result);
if (result != null) {
System.out.println("INPUT "
+ (sequence.indexOf(result, 0) > -1 ? "contains"
: "doesn't contain") + " RESULT");
System.out.println("RESULT "
+ (result.indexOf(sequence, 0) > -1 ? "contains"
: "doesn't contain") + " GENERATED");
}
} catch (MbiException e) {
System.out.println("Exception: " + e.getMessage());
}
}
public static void benchmark() {
for (int length = 15; length < 10000; length *= 1.5) {
for (int k = 3; k < 20; ++k) {
int successes = 0;
long levelTotalTime = 0;
for (int test = 0; test < 100; ++test) {
String sequence = AssemblerDNA.generateSequence(length);
long startTime = System.currentTimeMillis();
try {
String result = AssemblerDNA.assemble(
AssemblerDNA.idealShotgun(sequence, k), false);
if (sequence.equals(result)) {
++successes;
}
} catch (MbiException e) {
} finally {
levelTotalTime += (System.currentTimeMillis() - startTime);
}
}
System.out.println("Length: " + length + ", K: " + k
+ ", success ratio: " + successes / (double) 100
+ ", avg. time: " + levelTotalTime / (double) (100)
+ " msec.");
}
}
}
}
| Java |
package mbi;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.jgrapht.graph.DirectedMultigraph;
public class DeBruijnGraph extends DirectedMultigraph<String, String> {
private static final long serialVersionUID = 1L;
public DeBruijnGraph(DeBruijnEdgeFactory arg0) {
super(arg0);
arg0.setGraph(this);
}
// TODO: figure out a way to do it.
public void balance() {
}
public Set<String> getImbalancedVertices() {
Set<String> vers = new HashSet<String>();
for (String vert : this.vertexSet()) {
if (this.inDegreeOf(vert) != this.outDegreeOf(vert)) {
vers.add(vert);
}
}
return vers;
}
public synchronized List<String> findEulerPath(boolean verbose)
throws MbiException {
List<String> path = new LinkedList<String>();
DeBruijnGraph g = (DeBruijnGraph) this.clone();
while (g.vertexSet().size() != 0) {
String start = null, end = null;
int startIndex = -1;
if (path.size() == 0) {
Set<String> imbalanced = g.getImbalancedVertices();
if (imbalanced.size() != 2) {
if (verbose) {
System.err.println("Imbalanced graph. Aborting...");
}
throw new MbiException("Imbalanced graph given");
}
for (String vert : imbalanced) {
if (g.inDegreeOf(vert) < g.outDegreeOf(vert)) {
start = vert;
} else if (g.inDegreeOf(vert) > g.outDegreeOf(vert)) {
end = vert;
}
}
assert (start != null && end != null && !start.equals(end));
} else { // that is path is not null
for (String vert : g.vertexSet()) {
startIndex = path.lastIndexOf(vert);
if (startIndex >= 0) {
path.remove(startIndex);
start = vert;
break;
}
}
}
while (start != null) {
if (startIndex == -1) {
path.add(start);
} else {
path.add(startIndex++, start);
}
Set<String> directions = g.outgoingEdgesOf(start);
if (directions.size() > 0) {
String direction = directions.toArray(new String[directions
.size()])[0];
start = g.getEdgeTarget(direction);
g.removeEdge(direction);
} else {
start = null;
}
}
// remove stranded vertices - could have maintained a list of used
// vertices...
Set<String> vertsToRemove = new HashSet<String>();
for (String vert : g.vertexSet()) {
if (g.inDegreeOf(vert) == 0 && g.outDegreeOf(vert) == 0) {
vertsToRemove.add(vert);
}
}
for (String vert : vertsToRemove) {
g.removeVertex(vert);
}
}
return path;
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.multiple;
import java.util.List;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class BasicCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
private String[] myCrawlDomains;
@Override
public void onStart() {
myCrawlDomains = (String[]) myController.getCustomData();
}
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
if (FILTERS.matcher(href).matches()) {
return false;
}
for (String crawlDomain : myCrawlDomains) {
if (href.startsWith(crawlDomain)) {
return true;
}
}
return false;
}
@Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
int parentDocid = page.getWebURL().getParentDocid();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Docid of parent page: " + parentDocid);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
System.out.println("=============");
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.multiple;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class MultipleCrawlerController {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("Needed parameter: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
CrawlConfig config1 = new CrawlConfig();
CrawlConfig config2 = new CrawlConfig();
/*
* The two crawlers should have different storage folders for their
* intermediate data
*/
config1.setCrawlStorageFolder(crawlStorageFolder + "/crawler1");
config2.setCrawlStorageFolder(crawlStorageFolder + "/crawler2");
config1.setPolitenessDelay(1000);
config2.setPolitenessDelay(2000);
config1.setMaxPagesToFetch(50);
config2.setMaxPagesToFetch(100);
/*
* We will use different PageFetchers for the two crawlers.
*/
PageFetcher pageFetcher1 = new PageFetcher(config1);
PageFetcher pageFetcher2 = new PageFetcher(config2);
/*
* We will use the same RobotstxtServer for both of the crawlers.
*/
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher1);
CrawlController controller1 = new CrawlController(config1, pageFetcher1, robotstxtServer);
CrawlController controller2 = new CrawlController(config2, pageFetcher2, robotstxtServer);
String[] crawler1Domains = new String[] { "http://www.ics.uci.edu/", "http://www.cnn.com/" };
String[] crawler2Domains = new String[] { "http://en.wikipedia.org/" };
controller1.setCustomData(crawler1Domains);
controller2.setCustomData(crawler2Domains);
controller1.addSeed("http://www.ics.uci.edu/");
controller1.addSeed("http://www.cnn.com/");
controller1.addSeed("http://www.ics.uci.edu/~lopes/");
controller1.addSeed("http://www.cnn.com/POLITICS/");
controller2.addSeed("http://en.wikipedia.org/wiki/Main_Page");
controller2.addSeed("http://en.wikipedia.org/wiki/Obama");
controller2.addSeed("http://en.wikipedia.org/wiki/Bing");
/*
* The first crawler will have 5 cuncurrent threads and the second
* crawler will have 7 threads.
*/
controller1.startNonBlocking(BasicCrawler.class, 5);
controller2.startNonBlocking(BasicCrawler.class, 7);
controller1.waitUntilFinish();
System.out.println("Crawler 1 is finished.");
controller2.waitUntilFinish();
System.out.println("Crawler 2 is finished.");
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.statushandler;
import java.util.regex.Pattern;
import org.apache.http.HttpStatus;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class StatusHandlerCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether
* the given url should be crawled or not (based on your
* crawling logic).
*/
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready
* to be processed by your program.
*/
@Override
public void visit(Page page) {
// Do nothing
}
@Override
protected void handlePageStatusCode(WebURL webUrl, int statusCode, String statusDescription) {
if (statusCode != HttpStatus.SC_OK) {
if (statusCode == HttpStatus.SC_NOT_FOUND) {
System.out.println("Broken link: " + webUrl.getURL() + ", this link was found in page: " + webUrl.getParentUrl());
} else {
System.out.println("Non success status for link: " + webUrl.getURL() + ", status code: " + statusCode + ", description: " + statusDescription);
}
}
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.statushandler;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class StatusHandlerCrawlController {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
/*
* Be polite: Make sure that we don't send more than 1 request per
* second (1000 milliseconds between requests).
*/
config.setPolitenessDelay(1000);
/*
* You can set the maximum crawl depth here. The default value is -1 for
* unlimited depth
*/
config.setMaxDepthOfCrawling(2);
/*
* You can set the maximum number of pages to crawl. The default value
* is -1 for unlimited number of pages
*/
config.setMaxPagesToFetch(1000);
/*
* Do you need to set a proxy? If so, you can use:
* config.setProxyHost("proxyserver.example.com");
* config.setProxyPort(8080);
*
* If your proxy also needs authentication:
* config.setProxyUsername(username); config.getProxyPassword(password);
*/
/*
* This config parameter can be used to set your crawl to be resumable
* (meaning that you can resume the crawl from a previously
* interrupted/crashed crawl). Note: if you enable resuming feature and
* want to start a fresh crawl, you need to delete the contents of
* rootFolder manually.
*/
config.setResumableCrawling(false);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/~welling/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.start(StatusHandlerCrawler.class, numberOfCrawlers);
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.shutdown;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class ControllerWithShutdown {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
config.setPolitenessDelay(1000);
// Unlimited number of pages can be crawled.
config.setMaxPagesToFetch(-1);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/~welling/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.startNonBlocking(BasicCrawler.class, numberOfCrawlers);
// Wait for 30 seconds
Thread.sleep(30 * 1000);
// Send the shutdown request and then wait for finishing
controller.shutdown();
controller.waitUntilFinish();
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.shutdown;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.List;
import java.util.regex.Pattern;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class BasicCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
private final static String DOMAIN = "http://www.ics.uci.edu/";
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith(DOMAIN);
}
@Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
int parentDocid = page.getWebURL().getParentDocid();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Docid of parent page: " + parentDocid);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
System.out.println("=============");
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.imagecrawler;
import java.security.MessageDigest;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class Cryptography {
private static final char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'f' };
public static String MD5(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
return hexStringFromBytes(md.digest());
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
private static String hexStringFromBytes(byte[] b) {
String hex = "";
int msb;
int lsb;
int i;
// MSB maps to idx 0
for (i = 0; i < b.length; i++) {
msb = (b[i] & 0x000000FF) / 16;
lsb = (b[i] & 0x000000FF) % 16;
hex = hex + hexChars[msb] + hexChars[lsb];
}
return (hex);
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.imagecrawler;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
/*
* IMPORTANT: Make sure that you update crawler4j.properties file and set
* crawler.include_images to true
*/
public class ImageCrawlController {
public static void main(String[] args) throws Exception {
if (args.length < 3) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
System.out.println("\t storageFolder (a folder for storing downloaded images)");
return;
}
String rootFolder = args[0];
int numberOfCrawlers = Integer.parseInt(args[1]);
String storageFolder = args[2];
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(rootFolder);
/*
* Since images are binary content, we need to set this parameter to
* true to make sure they are included in the crawl.
*/
config.setIncludeBinaryContentInCrawling(true);
String[] crawlDomains = new String[] { "http://uci.edu/" };
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
for (String domain : crawlDomains) {
controller.addSeed(domain);
}
ImageCrawler.configure(crawlDomains, storageFolder);
controller.start(ImageCrawler.class, numberOfCrawlers);
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.imagecrawler;
import java.io.File;
import java.util.regex.Pattern;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.BinaryParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import edu.uci.ics.crawler4j.util.IO;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
/*
* This class shows how you can crawl images on the web and store them in a
* folder. This is just for demonstration purposes and doesn't scale for large
* number of images. For crawling millions of images you would need to store
* downloaded images in a hierarchy of folders
*/
public class ImageCrawler extends WebCrawler {
private static final Pattern filters = Pattern.compile(".*(\\.(css|js|mid|mp2|mp3|mp4|wav|avi|mov|mpeg|ram|m4v|pdf"
+ "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
private static final Pattern imgPatterns = Pattern.compile(".*(\\.(bmp|gif|jpe?g|png|tiff?))$");
private static File storageFolder;
private static String[] crawlDomains;
public static void configure(String[] domain, String storageFolderName) {
ImageCrawler.crawlDomains = domain;
storageFolder = new File(storageFolderName);
if (!storageFolder.exists()) {
storageFolder.mkdirs();
}
}
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
if (filters.matcher(href).matches()) {
return false;
}
if (imgPatterns.matcher(href).matches()) {
return true;
}
for (String domain : crawlDomains) {
if (href.startsWith(domain)) {
return true;
}
}
return false;
}
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
// We are only interested in processing images
if (!(page.getParseData() instanceof BinaryParseData)) {
return;
}
if (!imgPatterns.matcher(url).matches()) {
return;
}
// Not interested in very small images
if (page.getContentData().length < 10 * 1024) {
return;
}
// get a unique name for storing this image
String extension = url.substring(url.lastIndexOf("."));
String hashedName = Cryptography.MD5(url) + extension;
// store image
IO.writeBytesToFile(page.getContentData(), storageFolder.getAbsolutePath() + "/" + hashedName);
System.out.println("Stored: " + url);
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.basic;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class BasicCrawlController {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
/*
* crawlStorageFolder is a folder where intermediate crawl data is
* stored.
*/
String crawlStorageFolder = args[0];
/*
* numberOfCrawlers shows the number of concurrent threads that should
* be initiated for crawling.
*/
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
/*
* Be polite: Make sure that we don't send more than 1 request per
* second (1000 milliseconds between requests).
*/
config.setPolitenessDelay(1000);
/*
* You can set the maximum crawl depth here. The default value is -1 for
* unlimited depth
*/
config.setMaxDepthOfCrawling(2);
/*
* You can set the maximum number of pages to crawl. The default value
* is -1 for unlimited number of pages
*/
config.setMaxPagesToFetch(1000);
/*
* Do you need to set a proxy? If so, you can use:
* config.setProxyHost("proxyserver.example.com");
* config.setProxyPort(8080);
*
* If your proxy also needs authentication:
* config.setProxyUsername(username); config.getProxyPassword(password);
*/
/*
* This config parameter can be used to set your crawl to be resumable
* (meaning that you can resume the crawl from a previously
* interrupted/crashed crawl). Note: if you enable resuming feature and
* want to start a fresh crawl, you need to delete the contents of
* rootFolder manually.
*/
config.setResumableCrawling(false);
/*
* Instantiate the controller for this crawl.
*/
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
/*
* For each crawl, you need to add some seed urls. These are the first
* URLs that are fetched and then the crawler starts following links
* which are found in these pages
*/
controller.addSeed("http://www.ics.uci.edu/");
controller.addSeed("http://www.ics.uci.edu/~lopes/");
controller.addSeed("http://www.ics.uci.edu/~welling/");
/*
* Start the crawl. This is a blocking operation, meaning that your code
* will reach the line after this only when crawling is finished.
*/
controller.start(BasicCrawler.class, numberOfCrawlers);
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.basic;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.http.Header;
/**
* @author Yasser Ganjisaffar <lastname at gmail dot com>
*/
public class BasicCrawler extends WebCrawler {
private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether the given url
* should be crawled or not (based on your crawling logic).
*/
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready to be processed
* by your program.
*/
@Override
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String domain = page.getWebURL().getDomain();
String path = page.getWebURL().getPath();
String subDomain = page.getWebURL().getSubDomain();
String parentUrl = page.getWebURL().getParentUrl();
String anchor = page.getWebURL().getAnchor();
System.out.println("Docid: " + docid);
System.out.println("URL: " + url);
System.out.println("Domain: '" + domain + "'");
System.out.println("Sub-domain: '" + subDomain + "'");
System.out.println("Path: '" + path + "'");
System.out.println("Parent page: " + parentUrl);
System.out.println("Anchor text: " + anchor);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " + links.size());
}
Header[] responseHeaders = page.getFetchResponseHeaders();
if (responseHeaders != null) {
System.out.println("Response headers:");
for (Header header : responseHeaders) {
System.out.println("\t" + header.getName() + ": " + header.getValue());
}
}
System.out.println("=============");
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.localdata;
import org.apache.http.HttpStatus;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.fetcher.PageFetchResult;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.parser.ParseData;
import edu.uci.ics.crawler4j.parser.Parser;
import edu.uci.ics.crawler4j.url.WebURL;
/**
* This class is a demonstration of how crawler4j can be used to download a
* single page and extract its title and text.
*/
public class Downloader {
private Parser parser;
private PageFetcher pageFetcher;
public Downloader() {
CrawlConfig config = new CrawlConfig();
parser = new Parser(config);
pageFetcher = new PageFetcher(config);
}
private Page download(String url) {
WebURL curURL = new WebURL();
curURL.setURL(url);
PageFetchResult fetchResult = null;
try {
fetchResult = pageFetcher.fetchHeader(curURL);
if (fetchResult.getStatusCode() == HttpStatus.SC_OK) {
try {
Page page = new Page(curURL);
fetchResult.fetchContent(page);
if (parser.parse(page, curURL.getURL())) {
return page;
}
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
if (fetchResult != null)
{
fetchResult.discardContentIfNotConsumed();
}
}
return null;
}
public void processUrl(String url) {
System.out.println("Processing: " + url);
Page page = download(url);
if (page != null) {
ParseData parseData = page.getParseData();
if (parseData != null) {
if (parseData instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData) parseData;
System.out.println("Title: " + htmlParseData.getTitle());
System.out.println("Text length: " + htmlParseData.getText().length());
System.out.println("Html length: " + htmlParseData.getHtml().length());
}
} else {
System.out.println("Couldn't parse the content of the page.");
}
} else {
System.out.println("Couldn't fetch the content of the page.");
}
System.out.println("==============");
}
public static void main(String[] args) {
Downloader downloader = new Downloader();
downloader.processUrl("http://en.wikipedia.org/wiki/Main_Page/");
downloader.processUrl("http://www.yahoo.com/");
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.localdata;
import java.util.List;
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
public class LocalDataCollectorController {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("Needed parameters: ");
System.out.println("\t rootFolder (it will contain intermediate crawl data)");
System.out.println("\t numberOfCralwers (number of concurrent threads)");
return;
}
String rootFolder = args[0];
int numberOfCrawlers = Integer.parseInt(args[1]);
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(rootFolder);
config.setMaxPagesToFetch(10);
config.setPolitenessDelay(1000);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config, pageFetcher, robotstxtServer);
controller.addSeed("http://www.ics.uci.edu/");
controller.start(LocalDataCollectorCrawler.class, numberOfCrawlers);
List<Object> crawlersLocalData = controller.getCrawlersLocalData();
long totalLinks = 0;
long totalTextSize = 0;
int totalProcessedPages = 0;
for (Object localData : crawlersLocalData) {
CrawlStat stat = (CrawlStat) localData;
totalLinks += stat.getTotalLinks();
totalTextSize += stat.getTotalTextSize();
totalProcessedPages += stat.getTotalProcessedPages();
}
System.out.println("Aggregated Statistics:");
System.out.println(" Processed Pages: " + totalProcessedPages);
System.out.println(" Total Links found: " + totalLinks);
System.out.println(" Total Text Size: " + totalTextSize);
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.localdata;
public class CrawlStat {
private int totalProcessedPages;
private long totalLinks;
private long totalTextSize;
public int getTotalProcessedPages() {
return totalProcessedPages;
}
public void setTotalProcessedPages(int totalProcessedPages) {
this.totalProcessedPages = totalProcessedPages;
}
public void incProcessedPages() {
this.totalProcessedPages++;
}
public long getTotalLinks() {
return totalLinks;
}
public void setTotalLinks(long totalLinks) {
this.totalLinks = totalLinks;
}
public long getTotalTextSize() {
return totalTextSize;
}
public void setTotalTextSize(long totalTextSize) {
this.totalTextSize = totalTextSize;
}
public void incTotalLinks(int count) {
this.totalLinks += count;
}
public void incTotalTextSize(int count) {
this.totalTextSize += count;
}
}
| Java |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 edu.uci.ics.crawler4j.examples.localdata;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.regex.Pattern;
public class LocalDataCollectorCrawler extends WebCrawler {
Pattern filters = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
+ "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");
CrawlStat myCrawlStat;
public LocalDataCollectorCrawler() {
myCrawlStat = new CrawlStat();
}
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !filters.matcher(href).matches() && href.startsWith("http://www.ics.uci.edu/");
}
@Override
public void visit(Page page) {
System.out.println("Visited: " + page.getWebURL().getURL());
myCrawlStat.incProcessedPages();
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData parseData = (HtmlParseData) page.getParseData();
List<WebURL> links = parseData.getOutgoingUrls();
myCrawlStat.incTotalLinks(links.size());
try {
myCrawlStat.incTotalTextSize(parseData.getText().getBytes("UTF-8").length);
} catch (UnsupportedEncodingException ignored) {
// Do nothing
}
}
// We dump this crawler statistics after processing every 50 pages
if (myCrawlStat.getTotalProcessedPages() % 50 == 0) {
dumpMyData();
}
}
// This function is called by controller to get the local data of this
// crawler when job is finished
@Override
public Object getMyLocalData() {
return myCrawlStat;
}
// This function is called by controller before finishing the job.
// You can put whatever stuff you need here.
@Override
public void onBeforeExit() {
dumpMyData();
}
public void dumpMyData() {
int id = getMyId();
// This is just an example. Therefore I print on screen. You may
// probably want to write in a text file.
System.out.println("Crawler " + id + "> Processed Pages: " + myCrawlStat.getTotalProcessedPages());
System.out.println("Crawler " + id + "> Total Links Found: " + myCrawlStat.getTotalLinks());
System.out.println("Crawler " + id + "> Total Text Size: " + myCrawlStat.getTotalTextSize());
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.