code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.types;
import java.util.ArrayList;
import java.util.List;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Tags extends ArrayList<String> implements FoursquareType {
private static final long serialVersionUID = 1L;
public Tags() {
super();
}
public Tags(List<String> values) {
super();
addAll(values);
}
} | Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquare.types.Credentials;
import com.joelapenna.foursquare.types.FriendInvitesResult;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Response;
import com.joelapenna.foursquare.types.Settings;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import android.net.Uri;
import android.text.TextUtils;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Foursquare {
private static final Logger LOG = Logger.getLogger("com.joelapenna.foursquare");
public static final boolean DEBUG = false;
public static final boolean PARSER_DEBUG = false;
public static final String FOURSQUARE_API_DOMAIN = "api.foursquare.com";
public static final String FOURSQUARE_MOBILE_ADDFRIENDS = "http://m.foursquare.com/addfriends";
public static final String FOURSQUARE_MOBILE_FRIENDS = "http://m.foursquare.com/friends";
public static final String FOURSQUARE_MOBILE_SIGNUP = "http://m.foursquare.com/signup";
public static final String FOURSQUARE_PREFERENCES = "http://foursquare.com/settings";
public static final String MALE = "male";
public static final String FEMALE = "female";
private String mPhone;
private String mPassword;
private FoursquareHttpApiV1 mFoursquareV1;
@V1
public Foursquare(FoursquareHttpApiV1 httpApi) {
mFoursquareV1 = httpApi;
}
public void setCredentials(String phone, String password) {
mPhone = phone;
mPassword = password;
mFoursquareV1.setCredentials(phone, password);
}
@V1
public void setOAuthToken(String token, String secret) {
mFoursquareV1.setOAuthTokenWithSecret(token, secret);
}
@V1
public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) {
mFoursquareV1.setOAuthConsumerCredentials(oAuthConsumerKey, oAuthConsumerSecret);
}
public void clearAllCredentials() {
setCredentials(null, null);
setOAuthToken(null, null);
}
@V1
public boolean hasCredentials() {
return mFoursquareV1.hasCredentials() && mFoursquareV1.hasOAuthTokenWithSecret();
}
@V1
public boolean hasLoginAndPassword() {
return mFoursquareV1.hasCredentials();
}
@V1
public Credentials authExchange() throws FoursquareException, FoursquareError,
FoursquareCredentialsException, IOException {
if (mFoursquareV1 == null) {
throw new NoSuchMethodError(
"authExchange is unavailable without a consumer key/secret.");
}
return mFoursquareV1.authExchange(mPhone, mPassword);
}
@V1
public Tip addTip(String vid, String text, String type, Location location)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.addtip(vid, text, type, location.geolat, location.geolong,
location.geohacc, location.geovacc, location.geoalt);
}
@V1
public Tip tipDetail(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.tipDetail(tid);
}
@V1
@LocationRequired
public Venue addVenue(String name, String address, String crossstreet, String city,
String state, String zip, String phone, String categoryId, Location location)
throws FoursquareException,
FoursquareError, IOException {
return mFoursquareV1.addvenue(name, address, crossstreet, city, state, zip, phone,
categoryId, location.geolat, location.geolong, location.geohacc, location.geovacc,
location.geoalt);
}
@V1
public CheckinResult checkin(String venueId, String venueName, Location location, String shout,
boolean isPrivate, boolean tellFollowers, boolean twitter, boolean facebook)
throws FoursquareException,
FoursquareError,
IOException {
return mFoursquareV1.checkin(venueId, venueName, location.geolat, location.geolong,
location.geohacc, location.geovacc, location.geoalt, shout, isPrivate,
tellFollowers, twitter, facebook);
}
@V1
public Group<Checkin> checkins(Location location) throws FoursquareException, FoursquareError,
IOException {
return mFoursquareV1.checkins(location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt);
}
@V1
public Group<User> friends(String userId, Location location) throws FoursquareException,
FoursquareError, IOException {
return mFoursquareV1.friends(userId, location.geolat, location.geolong,
location.geohacc, location.geovacc, location.geoalt);
}
@V1
public Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.friendRequests();
}
@V1
public User friendApprove(String userId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.friendApprove(userId);
}
@V1
public User friendDeny(String userId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.friendDeny(userId);
}
@V1
public User friendSendrequest(String userId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.friendSendrequest(userId);
}
@V1
public Group<Tip> tips(Location location, String uid, String filter, String sort, int limit)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.tips(location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt, uid, filter, sort, limit);
}
@V1
public Group<Todo> todos(Location location, String uid, boolean recent, boolean nearby, int limit)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.todos(uid, location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt, recent, nearby, limit);
}
@V1
public User user(String user, boolean mayor, boolean badges, boolean stats, Location location)
throws FoursquareException, FoursquareError, IOException {
if (location != null) {
return mFoursquareV1.user(user, mayor, badges, stats, location.geolat, location.geolong,
location.geohacc, location.geovacc, location.geoalt);
} else {
return mFoursquareV1.user(user, mayor, badges, stats, null, null, null, null, null);
}
}
@V1
public Venue venue(String id, Location location) throws FoursquareException, FoursquareError,
IOException {
return mFoursquareV1.venue(id, location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt);
}
@V1
@LocationRequired
public Group<Group<Venue>> venues(Location location, String query, int limit)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.venues(location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt, query, limit);
}
@V1
public Group<User> findFriendsByName(String text)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByName(text);
}
@V1
public Group<User> findFriendsByPhone(String text)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByPhone(text);
}
@V1
public Group<User> findFriendsByFacebook(String text)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByFacebook(text);
}
@V1
public Group<User> findFriendsByTwitter(String text)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByTwitter(text);
}
@V1
public Group<Category> categories()
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.categories();
}
@V1
public Group<Checkin> history(String limit, String sinceid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.history(limit, sinceid);
}
@V1
public Todo markTodo(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.markTodo(tid);
}
@V1
public Todo markTodoVenue(String vid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.markTodoVenue(vid);
}
@V1
public Tip markIgnore(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.markIgnore(tid);
}
@V1
public Tip markDone(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.markDone(tid);
}
@V1
public Tip unmarkTodo(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.unmarkTodo(tid);
}
@V1
public Tip unmarkDone(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.unmarkDone(tid);
}
@V1
public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByPhoneOrEmail(phones, emails);
}
@V1
public Response inviteByEmail(String emails)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.inviteByEmail(emails);
}
@V1
public Settings setpings(boolean on)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.setpings(on);
}
@V1
public Settings setpings(String userid, boolean on)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.setpings(userid, on);
}
@V1
public Response flagclosed(String venueid)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.flagclosed(venueid);
}
@V1
public Response flagmislocated(String venueid)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.flagmislocated(venueid);
}
@V1
public Response flagduplicate(String venueid)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.flagduplicate(venueid);
}
@V1
public Response proposeedit(String venueId, String name, String address, String crossstreet,
String city, String state, String zip, String phone, String categoryId, Location location)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.proposeedit(venueId, name, address, crossstreet, city, state, zip,
phone, categoryId, location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt);
}
@V1
public User userUpdate(String imagePathToJpg, String username, String password)
throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException {
return mFoursquareV1.userUpdate(imagePathToJpg, username, password);
}
public static final FoursquareHttpApiV1 createHttpApi(String domain, String clientVersion,
boolean useOAuth) {
LOG.log(Level.INFO, "Using foursquare.com for requests.");
return new FoursquareHttpApiV1(domain, clientVersion, useOAuth);
}
public static final FoursquareHttpApiV1 createHttpApi(String clientVersion, boolean useOAuth) {
return createHttpApi(FOURSQUARE_API_DOMAIN, clientVersion, useOAuth);
}
public static final String createLeaderboardUrl(String userId, Location location) {
Uri.Builder builder = new Uri.Builder() //
.scheme("http") //
.authority("foursquare.com") //
.appendEncodedPath("/iphone/me") //
.appendQueryParameter("view", "all") //
.appendQueryParameter("scope", "friends") //
.appendQueryParameter("uid", userId);
if (!TextUtils.isEmpty(location.geolat)) {
builder.appendQueryParameter("geolat", location.geolat);
}
if (!TextUtils.isEmpty(location.geolong)) {
builder.appendQueryParameter("geolong", location.geolong);
}
if (!TextUtils.isEmpty(location.geohacc)) {
builder.appendQueryParameter("geohacc", location.geohacc);
}
if (!TextUtils.isEmpty(location.geovacc)) {
builder.appendQueryParameter("geovacc", location.geovacc);
}
return builder.build().toString();
}
/**
* This api is supported in the V1 API documented at:
* http://groups.google.com/group/foursquare-api/web/api-documentation
*/
@interface V1 {
}
/**
* This api call requires a location.
*/
@interface LocationRequired {
}
public static class Location {
String geolat = null;
String geolong = null;
String geohacc = null;
String geovacc = null;
String geoalt = null;
public Location() {
}
public Location(final String geolat, final String geolong, final String geohacc,
final String geovacc, final String geoalt) {
this.geolat = geolat;
this.geolong = geolong;
this.geohacc = geohacc;
this.geovacc = geovacc;
this.geoalt = geovacc;
}
public Location(final String geolat, final String geolong) {
this(geolat, geolong, null, null, null);
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Checkin;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CheckinParser extends AbstractParser<Checkin> {
@Override
public Checkin parse(JSONObject json) throws JSONException {
Checkin obj = new Checkin();
if (json.has("created")) {
obj.setCreated(json.getString("created"));
}
if (json.has("display")) {
obj.setDisplay(json.getString("display"));
}
if (json.has("distance")) {
obj.setDistance(json.getString("distance"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("ismayor")) {
obj.setIsmayor(json.getBoolean("ismayor"));
}
if (json.has("ping")) {
obj.setPing(json.getBoolean("ping"));
}
if (json.has("shout")) {
obj.setShout(json.getString("shout"));
}
if (json.has("user")) {
obj.setUser(new UserParser().parse(json.getJSONObject("user")));
}
if (json.has("venue")) {
obj.setVenue(new VenueParser().parse(json.getJSONObject("venue")));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Special;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class SpecialParser extends AbstractParser<Special> {
@Override
public Special parse(JSONObject json) throws JSONException {
Special obj = new Special();
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("type")) {
obj.setType(json.getString("type"));
}
if (json.has("venue")) {
obj.setVenue(new VenueParser().parse(json.getJSONObject("venue")));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Emails;
import com.joelapenna.foursquare.types.FriendInvitesResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class FriendInvitesResultParser extends AbstractParser<FriendInvitesResult> {
@Override
public FriendInvitesResult parse(JSONObject json) throws JSONException {
FriendInvitesResult obj = new FriendInvitesResult();
if (json.has("users")) {
obj.setContactsOnFoursquare(
new GroupParser(
new UserParser()).parse(json.getJSONArray("users")));
}
if (json.has("emails")) {
Emails emails = new Emails();
if (json.optJSONObject("emails") != null) {
JSONObject emailsAsObject = json.getJSONObject("emails");
emails.add(emailsAsObject.getString("email"));
} else if (json.optJSONArray("emails") != null) {
JSONArray emailsAsArray = json.getJSONArray("emails");
for (int i = 0; i < emailsAsArray.length(); i++) {
emails.add(emailsAsArray.getString(i));
}
}
obj.setContactEmailsOnNotOnFoursquare(emails);
}
if (json.has("invited")) {
Emails emails = new Emails();
JSONArray array = json.getJSONArray("invited");
for (int i = 0; i < array.length(); i++) {
emails.add(array.getString(i));
}
obj.setContactEmailsOnNotOnFoursquareAlreadyInvited(emails);
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Todo;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date September 2, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TodoParser extends AbstractParser<Todo> {
@Override
public Todo parse(JSONObject json) throws JSONException {
Todo obj = new Todo();
if (json.has("created")) {
obj.setCreated(json.getString("created"));
}
if (json.has("tip")) {
obj.setTip(new TipParser().parse(json.getJSONObject("tip")));
}
if (json.has("todoid")) {
obj.setId(json.getString("todoid"));
}
return obj;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Group;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public interface Parser<T extends FoursquareType> {
public abstract T parse(JSONObject json) throws JSONException;
public Group parse(JSONArray array) throws JSONException;
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class StringArrayParser {
public static List<String> parse(JSONArray json) throws JSONException {
List<String> array = new ArrayList<String>();
for (int i = 0, m = json.length(); i < m; i++) {
array.add(json.getString(i));
}
return array;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Stats;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class StatsParser extends AbstractParser<Stats> {
@Override
public Stats parse(JSONObject json) throws JSONException {
Stats obj = new Stats();
if (json.has("beenhere")) {
obj.setBeenhere(new BeenhereParser().parse(json.getJSONObject("beenhere")));
}
if (json.has("checkins")) {
obj.setCheckins(json.getString("checkins"));
}
if (json.has("herenow")) {
obj.setHereNow(json.getString("herenow"));
}
if (json.has("mayor")) {
obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor")));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Settings;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class SettingsParser extends AbstractParser<Settings> {
@Override
public Settings parse(JSONObject json) throws JSONException {
Settings obj = new Settings();
if (json.has("feeds_key")) {
obj.setFeedsKey(json.getString("feeds_key"));
}
if (json.has("get_pings")) {
obj.setGetPings(json.getBoolean("get_pings"));
}
if (json.has("pings")) {
obj.setPings(json.getString("pings"));
}
if (json.has("sendtofacebook")) {
obj.setSendtofacebook(json.getBoolean("sendtofacebook"));
}
if (json.has("sendtotwitter")) {
obj.setSendtotwitter(json.getBoolean("sendtotwitter"));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Badge;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class BadgeParser extends AbstractParser<Badge> {
@Override
public Badge parse(JSONObject json) throws JSONException {
Badge obj = new Badge();
if (json.has("description")) {
obj.setDescription(json.getString("description"));
}
if (json.has("icon")) {
obj.setIcon(json.getString("icon"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("name")) {
obj.setName(json.getString("name"));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Beenhere;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class BeenhereParser extends AbstractParser<Beenhere> {
@Override
public Beenhere parse(JSONObject json) throws JSONException {
Beenhere obj = new Beenhere();
if (json.has("friends")) {
obj.setFriends(json.getBoolean("friends"));
}
if (json.has("me")) {
obj.setMe(json.getBoolean("me"));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Response;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date April 28, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class ResponseParser extends AbstractParser<Response> {
@Override
public Response parse(JSONObject json) throws JSONException {
Response response = new Response();
response.setValue(json.getString("response"));
return response;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Group;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public abstract class AbstractParser<T extends FoursquareType> implements Parser<T> {
/**
* All derived parsers must implement parsing a JSONObject instance of themselves.
*/
public abstract T parse(JSONObject json) throws JSONException;
/**
* Only the GroupParser needs to implement this.
*/
public Group parse(JSONArray array) throws JSONException {
throw new JSONException("Unexpected JSONArray parse type encountered.");
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Tip;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TipParser extends AbstractParser<Tip> {
@Override
public Tip parse(JSONObject json) throws JSONException {
Tip obj = new Tip();
if (json.has("created")) {
obj.setCreated(json.getString("created"));
}
if (json.has("distance")) {
obj.setDistance(json.getString("distance"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("stats")) {
obj.setStats(new TipParser.StatsParser().parse(json.getJSONObject("stats")));
}
if (json.has("status")) {
obj.setStatus(json.getString("status"));
}
if (json.has("text")) {
obj.setText(json.getString("text"));
}
if (json.has("user")) {
obj.setUser(new UserParser().parse(json.getJSONObject("user")));
}
if (json.has("venue")) {
obj.setVenue(new VenueParser().parse(json.getJSONObject("venue")));
}
return obj;
}
public static class StatsParser extends AbstractParser<Tip.Stats> {
@Override
public Tip.Stats parse(JSONObject json) throws JSONException {
Tip.Stats stats = new Tip.Stats();
if (json.has("donecount")) {
stats.setDoneCount(json.getInt("donecount"));
}
if (json.has("todocount")) {
stats.setTodoCount(json.getInt("todocount"));
}
return stats;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Credentials;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CredentialsParser extends AbstractParser<Credentials> {
@Override
public Credentials parse(JSONObject json) throws JSONException {
Credentials obj = new Credentials();
if (json.has("oauth_token")) {
obj.setOauthToken(json.getString("oauth_token"));
}
if (json.has("oauth_token_secret")) {
obj.setOauthTokenSecret(json.getString("oauth_token_secret"));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Data;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class DataParser extends AbstractParser<Data> {
@Override
public Data parse(JSONObject json) throws JSONException {
Data obj = new Data();
if (json.has("cityid")) {
obj.setCityid(json.getString("cityid"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("status")) {
obj.setStatus("1".equals(json.getString("status")));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.City;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CityParser extends AbstractParser<City> {
@Override
public City parse(JSONObject json) throws JSONException {
City obj = new City();
if (json.has("geolat")) {
obj.setGeolat(json.getString("geolat"));
}
if (json.has("geolong")) {
obj.setGeolong(json.getString("geolong"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("name")) {
obj.setName(json.getString("name"));
}
if (json.has("shortname")) {
obj.setShortname(json.getString("shortname"));
}
if (json.has("timezone")) {
obj.setTimezone(json.getString("timezone"));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Score;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class ScoreParser extends AbstractParser<Score> {
@Override
public Score parse(JSONObject json) throws JSONException {
Score obj = new Score();
if (json.has("icon")) {
obj.setIcon(json.getString("icon"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("points")) {
obj.setPoints(json.getString("points"));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Group;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import java.util.logging.Level;
/**
* Reference:
* http://www.json.org/javadoc/org/json/JSONObject.html
* http://www.json.org/javadoc/org/json/JSONArray.html
*
* @author Mark Wyszomierski (markww@gmail.com)
* @param <T>
*/
public class GroupParser extends AbstractParser<Group> {
private Parser<? extends FoursquareType> mSubParser;
public GroupParser(Parser<? extends FoursquareType> subParser) {
mSubParser = subParser;
}
/**
* When we encounter a JSONObject in a GroupParser, we expect one attribute
* named 'type', and then another JSONArray attribute.
*/
public Group<FoursquareType> parse(JSONObject json) throws JSONException {
Group<FoursquareType> group = new Group<FoursquareType>();
Iterator<String> it = (Iterator<String>)json.keys();
while (it.hasNext()) {
String key = it.next();
if (key.equals("type")) {
group.setType(json.getString(key));
} else {
Object obj = json.get(key);
if (obj instanceof JSONArray) {
parse(group, (JSONArray)obj);
} else {
throw new JSONException("Could not parse data.");
}
}
}
return group;
}
/**
* Here we are getting a straight JSONArray and do not expect the 'type' attribute.
*/
@Override
public Group parse(JSONArray array) throws JSONException {
Group<FoursquareType> group = new Group<FoursquareType>();
parse(group, array);
return group;
}
private void parse(Group group, JSONArray array) throws JSONException {
for (int i = 0, m = array.length(); i < m; i++) {
Object element = array.get(i);
FoursquareType item = null;
if (element instanceof JSONArray) {
item = mSubParser.parse((JSONArray)element);
} else {
item = mSubParser.parse((JSONObject)element);
}
group.add(item);
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Types;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TypesParser extends AbstractParser<Types> {
@Override
public Types parse(JSONObject json) throws JSONException {
Types obj = new Types();
if (json.has("type")) {
obj.add(json.getString("type"));
}
return obj;
}
public Types parseAsJSONArray(JSONArray array) throws JSONException {
Types obj = new Types();
for (int i = 0, m = array.length(); i < m; i++) {
obj.add(array.getString(i));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.User;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserParser extends AbstractParser<User> {
@Override
public User parse(JSONObject json) throws JSONException {
User user = new User();
if (json.has("badges")) {
user.setBadges(
new GroupParser(
new BadgeParser()).parse(json.getJSONArray("badges")));
}
if (json.has("badgecount")) {
user.setBadgeCount(json.getInt("badgecount"));
}
if (json.has("checkin")) {
user.setCheckin(new CheckinParser().parse(json.getJSONObject("checkin")));
}
if (json.has("checkincount")) {
user.setCheckinCount(json.getInt("checkincount"));
}
if (json.has("created")) {
user.setCreated(json.getString("created"));
}
if (json.has("email")) {
user.setEmail(json.getString("email"));
}
if (json.has("facebook")) {
user.setFacebook(json.getString("facebook"));
}
if (json.has("firstname")) {
user.setFirstname(json.getString("firstname"));
}
if (json.has("followercount")) {
user.setFollowerCount(json.getInt("followercount"));
}
if (json.has("friendcount")) {
user.setFriendCount(json.getInt("friendcount"));
}
if (json.has("friendsincommon")) {
user.setFriendsInCommon(
new GroupParser(
new UserParser()).parse(json.getJSONArray("friendsincommon")));
}
if (json.has("friendstatus")) {
user.setFriendstatus(json.getString("friendstatus"));
}
if (json.has("gender")) {
user.setGender(json.getString("gender"));
}
if (json.has("hometown")) {
user.setHometown(json.getString("hometown"));
}
if (json.has("id")) {
user.setId(json.getString("id"));
}
if (json.has("lastname")) {
user.setLastname(json.getString("lastname"));
}
if (json.has("mayor")) {
user.setMayorships(
new GroupParser(
new VenueParser()).parse(json.getJSONArray("mayor")));
}
if (json.has("mayorcount")) {
user.setMayorCount(json.getInt("mayorcount"));
}
if (json.has("phone")) {
user.setPhone(json.getString("phone"));
}
if (json.has("photo")) {
user.setPhoto(json.getString("photo"));
}
if (json.has("settings")) {
user.setSettings(new SettingsParser().parse(json.getJSONObject("settings")));
}
if (json.has("tipcount")) {
user.setTipCount(json.getInt("tipcount"));
}
if (json.has("todocount")) {
user.setTodoCount(json.getInt("todocount"));
}
if (json.has("twitter")) {
user.setTwitter(json.getString("twitter"));
}
if (json.has("types")) {
user.setTypes(new TypesParser().parseAsJSONArray(json.getJSONArray("types")));
}
return user;
}
//@Override
//public String getObjectName() {
// return "user";
//}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Rank;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class RankParser extends AbstractParser<Rank> {
@Override
public Rank parse(JSONObject json) throws JSONException {
Rank obj = new Rank();
if (json.has("city")) {
obj.setCity(json.getString("city"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("position")) {
obj.setPosition(json.getString("position"));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Mayor;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class MayorParser extends AbstractParser<Mayor> {
@Override
public Mayor parse(JSONObject json) throws JSONException {
Mayor obj = new Mayor();
if (json.has("checkins")) {
obj.setCheckins(json.getString("checkins"));
}
if (json.has("count")) {
obj.setCount(json.getString("count"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("type")) {
obj.setType(json.getString("type"));
}
if (json.has("user")) {
obj.setUser(new UserParser().parse(json.getJSONObject("user")));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Tags;
import com.joelapenna.foursquare.types.Venue;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class VenueParser extends AbstractParser<Venue> {
@Override
public Venue parse(JSONObject json) throws JSONException {
Venue obj = new Venue();
if (json.has("address")) {
obj.setAddress(json.getString("address"));
}
if (json.has("checkins")) {
obj.setCheckins(
new GroupParser(
new CheckinParser()).parse(json.getJSONArray("checkins")));
}
if (json.has("city")) {
obj.setCity(json.getString("city"));
}
if (json.has("cityid")) {
obj.setCityid(json.getString("cityid"));
}
if (json.has("crossstreet")) {
obj.setCrossstreet(json.getString("crossstreet"));
}
if (json.has("distance")) {
obj.setDistance(json.getString("distance"));
}
if (json.has("geolat")) {
obj.setGeolat(json.getString("geolat"));
}
if (json.has("geolong")) {
obj.setGeolong(json.getString("geolong"));
}
if (json.has("hasTodo")) {
obj.setHasTodo(json.getBoolean("hasTodo"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("name")) {
obj.setName(json.getString("name"));
}
if (json.has("phone")) {
obj.setPhone(json.getString("phone"));
}
if (json.has("primarycategory")) {
obj.setCategory(new CategoryParser().parse(json.getJSONObject("primarycategory")));
}
if (json.has("specials")) {
obj.setSpecials(
new GroupParser(
new SpecialParser()).parse(json.getJSONArray("specials")));
}
if (json.has("state")) {
obj.setState(json.getString("state"));
}
if (json.has("stats")) {
obj.setStats(new StatsParser().parse(json.getJSONObject("stats")));
}
if (json.has("tags")) {
obj.setTags(
new Tags(StringArrayParser.parse(json.getJSONArray("tags"))));
}
if (json.has("tips")) {
obj.setTips(
new GroupParser(
new TipParser()).parse(json.getJSONArray("tips")));
}
if (json.has("todos")) {
obj.setTodos(
new GroupParser(
new TodoParser()).parse(json.getJSONArray("todos")));
}
if (json.has("twitter")) {
obj.setTwitter(json.getString("twitter"));
}
if (json.has("zip")) {
obj.setZip(json.getString("zip"));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.CheckinResult;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CheckinResultParser extends AbstractParser<CheckinResult> {
@Override
public CheckinResult parse(JSONObject json) throws JSONException {
CheckinResult obj = new CheckinResult();
if (json.has("badges")) {
obj.setBadges(
new GroupParser(
new BadgeParser()).parse(json.getJSONArray("badges")));
}
if (json.has("created")) {
obj.setCreated(json.getString("created"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("markup")) {
obj.setMarkup(json.getString("markup"));
}
if (json.has("mayor")) {
obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor")));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("scores")) {
obj.setScoring(
new GroupParser(
new ScoreParser()).parse(json.getJSONArray("scores")));
}
if (json.has("specials")) {
obj.setSpecials(
new GroupParser(
new SpecialParser()).parse(json.getJSONArray("specials")));
}
if (json.has("venue")) {
obj.setVenue(new VenueParser().parse(json.getJSONObject("venue")));
}
return obj;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.parsers.json.CategoryParser;
import com.joelapenna.foursquare.parsers.json.GroupParser;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.util.IconUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CategoryParser extends AbstractParser<Category> {
@Override
public Category parse(JSONObject json) throws JSONException {
Category obj = new Category();
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("fullpathname")) {
obj.setFullPathName(json.getString("fullpathname"));
}
if (json.has("nodename")) {
obj.setNodeName(json.getString("nodename"));
}
if (json.has("iconurl")) {
// TODO: Remove this once api v2 allows icon request.
String iconUrl = json.getString("iconurl");
if (IconUtils.get().getRequestHighDensityIcons()) {
iconUrl = iconUrl.replace(".png", "_64.png");
}
obj.setIconUrl(iconUrl);
}
if (json.has("categories")) {
obj.setChildCategories(
new GroupParser(
new CategoryParser()).parse(json.getJSONArray("categories")));
}
return obj;
}
} | Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.http.AbstractHttpApi;
import com.joelapenna.foursquare.http.HttpApi;
import com.joelapenna.foursquare.http.HttpApiWithBasicAuth;
import com.joelapenna.foursquare.http.HttpApiWithOAuth;
import com.joelapenna.foursquare.parsers.json.CategoryParser;
import com.joelapenna.foursquare.parsers.json.CheckinParser;
import com.joelapenna.foursquare.parsers.json.CheckinResultParser;
import com.joelapenna.foursquare.parsers.json.CityParser;
import com.joelapenna.foursquare.parsers.json.CredentialsParser;
import com.joelapenna.foursquare.parsers.json.FriendInvitesResultParser;
import com.joelapenna.foursquare.parsers.json.GroupParser;
import com.joelapenna.foursquare.parsers.json.ResponseParser;
import com.joelapenna.foursquare.parsers.json.SettingsParser;
import com.joelapenna.foursquare.parsers.json.TipParser;
import com.joelapenna.foursquare.parsers.json.TodoParser;
import com.joelapenna.foursquare.parsers.json.UserParser;
import com.joelapenna.foursquare.parsers.json.VenueParser;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquare.types.City;
import com.joelapenna.foursquare.types.Credentials;
import com.joelapenna.foursquare.types.FriendInvitesResult;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Response;
import com.joelapenna.foursquare.types.Settings;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquare.util.JSONUtils;
import com.joelapenna.foursquared.util.Base64Coder;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
class FoursquareHttpApiV1 {
private static final Logger LOG = Logger
.getLogger(FoursquareHttpApiV1.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.DEBUG;
private static final String DATATYPE = ".json";
private static final String URL_API_AUTHEXCHANGE = "/authexchange";
private static final String URL_API_ADDVENUE = "/addvenue";
private static final String URL_API_ADDTIP = "/addtip";
private static final String URL_API_CITIES = "/cities";
private static final String URL_API_CHECKINS = "/checkins";
private static final String URL_API_CHECKIN = "/checkin";
private static final String URL_API_USER = "/user";
private static final String URL_API_VENUE = "/venue";
private static final String URL_API_VENUES = "/venues";
private static final String URL_API_TIPS = "/tips";
private static final String URL_API_TODOS = "/todos";
private static final String URL_API_FRIEND_REQUESTS = "/friend/requests";
private static final String URL_API_FRIEND_APPROVE = "/friend/approve";
private static final String URL_API_FRIEND_DENY = "/friend/deny";
private static final String URL_API_FRIEND_SENDREQUEST = "/friend/sendrequest";
private static final String URL_API_FRIENDS = "/friends";
private static final String URL_API_FIND_FRIENDS_BY_NAME = "/findfriends/byname";
private static final String URL_API_FIND_FRIENDS_BY_PHONE = "/findfriends/byphone";
private static final String URL_API_FIND_FRIENDS_BY_FACEBOOK = "/findfriends/byfacebook";
private static final String URL_API_FIND_FRIENDS_BY_TWITTER = "/findfriends/bytwitter";
private static final String URL_API_CATEGORIES = "/categories";
private static final String URL_API_HISTORY = "/history";
private static final String URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL = "/findfriends/byphoneoremail";
private static final String URL_API_INVITE_BY_EMAIL = "/invite/byemail";
private static final String URL_API_SETPINGS = "/settings/setpings";
private static final String URL_API_VENUE_FLAG_CLOSED = "/venue/flagclosed";
private static final String URL_API_VENUE_FLAG_MISLOCATED = "/venue/flagmislocated";
private static final String URL_API_VENUE_FLAG_DUPLICATE = "/venue/flagduplicate";
private static final String URL_API_VENUE_PROPOSE_EDIT = "/venue/proposeedit";
private static final String URL_API_USER_UPDATE = "/user/update";
private static final String URL_API_MARK_TODO = "/mark/todo";
private static final String URL_API_MARK_IGNORE = "/mark/ignore";
private static final String URL_API_MARK_DONE = "/mark/done";
private static final String URL_API_UNMARK_TODO = "/unmark/todo";
private static final String URL_API_UNMARK_DONE = "/unmark/done";
private static final String URL_API_TIP_DETAIL = "/tip/detail";
private final DefaultHttpClient mHttpClient = AbstractHttpApi.createHttpClient();
private HttpApi mHttpApi;
private final String mApiBaseUrl;
private final AuthScope mAuthScope;
public FoursquareHttpApiV1(String domain, String clientVersion, boolean useOAuth) {
mApiBaseUrl = "https://" + domain + "/v1";
mAuthScope = new AuthScope(domain, 80);
if (useOAuth) {
mHttpApi = new HttpApiWithOAuth(mHttpClient, clientVersion);
} else {
mHttpApi = new HttpApiWithBasicAuth(mHttpClient, clientVersion);
}
}
void setCredentials(String phone, String password) {
if (phone == null || phone.length() == 0 || password == null || password.length() == 0) {
if (DEBUG) LOG.log(Level.FINE, "Clearing Credentials");
mHttpClient.getCredentialsProvider().clear();
} else {
if (DEBUG) LOG.log(Level.FINE, "Setting Phone/Password: " + phone + "/******");
mHttpClient.getCredentialsProvider().setCredentials(mAuthScope,
new UsernamePasswordCredentials(phone, password));
}
}
public boolean hasCredentials() {
return mHttpClient.getCredentialsProvider().getCredentials(mAuthScope) != null;
}
public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) {
if (DEBUG) {
LOG.log(Level.FINE, "Setting consumer key/secret: " + oAuthConsumerKey + " "
+ oAuthConsumerSecret);
}
((HttpApiWithOAuth) mHttpApi).setOAuthConsumerCredentials(oAuthConsumerKey,
oAuthConsumerSecret);
}
public void setOAuthTokenWithSecret(String token, String secret) {
if (DEBUG) LOG.log(Level.FINE, "Setting oauth token/secret: " + token + " " + secret);
((HttpApiWithOAuth) mHttpApi).setOAuthTokenWithSecret(token, secret);
}
public boolean hasOAuthTokenWithSecret() {
return ((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret();
}
/*
* /authexchange?oauth_consumer_key=d123...a1bffb5&oauth_consumer_secret=fec...
* 18
*/
public Credentials authExchange(String phone, String password) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
if (((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret()) {
throw new IllegalStateException("Cannot do authExchange with OAuthToken already set");
}
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_AUTHEXCHANGE), //
new BasicNameValuePair("fs_username", phone), //
new BasicNameValuePair("fs_password", password));
return (Credentials) mHttpApi.doHttpRequest(httpPost, new CredentialsParser());
}
/*
* /addtip?vid=1234&text=I%20added%20a%20tip&type=todo (type defaults "tip")
*/
Tip addtip(String vid, String text, String type, String geolat, String geolong, String geohacc,
String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDTIP), //
new BasicNameValuePair("vid", vid), //
new BasicNameValuePair("text", text), //
new BasicNameValuePair("type", type), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* @param name the name of the venue
* @param address the address of the venue (e.g., "202 1st Avenue")
* @param crossstreet the cross streets (e.g., "btw Grand & Broome")
* @param city the city name where this venue is
* @param state the state where the city is
* @param zip (optional) the ZIP code for the venue
* @param phone (optional) the phone number for the venue
* @return
* @throws FoursquareException
* @throws FoursquareCredentialsException
* @throws FoursquareError
* @throws IOException
*/
Venue addvenue(String name, String address, String crossstreet, String city, String state,
String zip, String phone, String categoryId, String geolat, String geolong, String geohacc,
String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDVENUE), //
new BasicNameValuePair("name", name), //
new BasicNameValuePair("address", address), //
new BasicNameValuePair("crossstreet", crossstreet), //
new BasicNameValuePair("city", city), //
new BasicNameValuePair("state", state), //
new BasicNameValuePair("zip", zip), //
new BasicNameValuePair("phone", phone), //
new BasicNameValuePair("primarycategoryid", categoryId), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Venue) mHttpApi.doHttpRequest(httpPost, new VenueParser());
}
/*
* /cities
*/
@SuppressWarnings("unchecked")
Group<City> cities() throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CITIES));
return (Group<City>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CityParser()));
}
/*
* /checkins?
*/
@SuppressWarnings("unchecked")
Group<Checkin> checkins(String geolat, String geolong, String geohacc, String geovacc,
String geoalt) throws FoursquareException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CHECKINS), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt));
return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet,
new GroupParser(new CheckinParser()));
}
/*
* /checkin?vid=1234&venue=Noc%20Noc&shout=Come%20here&private=0&twitter=1
*/
CheckinResult checkin(String vid, String venue, String geolat, String geolong, String geohacc,
String geovacc, String geoalt, String shout, boolean isPrivate, boolean tellFollowers,
boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_CHECKIN), //
new BasicNameValuePair("vid", vid), //
new BasicNameValuePair("venue", venue), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("shout", shout), //
new BasicNameValuePair("private", (isPrivate) ? "1" : "0"), //
new BasicNameValuePair("followers", (tellFollowers) ? "1" : "0"), //
new BasicNameValuePair("twitter", (twitter) ? "1" : "0"), //
new BasicNameValuePair("facebook", (facebook) ? "1" : "0"), //
new BasicNameValuePair("markup", "android")); // used only by android for checkin result 'extras'.
return (CheckinResult) mHttpApi.doHttpRequest(httpPost, new CheckinResultParser());
}
/**
* /user?uid=9937
*/
User user(String uid, boolean mayor, boolean badges, boolean stats, String geolat, String geolong,
String geohacc, String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_USER), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("mayor", (mayor) ? "1" : "0"), //
new BasicNameValuePair("badges", (badges) ? "1" : "0"), //
new BasicNameValuePair("stats", (stats) ? "1" : "0"), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (User) mHttpApi.doHttpRequest(httpGet, new UserParser());
}
/**
* /venues?geolat=37.770900&geolong=-122.43698
*/
@SuppressWarnings("unchecked")
Group<Group<Venue>> venues(String geolat, String geolong, String geohacc, String geovacc,
String geoalt, String query, int limit) throws FoursquareException, FoursquareError,
IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUES), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("q", query), //
new BasicNameValuePair("l", String.valueOf(limit)));
return (Group<Group<Venue>>) mHttpApi.doHttpRequest(httpGet, new GroupParser(
new GroupParser(new VenueParser())));
}
/**
* /venue?vid=1234
*/
Venue venue(String vid, String geolat, String geolong, String geohacc, String geovacc,
String geoalt) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUE), //
new BasicNameValuePair("vid", vid), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Venue) mHttpApi.doHttpRequest(httpGet, new VenueParser());
}
/**
* /tips?geolat=37.770900&geolong=-122.436987&l=1
*/
@SuppressWarnings("unchecked")
Group<Tip> tips(String geolat, String geolong, String geohacc, String geovacc,
String geoalt, String uid, String filter, String sort, int limit) throws FoursquareException,
FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIPS), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("filter", filter), //
new BasicNameValuePair("sort", sort), //
new BasicNameValuePair("l", String.valueOf(limit)) //
);
return (Group<Tip>) mHttpApi.doHttpRequest(httpGet, new GroupParser(
new TipParser()));
}
/**
* /todos?geolat=37.770900&geolong=-122.436987&l=1&sort=[recent|nearby]
*/
@SuppressWarnings("unchecked")
Group<Todo> todos(String uid, String geolat, String geolong, String geohacc, String geovacc,
String geoalt, boolean recent, boolean nearby, int limit)
throws FoursquareException, FoursquareError, IOException {
String sort = null;
if (recent) {
sort = "recent";
} else if (nearby) {
sort = "nearby";
}
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TODOS), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("sort", sort), //
new BasicNameValuePair("l", String.valueOf(limit)) //
);
return (Group<Todo>) mHttpApi.doHttpRequest(httpGet, new GroupParser(
new TodoParser()));
}
/*
* /friends?uid=9937
*/
@SuppressWarnings("unchecked")
Group<User> friends(String uid, String geolat, String geolong, String geohacc, String geovacc,
String geoalt) throws FoursquareException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIENDS), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/*
* /friend/requests
*/
@SuppressWarnings("unchecked")
Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIEND_REQUESTS));
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/*
* /friend/approve?uid=9937
*/
User friendApprove(String uid) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_APPROVE), //
new BasicNameValuePair("uid", uid));
return (User) mHttpApi.doHttpRequest(httpPost, new UserParser());
}
/*
* /friend/deny?uid=9937
*/
User friendDeny(String uid) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_DENY), //
new BasicNameValuePair("uid", uid));
return (User) mHttpApi.doHttpRequest(httpPost, new UserParser());
}
/*
* /friend/sendrequest?uid=9937
*/
User friendSendrequest(String uid) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_SENDREQUEST), //
new BasicNameValuePair("uid", uid));
return (User) mHttpApi.doHttpRequest(httpPost, new UserParser());
}
/**
* /findfriends/byname?q=john doe, mary smith
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByName(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_NAME), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/**
* /findfriends/byphone?q=555-5555,555-5556
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByPhone(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser()));
}
/**
* /findfriends/byfacebook?q=friendid,friendid,friendid
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByFacebook(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_FACEBOOK), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser()));
}
/**
* /findfriends/bytwitter?q=yourtwittername
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByTwitter(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_TWITTER), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/**
* /categories
*/
@SuppressWarnings("unchecked")
public Group<Category> categories() throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CATEGORIES));
return (Group<Category>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CategoryParser()));
}
/**
* /history
*/
@SuppressWarnings("unchecked")
public Group<Checkin> history(String limit, String sinceid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_HISTORY),
new BasicNameValuePair("l", limit),
new BasicNameValuePair("sinceid", sinceid));
return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CheckinParser()));
}
/**
* /mark/todo
*/
public Todo markTodo(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), //
new BasicNameValuePair("tid", tid));
return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser());
}
/**
* This is a hacky special case, hopefully the api will be updated in v2 for this.
* /mark/todo
*/
public Todo markTodoVenue(String vid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), //
new BasicNameValuePair("vid", vid));
return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser());
}
/**
* /mark/ignore
*/
public Tip markIgnore(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_IGNORE), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /mark/done
*/
public Tip markDone(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_DONE), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /unmark/todo
*/
public Tip unmarkTodo(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_TODO), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /unmark/done
*/
public Tip unmarkDone(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_DONE), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /tip/detail?tid=1234
*/
public Tip tipDetail(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIP_DETAIL), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpGet, new TipParser());
}
/**
* /findfriends/byphoneoremail?p=comma-sep-list-of-phones&e=comma-sep-list-of-emails
*/
public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL), //
new BasicNameValuePair("p", phones),
new BasicNameValuePair("e", emails));
return (FriendInvitesResult) mHttpApi.doHttpRequest(httpPost, new FriendInvitesResultParser());
}
/**
* /invite/byemail?q=comma-sep-list-of-emails
*/
public Response inviteByEmail(String emails) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_INVITE_BY_EMAIL), //
new BasicNameValuePair("q", emails));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /settings/setpings?self=[on|off]
*/
public Settings setpings(boolean on) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), //
new BasicNameValuePair("self", on ? "on" : "off"));
return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser());
}
/**
* /settings/setpings?uid=userid
*/
public Settings setpings(String userid, boolean on) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), //
new BasicNameValuePair(userid, on ? "on" : "off"));
return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser());
}
/**
* /venue/flagclosed?vid=venueid
*/
public Response flagclosed(String venueId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_CLOSED), //
new BasicNameValuePair("vid", venueId));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /venue/flagmislocated?vid=venueid
*/
public Response flagmislocated(String venueId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_MISLOCATED), //
new BasicNameValuePair("vid", venueId));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /venue/flagduplicate?vid=venueid
*/
public Response flagduplicate(String venueId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_DUPLICATE), //
new BasicNameValuePair("vid", venueId));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /venue/prposeedit?vid=venueid&name=...
*/
public Response proposeedit(String venueId, String name, String address, String crossstreet,
String city, String state, String zip, String phone, String categoryId, String geolat,
String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_PROPOSE_EDIT), //
new BasicNameValuePair("vid", venueId), //
new BasicNameValuePair("name", name), //
new BasicNameValuePair("address", address), //
new BasicNameValuePair("crossstreet", crossstreet), //
new BasicNameValuePair("city", city), //
new BasicNameValuePair("state", state), //
new BasicNameValuePair("zip", zip), //
new BasicNameValuePair("phone", phone), //
new BasicNameValuePair("primarycategoryid", categoryId), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
private String fullUrl(String url) {
return mApiBaseUrl + url + DATATYPE;
}
/**
* /user/update
* Need to bring this method under control like the rest of the api methods. Leaving it
* in this state as authorization will probably switch from basic auth in the near future
* anyway, will have to be updated. Also unlike the other methods, we're sending up data
* which aren't basic name/value pairs.
*/
public User userUpdate(String imagePathToJpg, String username, String password)
throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException {
String BOUNDARY = "------------------319831265358979362846";
String lineEnd = "\r\n";
String twoHyphens = "--";
int maxBufferSize = 8192;
File file = new File(imagePathToJpg);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(fullUrl(URL_API_USER_UPDATE));
HttpURLConnection conn = mHttpApi.createHttpURLConnectionPost(url, BOUNDARY);
conn.setRequestProperty("Authorization", "Basic " + Base64Coder.encodeString(username + ":" + password));
// We are always saving the image to a jpg so we can use .jpg as the extension below.
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + BOUNDARY + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"image,jpeg\";filename=\"" + "image.jpeg" +"\"" + lineEnd);
dos.writeBytes("Content-Type: " + "image/jpeg" + lineEnd);
dos.writeBytes(lineEnd);
int bytesAvailable = fileInputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int totalBytesRead = bytesRead;
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytesRead = totalBytesRead + bytesRead;
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + BOUNDARY + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String responseLine = "";
while ((responseLine = in.readLine()) != null) {
response.append(responseLine);
}
in.close();
try {
return (User)JSONUtils.consume(new UserParser(), response.toString());
} catch (Exception ex) {
throw new FoursquareParseException(
"Error parsing user photo upload response, invalid json.");
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareParseException extends FoursquareException {
private static final long serialVersionUID = 1L;
public FoursquareParseException(String message) {
super(message);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareError extends FoursquareException {
private static final long serialVersionUID = 1L;
public FoursquareError(String message) {
super(message);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareCredentialsException extends FoursquareException {
private static final long serialVersionUID = 1L;
public FoursquareCredentialsException(String message) {
super(message);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareException extends Exception {
private static final long serialVersionUID = 1L;
private String mExtra;
public FoursquareException(String message) {
super(message);
}
public FoursquareException(String message, String extra) {
super(message);
mExtra = extra;
}
public String getExtra() {
return mExtra;
}
}
| 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 |
/**
* 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;
/**
* @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.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 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 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
* 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 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
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.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquare.util.VenueUtils;
import com.joelapenna.foursquared.maps.CheckinGroup;
import com.joelapenna.foursquared.maps.CheckinGroupItemizedOverlay;
import com.joelapenna.foursquared.maps.CheckinGroupItemizedOverlay.CheckinGroupOverlayTapListener;
import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay;
import com.joelapenna.foursquared.util.CheckinTimestampSort;
import com.joelapenna.foursquared.util.GeoUtils;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.widget.MapCalloutView;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Added support for checkingroup items, also stopped recreation
* of overlay group in onResume(). [2010-06-21]
*/
public class FriendsMapActivity extends MapActivity {
public static final String TAG = "FriendsMapActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_CHECKIN_PARCELS = Foursquared.PACKAGE_NAME
+ ".FriendsMapActivity.EXTRA_CHECKIN_PARCELS";
private StateHolder mStateHolder;
private Venue mTappedVenue;
private MapCalloutView mCallout;
private MapView mMapView;
private MapController mMapController;
private List<CheckinGroupItemizedOverlay> mCheckinGroupOverlays;
private MyLocationOverlay mMyLocationOverlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_map_activity);
if (getLastNonConfigurationInstance() != null) {
mStateHolder = (StateHolder) getLastNonConfigurationInstance();
} else {
if (getIntent().hasExtra(EXTRA_CHECKIN_PARCELS)) {
Parcelable[] parcelables = getIntent().getParcelableArrayExtra(EXTRA_CHECKIN_PARCELS);
Group<Checkin> checkins = new Group<Checkin>();
for (int i = 0; i < parcelables.length; i++) {
checkins.add((Checkin)parcelables[i]);
}
mStateHolder = new StateHolder();
mStateHolder.setCheckins(checkins);
} else {
Log.e(TAG, "FriendsMapActivity requires checkin array in intent extras.");
finish();
return;
}
}
initMap();
}
@Override
public void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
if (UiUtil.sdkVersion() > 3) {
mMyLocationOverlay.enableCompass();
}
}
@Override
public void onPause() {
super.onPause();
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
}
private void initMap() {
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mMyLocationOverlay);
loadSearchResults(mStateHolder.getCheckins());
mCallout = (MapCalloutView) findViewById(R.id.map_callout);
mCallout.setVisibility(View.GONE);
mCallout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(FriendsMapActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, mTappedVenue);
startActivity(intent);
}
});
recenterMap();
}
private void loadSearchResults(Group<Checkin> checkins) {
// One CheckinItemizedOverlay per group!
CheckinGroupItemizedOverlay mappableCheckinsOverlay = createMappableCheckinsOverlay(checkins);
mCheckinGroupOverlays = new ArrayList<CheckinGroupItemizedOverlay>();
if (mappableCheckinsOverlay != null) {
mCheckinGroupOverlays.add(mappableCheckinsOverlay);
}
// Only add the list of checkin group overlays if it contains any overlays.
if (mCheckinGroupOverlays.size() > 0) {
mMapView.getOverlays().addAll(mCheckinGroupOverlays);
} else {
Toast.makeText(this, getResources().getString(
R.string.friendsmapactivity_no_checkins), Toast.LENGTH_LONG).show();
}
}
/**
* Create an overlay that contains a specific group's list of mappable
* checkins.
*/
private CheckinGroupItemizedOverlay createMappableCheckinsOverlay(Group<Checkin> group) {
// We want to group checkins by venue. Do max three checkins per venue, a total
// of 100 venues total. We should only also display checkins that are within a
// city radius, and are at most three hours old.
CheckinTimestampSort timestamps = new CheckinTimestampSort();
Map<String, CheckinGroup> checkinMap = new HashMap<String, CheckinGroup>();
for (int i = 0, m = group.size(); i < m; i++) {
Checkin checkin = (Checkin)group.get(i);
Venue venue = checkin.getVenue();
if (VenueUtils.hasValidLocation(venue)) {
// Make sure the venue is within city radius.
try {
int distance = Integer.parseInt(checkin.getDistance());
if (distance > FriendsActivity.CITY_RADIUS_IN_METERS) {
continue;
}
} catch (NumberFormatException ex) {
// Distance was invalid, ignore this checkin.
continue;
}
// Make sure the checkin happened within the last three hours.
try {
Date date = new Date(checkin.getCreated());
if (date.before(timestamps.getBoundaryRecent())) {
continue;
}
} catch (Exception ex) {
// Timestamps was invalid, ignore this checkin.
continue;
}
String venueId = venue.getId();
CheckinGroup cg = checkinMap.get(venueId);
if (cg == null) {
cg = new CheckinGroup();
checkinMap.put(venueId, cg);
}
// Stop appending if we already have three checkins here.
if (cg.getCheckinCount() < 3) {
cg.appendCheckin(checkin);
}
}
// We can't have too many pins on the map.
if (checkinMap.size() > 99) {
break;
}
}
Group<CheckinGroup> mappableCheckins = new Group<CheckinGroup>(checkinMap.values());
if (mappableCheckins.size() > 0) {
CheckinGroupItemizedOverlay mappableCheckinsGroupOverlay = new CheckinGroupItemizedOverlay(
this,
((Foursquared) getApplication()).getRemoteResourceManager(),
this.getResources().getDrawable(R.drawable.pin_checkin_multiple),
mCheckinGroupOverlayTapListener);
mappableCheckinsGroupOverlay.setGroup(mappableCheckins);
return mappableCheckinsGroupOverlay;
} else {
return null;
}
}
private void recenterMap() {
// Previously we'd try to zoom to span, but this gives us odd results a lot of times,
// so falling back to zoom at a fixed level.
GeoPoint center = mMyLocationOverlay.getMyLocation();
if (center != null) {
Log.i(TAG, "Using my location overlay as center point for map centering.");
mMapController.animateTo(center);
mMapController.setZoom(16);
} else {
// Location overlay wasn't ready yet, try using last known geolocation from manager.
Location bestLocation = GeoUtils.getBestLastGeolocation(this);
if (bestLocation != null) {
Log.i(TAG, "Using last known location for map centering.");
mMapController.animateTo(GeoUtils.locationToGeoPoint(bestLocation));
mMapController.setZoom(16);
} else {
// We have no location information at all, so we'll just show the map at a high
// zoom level and the user can zoom in as they wish.
Log.i(TAG, "No location available for map centering.");
mMapController.setZoom(8);
}
}
}
/** Handle taps on one of the pins. */
private CheckinGroupOverlayTapListener mCheckinGroupOverlayTapListener =
new CheckinGroupOverlayTapListener() {
@Override
public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, CheckinGroup cg) {
mTappedVenue = cg.getVenue();
mCallout.setTitle(cg.getVenue().getName());
mCallout.setMessage(cg.getDescription());
mCallout.setVisibility(View.VISIBLE);
mMapController.animateTo(new GeoPoint(cg.getLatE6(), cg.getLonE6()));
}
@Override
public void onTap(GeoPoint p, MapView mapView) {
mCallout.setVisibility(View.GONE);
}
};
@Override
protected boolean isRouteDisplayed() {
return false;
}
private static class StateHolder {
private Group<Checkin> mCheckins;
public StateHolder() {
mCheckins = new Group<Checkin>();
}
public Group<Checkin> getCheckins() {
return mCheckins;
}
public void setCheckins(Group<Checkin> checkins) {
mCheckins = checkins;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquared.util.NotificationsUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* Handles fetching an image from the web, then writes it to a temporary file on
* the sdcard so we can hand it off to a view intent. This activity can be
* styled with a custom transparent-background theme, so that it appears like a
* simple progress dialog to the user over whichever activity launches it,
* instead of two seaparate activities before they finally get to the
* image-viewing activity. The only required intent extra is the URL to download
* the image, the others are optional:
* <ul>
* <li>IMAGE_URL - String, url of the image to download, either jpeg or png.</li>
* <li>CONNECTION_TIMEOUT_IN_SECONDS - int, optional, max timeout wait for
* download, in seconds.</li>
* <li>READ_TIMEOUT_IN_SECONDS - int, optional, max timeout wait for read of
* image, in seconds.</li>
* <li>PROGRESS_BAR_TITLE - String, optional, title of the progress bar during
* download.</li>
* <li>PROGRESS_BAR_MESSAGE - String, optional, message body of the progress bar
* during download.</li>
* </ul>
*
* When the download is complete, the activity will return the path of the
* saved image on disk. The calling activity can then choose to launch an
* intent to view the image.
*
* @date February 25, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class FetchImageForViewIntent extends Activity {
private static final String TAG = "FetchImageForViewIntent";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final String TEMP_FILE_NAME = "tmp_fsq";
public static final String IMAGE_URL = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.IMAGE_URL";
public static final String CONNECTION_TIMEOUT_IN_SECONDS = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.CONNECTION_TIMEOUT_IN_SECONDS";
public static final String READ_TIMEOUT_IN_SECONDS = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.READ_TIMEOUT_IN_SECONDS";
public static final String PROGRESS_BAR_TITLE = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.PROGRESS_BAR_TITLE";
public static final String PROGRESS_BAR_MESSAGE = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.PROGRESS_BAR_MESSAGE";
public static final String LAUNCH_VIEW_INTENT_ON_COMPLETION = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.LAUNCH_VIEW_INTENT_ON_COMPLETION";
public static final String EXTRA_SAVED_IMAGE_PATH_RETURNED = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.EXTRA_SAVED_IMAGE_PATH_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
setContentView(R.layout.fetch_image_for_view_intent_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
String url = null;
if (getIntent().getExtras().containsKey(IMAGE_URL)) {
url = getIntent().getExtras().getString(IMAGE_URL);
} else {
Log.e(TAG, "FetchImageForViewIntent requires intent extras parameter 'IMAGE_URL'.");
finish();
return;
}
if (DEBUG) Log.d(TAG, "Fetching image: " + url);
// Grab the extension of the file that should be present at the end
// of the url. We can do a better job of this, and could even check
// that the extension is of an expected type.
int posdot = url.lastIndexOf(".");
if (posdot < 0) {
Log.e(TAG, "FetchImageForViewIntent requires a url to an image resource with a file extension in its name.");
finish();
return;
}
String progressBarTitle = getIntent().getStringExtra(PROGRESS_BAR_TITLE);
String progressBarMessage = getIntent().getStringExtra(PROGRESS_BAR_MESSAGE);
if (progressBarMessage == null) {
progressBarMessage = "Fetching image...";
}
mStateHolder = new StateHolder();
mStateHolder.setLaunchViewIntentOnCompletion(
getIntent().getBooleanExtra(LAUNCH_VIEW_INTENT_ON_COMPLETION, true));
mStateHolder.startTask(
FetchImageForViewIntent.this,
url,
url.substring(posdot),
progressBarTitle,
progressBarMessage,
getIntent().getIntExtra(CONNECTION_TIMEOUT_IN_SECONDS, 20),
getIntent().getIntExtra(READ_TIMEOUT_IN_SECONDS, 20));
}
}
@Override
public void onResume() {
super.onResume();
if (mStateHolder.getIsRunning()) {
startProgressBar(mStateHolder.getProgressTitle(), mStateHolder.getProgressMessage());
}
}
@Override
public void onPause() {
super.onPause();
stopProgressBar();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void startProgressBar(String title, String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, title, message);
mDlgProgress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dlg) {
mStateHolder.cancel();
finish();
}
});
mDlgProgress.setCancelable(true);
}
mDlgProgress.setTitle(title);
mDlgProgress.setMessage(message);
}
private void stopProgressBar() {
if (mDlgProgress != null && mDlgProgress.isShowing()) {
mDlgProgress.dismiss();
}
mDlgProgress = null;
}
private void onFetchImageTaskComplete(Boolean result, String path, String extension,
Exception ex) {
try {
// If successful, start an intent to view the image.
if (result != null && result.equals(Boolean.TRUE)) {
// If the image can't be loaded or an intent can't be found to
// view it, launchViewIntent() will create a toast with an error
// message.
if (mStateHolder.getLaunchViewIntentOnCompletion()) {
launchViewIntent(path, extension);
} else {
// We'll finish now by handing the save image path back to the
// calling activity.
Intent intent = new Intent();
intent.putExtra(EXTRA_SAVED_IMAGE_PATH_RETURNED, path);
setResult(Activity.RESULT_OK, intent);
}
} else {
NotificationsUtil.ToastReasonForFailure(FetchImageForViewIntent.this, ex);
}
} finally {
// Whether download worked or not, we finish ourselves now. If an
// error occurred, the toast should remain on the calling activity.
mStateHolder.setIsRunning(false);
stopProgressBar();
finish();
}
}
private boolean launchViewIntent(String outputPath, String extension) {
Foursquared foursquared = (Foursquared) getApplication();
if (foursquared.getUseNativeImageViewerForFullScreenImages()) {
// Try to open the file now to create the uri we'll hand to the intent.
Uri uri = null;
try {
File file = new File(outputPath);
uri = Uri.fromFile(file);
} catch (Exception ex) {
Log.e(TAG, "Error opening downloaded image from temp location: ", ex);
Toast.makeText(this, "No application could be found to diplay the full image.",
Toast.LENGTH_SHORT);
return false;
}
// Try to start an intent to view the image. It's possible that the user
// may not have any intents to handle the request.
try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/" + extension);
startActivity(intent);
} catch (Exception ex) {
Log.e(TAG, "Error starting intent to view image: ", ex);
Toast.makeText(this, "There was an error displaying the image.", Toast.LENGTH_SHORT);
return false;
}
} else {
Intent intent = new Intent(this, FullSizeImageActivity.class);
intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_IMAGE_PATH, outputPath);
startActivity(intent);
}
return true;
}
/**
* Handles fetching the image from the net and saving it to disk in a task.
*/
private static class FetchImageTask extends AsyncTask<Void, Void, Boolean> {
private FetchImageForViewIntent mActivity;
private final String mUrl;
private String mExtension;
private final String mOutputPath;
private final int mConnectionTimeoutInSeconds;
private final int mReadTimeoutInSeconds;
private Exception mReason;
public FetchImageTask(FetchImageForViewIntent activity, String url, String extension,
int connectionTimeoutInSeconds, int readTimeoutInSeconds) {
mActivity = activity;
mUrl = url;
mExtension = extension;
mOutputPath = Environment.getExternalStorageDirectory() + "/" + TEMP_FILE_NAME;
mConnectionTimeoutInSeconds = connectionTimeoutInSeconds;
mReadTimeoutInSeconds = readTimeoutInSeconds;
}
public void setActivity(FetchImageForViewIntent activity) {
mActivity = activity;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
saveImage(mUrl, mOutputPath, mConnectionTimeoutInSeconds, mReadTimeoutInSeconds);
return Boolean.TRUE;
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "FetchImageTask: Exception while fetching image.", e);
mReason = e;
}
return Boolean.FALSE;
}
@Override
protected void onPostExecute(Boolean result) {
if (DEBUG) Log.d(TAG, "FetchImageTask: onPostExecute()");
if (mActivity != null) {
mActivity.onFetchImageTaskComplete(result, mOutputPath, mExtension, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onFetchImageTaskComplete(null, null, null,
new FoursquareException("Image download cancelled."));
}
}
}
public static void saveImage(String urlImage, String savePath, int connectionTimeoutInSeconds,
int readTimeoutInSeconds) throws Exception {
URL url = new URL(urlImage);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(connectionTimeoutInSeconds * 1000);
conn.setReadTimeout(readTimeoutInSeconds * 1000);
int contentLength = conn.getContentLength();
InputStream raw = conn.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1) {
break;
}
offset += bytesRead;
}
in.close();
if (offset != contentLength) {
Log.e(TAG, "Error fetching image, only read " + offset + " bytes of " + contentLength
+ " total.");
throw new FoursquareException("Error fetching full image, please try again.");
}
// This will fail if the user has no sdcard present, catch it specifically
// to alert user.
try {
FileOutputStream out = new FileOutputStream(savePath);
out.write(data);
out.flush();
out.close();
} catch (Exception ex) {
Log.e(TAG, "Error saving fetched image to disk.", ex);
throw new FoursquareException("Error opening fetched image, make sure an sdcard is present.");
}
}
/** Maintains state between rotations. */
private static class StateHolder {
FetchImageTask mTaskFetchImage;
boolean mIsRunning;
String mProgressTitle;
String mProgressMessage;
boolean mLaunchViewIntentOnCompletion;
public StateHolder() {
mIsRunning = false;
mLaunchViewIntentOnCompletion = true;
}
public void startTask(FetchImageForViewIntent activity, String url, String extension,
String progressBarTitle, String progressBarMessage, int connectionTimeoutInSeconds,
int readTimeoutInSeconds) {
mIsRunning = true;
mProgressTitle = progressBarTitle;
mProgressMessage = progressBarMessage;
mTaskFetchImage = new FetchImageTask(activity, url, extension,
connectionTimeoutInSeconds, readTimeoutInSeconds);
mTaskFetchImage.execute();
}
public void setActivity(FetchImageForViewIntent activity) {
if (mTaskFetchImage != null) {
mTaskFetchImage.setActivity(activity);
}
}
public void setIsRunning(boolean isRunning) {
mIsRunning = isRunning;
}
public boolean getIsRunning() {
return mIsRunning;
}
public String getProgressTitle() {
return mProgressTitle;
}
public String getProgressMessage() {
return mProgressMessage;
}
public void cancel() {
if (mTaskFetchImage != null) {
mTaskFetchImage.cancel(true);
mIsRunning = false;
}
}
public boolean getLaunchViewIntentOnCompletion() {
return mLaunchViewIntentOnCompletion;
}
public void setLaunchViewIntentOnCompletion(boolean launchViewIntentOnCompletion) {
mLaunchViewIntentOnCompletion = launchViewIntentOnCompletion;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
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.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay;
import com.joelapenna.foursquared.maps.VenueItemizedOverlayWithIcons;
import com.joelapenna.foursquared.maps.VenueItemizedOverlayWithIcons.VenueItemizedOverlayTapListener;
import com.joelapenna.foursquared.util.GeoUtils;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.widget.MapCalloutView;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Takes an array of venues and shows them on a map.
*
* @date June 30, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class NearbyVenuesMapActivity extends MapActivity {
public static final String TAG = "NearbyVenuesMapActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_VENUES = Foursquared.PACKAGE_NAME
+ ".NearbyVenuesMapActivity.INTENT_EXTRA_VENUES";
private StateHolder mStateHolder;
private String mTappedVenueId;
private MapCalloutView mCallout;
private MapView mMapView;
private MapController mMapController;
private ArrayList<VenueItemizedOverlayWithIcons> mVenueGroupOverlays =
new ArrayList<VenueItemizedOverlayWithIcons>();
private MyLocationOverlay mMyLocationOverlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_map_activity);
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
} else {
if (getIntent().hasExtra(INTENT_EXTRA_VENUES)) {
Parcelable[] parcelables = getIntent().getParcelableArrayExtra(
INTENT_EXTRA_VENUES);
Group<Venue> venues = new Group<Venue>();
for (int i = 0; i < parcelables.length; i++) {
venues.add((Venue)parcelables[i]);
}
mStateHolder = new StateHolder(venues);
} else {
Log.e(TAG, TAG + " requires venue array in intent extras.");
finish();
return;
}
}
ensureUi();
}
private void ensureUi() {
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mMyLocationOverlay);
mCallout = (MapCalloutView) findViewById(R.id.map_callout);
mCallout.setVisibility(View.GONE);
mCallout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(NearbyVenuesMapActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, mTappedVenueId);
startActivity(intent);
}
});
// One CheckinItemizedOverlay per group!
VenueItemizedOverlayWithIcons mappableVenuesOverlay = createMappableVenuesOverlay(
mStateHolder.getVenues());
if (mappableVenuesOverlay != null) {
mVenueGroupOverlays.add(mappableVenuesOverlay);
}
if (mVenueGroupOverlays.size() > 0) {
mMapView.getOverlays().addAll(mVenueGroupOverlays);
recenterMap();
} else {
Toast.makeText(this, getResources().getString(
R.string.friendsmapactivity_no_checkins), Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
if (UiUtil.sdkVersion() > 3) {
mMyLocationOverlay.enableCompass();
}
}
@Override
public void onPause() {
super.onPause();
mMyLocationOverlay.disableMyLocation();
if (UiUtil.sdkVersion() > 3) {
mMyLocationOverlay.disableCompass();
}
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
/**
* We can do something more fun here like create an overlay per category, so the user
* can hide parks and show only bars, for example.
*/
private VenueItemizedOverlayWithIcons createMappableVenuesOverlay(Group<Venue> venues) {
Group<Venue> mappableVenues = new Group<Venue>();
for (Venue it : venues) {
mappableVenues.add(it);
}
if (mappableVenues.size() > 0) {
VenueItemizedOverlayWithIcons overlay = new VenueItemizedOverlayWithIcons(
this,
((Foursquared) getApplication()).getRemoteResourceManager(),
getResources().getDrawable(R.drawable.pin_checkin_multiple),
mVenueOverlayTapListener);
overlay.setGroup(mappableVenues);
return overlay;
} else {
return null;
}
}
private void recenterMap() {
// Previously we'd try to zoom to span, but this gives us odd results a lot of times,
// so falling back to zoom at a fixed level.
GeoPoint center = mMyLocationOverlay.getMyLocation();
if (center != null) {
mMapController.animateTo(center);
mMapController.setZoom(14);
} else {
// Location overlay wasn't ready yet, try using last known geolocation from manager.
Location bestLocation = GeoUtils.getBestLastGeolocation(this);
if (bestLocation != null) {
mMapController.animateTo(GeoUtils.locationToGeoPoint(bestLocation));
mMapController.setZoom(14);
} else {
// We have no location information at all, so we'll just show the map at a high
// zoom level and the user can zoom in as they wish.
Venue venue = mStateHolder.getVenues().get(0);
mMapController.animateTo(new GeoPoint(
(int)(Float.valueOf(venue.getGeolat()) * 1E6),
(int)(Float.valueOf(venue.getGeolong()) * 1E6)));
mMapController.setZoom(8);
}
}
}
/**
* Handle taps on one of the pins.
*/
private VenueItemizedOverlayTapListener mVenueOverlayTapListener =
new VenueItemizedOverlayTapListener() {
@Override
public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, Venue venue) {
mTappedVenueId = venue.getId();
mCallout.setTitle(venue.getName());
mCallout.setMessage(venue.getAddress());
mCallout.setVisibility(View.VISIBLE);
mMapController.animateTo(GeoUtils.stringLocationToGeoPoint(
venue.getGeolat(), venue.getGeolong()));
}
@Override
public void onTap(GeoPoint p, MapView mapView) {
mCallout.setVisibility(View.GONE);
}
};
private class StateHolder {
private Group<Venue> mVenues;
public StateHolder(Group<Venue> venues) {
mVenues = venues;
}
public Group<Venue> getVenues() {
return mVenues;
}
}
}
| 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.Category;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Response;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
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.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
/**
* Allows the user to add a new venue. This activity can also be used to submit
* edits to an existing venue. Pass a venue parcelable using the EXTRA_VENUE_TO_EDIT
* key to put the activity into edit mode.
*
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Added support for using this activity to edit existing venues (June 8, 2010).
*/
public class AddVenueActivity extends Activity {
private static final String TAG = "AddVenueActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_VENUE_TO_EDIT = "com.joelapenna.foursquared.VenueParcel";
private static final double MINIMUM_ACCURACY_FOR_ADDRESS = 100.0;
private static final int DIALOG_PICK_CATEGORY = 1;
private static final int DIALOG_ERROR = 2;
private StateHolder mStateHolder;
private EditText mNameEditText;
private EditText mAddressEditText;
private EditText mCrossstreetEditText;
private EditText mCityEditText;
private EditText mStateEditText;
private EditText mZipEditText;
private EditText mPhoneEditText;
private Button mAddOrEditVenueButton;
private LinearLayout mCategoryLayout;
private ImageView mCategoryImageView;
private TextView mCategoryTextView;
private ProgressBar mCategoryProgressBar;
private ProgressDialog mDlgProgress;
private TextWatcher mNameFieldWatcher = 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) {
mAddOrEditVenueButton.setEnabled(canEnableSaveButton());
}
};
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_venue_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
mAddOrEditVenueButton = (Button) findViewById(R.id.addVenueButton);
mNameEditText = (EditText) findViewById(R.id.nameEditText);
mAddressEditText = (EditText) findViewById(R.id.addressEditText);
mCrossstreetEditText = (EditText) findViewById(R.id.crossstreetEditText);
mCityEditText = (EditText) findViewById(R.id.cityEditText);
mStateEditText = (EditText) findViewById(R.id.stateEditText);
mZipEditText = (EditText) findViewById(R.id.zipEditText);
mPhoneEditText = (EditText) findViewById(R.id.phoneEditText);
mCategoryLayout = (LinearLayout) findViewById(R.id.addVenueCategoryLayout);
mCategoryImageView = (ImageView) findViewById(R.id.addVenueCategoryIcon);
mCategoryTextView = (TextView) findViewById(R.id.addVenueCategoryTextView);
mCategoryProgressBar = (ProgressBar) findViewById(R.id.addVenueCategoryProgressBar);
mCategoryLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showDialog(DIALOG_PICK_CATEGORY);
}
});
mCategoryLayout.setEnabled(false);
mAddOrEditVenueButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String name = mNameEditText.getText().toString();
String address = mAddressEditText.getText().toString();
String crossstreet = mCrossstreetEditText.getText().toString();
String city = mCityEditText.getText().toString();
String state = mStateEditText.getText().toString();
String zip = mZipEditText.getText().toString();
String phone = mPhoneEditText.getText().toString();
if (mStateHolder.getVenueBeingEdited() != null) {
if (TextUtils.isEmpty(name)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_name));
return;
} else if (TextUtils.isEmpty(address)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_address));
return;
} else if (TextUtils.isEmpty(city)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_city));
return;
} else if (TextUtils.isEmpty(state)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_state));
return;
}
}
mStateHolder.startTaskAddOrEditVenue(
AddVenueActivity.this,
new String[] {
name,
address,
crossstreet,
city,
state,
zip,
phone,
mStateHolder.getChosenCategory() != null ?
mStateHolder.getChosenCategory().getId() : ""
},
// If editing a venue, pass in its id.
mStateHolder.getVenueBeingEdited() != null ?
mStateHolder.getVenueBeingEdited().getId() : null);
}
});
mNameEditText.addTextChangedListener(mNameFieldWatcher);
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
setFields(mStateHolder.getAddressLookup());
setChosenCategory(mStateHolder.getChosenCategory());
if (mStateHolder.getCategories() != null && mStateHolder.getCategories().size() > 0) {
mCategoryLayout.setEnabled(true);
mCategoryProgressBar.setVisibility(View.GONE);
}
} else {
mStateHolder = new StateHolder();
mStateHolder.startTaskGetCategories(this);
// If passed the venue parcelable, then we are in 'edit' mode.
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EXTRA_VENUE_TO_EDIT)) {
Venue venue = getIntent().getExtras().getParcelable(EXTRA_VENUE_TO_EDIT);
if (venue != null) {
mStateHolder.setVenueBeingEdited(venue);
setFields(venue);
setTitle(getResources().getString(R.string.add_venue_activity_label_edit_venue));
mAddOrEditVenueButton.setText(getResources().getString(
R.string.add_venue_activity_btn_submit_edits));
} else {
Log.e(TAG, "Null venue parcelable supplied at startup, will finish immediately.");
finish();
}
} else {
mStateHolder.startTaskAddressLookup(this);
}
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(true);
if (mStateHolder.getIsRunningTaskAddOrEditVenue()) {
startProgressBar();
}
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates();
stopProgressBar();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void showDialogError(String message) {
mStateHolder.setError(message);
showDialog(DIALOG_ERROR);
}
/**
* Set fields from an address lookup, only used when adding a venue. This is done
* to prepopulate some fields for the user.
*/
private void setFields(AddressLookup addressLookup) {
if (mStateHolder.getVenueBeingEdited() == null &&
addressLookup != null &&
addressLookup.getAddress() != null) {
// Don't fill in the street unless we're reasonably confident we
// know where the user is.
String address = addressLookup.getAddress().getAddressLine(0);
double accuracy = addressLookup.getLocation().getAccuracy();
if (address != null && (accuracy > 0.0 && accuracy < MINIMUM_ACCURACY_FOR_ADDRESS)) {
if (DEBUG) Log.d(TAG, "Accuracy good enough, setting address field.");
mAddressEditText.setText(address);
}
String city = addressLookup.getAddress().getLocality();
if (city != null) {
mCityEditText.setText(city);
}
String state = addressLookup.getAddress().getAdminArea();
if (state != null) {
mStateEditText.setText(state);
}
String zip = addressLookup.getAddress().getPostalCode();
if (zip != null) {
mZipEditText.setText(zip);
}
String phone = addressLookup.getAddress().getPhone();
if (phone != null) {
mPhoneEditText.setText(phone);
}
}
}
/**
* Set fields from an existing venue, this is only used when editing a venue.
*/
private void setFields(Venue venue) {
mNameEditText.setText(venue.getName());
mCrossstreetEditText.setText(venue.getCrossstreet());
mAddressEditText.setText(venue.getAddress());
mCityEditText.setText(venue.getCity());
mStateEditText.setText(venue.getState());
mZipEditText.setText(venue.getZip());
mPhoneEditText.setText(venue.getPhone());
}
private void startProgressBar() {
startProgressBar(
getResources().getString(
mStateHolder.getVenueBeingEdited() == null ?
R.string.add_venue_progress_bar_message_add_venue :
R.string.add_venue_progress_bar_message_edit_venue));
}
private void startProgressBar(String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, null, message);
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
private void onGetCategoriesTaskComplete(Group<Category> categories, Exception ex) {
mStateHolder.setIsRunningTaskGetCategories(false);
try {
// Populate the categories list now.
if (categories != null) {
mStateHolder.setCategories(categories);
mCategoryLayout.setEnabled(true);
mCategoryTextView.setText(getResources().getString(R.string.add_venue_activity_pick_category_label));
mCategoryProgressBar.setVisibility(View.GONE);
// If we are editing a venue, set its category here.
if (mStateHolder.getVenueBeingEdited() != null) {
Venue venue = mStateHolder.getVenueBeingEdited();
if (venue.getCategory() != null) {
setChosenCategory(venue.getCategory());
}
}
} else {
// If error, feed list adapter empty user group.
mStateHolder.setCategories(new Group<Category>());
NotificationsUtil.ToastReasonForFailure(this, ex);
}
} finally {
}
stopIndeterminateProgressBar();
}
private void ooGetAddressLookupTaskComplete(AddressLookup addressLookup, Exception ex) {
mStateHolder.setIsRunningTaskAddressLookup(false);
stopIndeterminateProgressBar();
if (addressLookup != null) {
mStateHolder.setAddressLookup(addressLookup);
setFields(addressLookup);
} else {
// Nothing to do on failure, don't need to report.
}
}
private void onAddOrEditVenueTaskComplete(Venue venue, String venueIdIfEditing, Exception ex) {
mStateHolder.setIsRunningTaskAddOrEditVenue(false);
stopProgressBar();
if (venueIdIfEditing == null) {
if (venue != null) {
// If they added the venue ok, then send them to an activity displaying it
// so they can play around with it.
Intent intent = new Intent(AddVenueActivity.this, VenueActivity.class);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
startActivity(intent);
finish();
} else {
// Error, let them hang out here.
NotificationsUtil.ToastReasonForFailure(this, ex);
}
} else {
if (venue != null) {
// Editing the venue worked ok, just return to caller.
Toast.makeText(this, getResources().getString(
R.string.add_venue_activity_edit_venue_success),
Toast.LENGTH_SHORT).show();
finish();
} else {
// Error, let them hang out here.
NotificationsUtil.ToastReasonForFailure(this, ex);
}
}
}
private void stopIndeterminateProgressBar() {
if (mStateHolder.getIsRunningTaskAddressLookup() == false &&
mStateHolder.getIsRunningTaskGetCategories() == false) {
setProgressBarIndeterminateVisibility(false);
}
}
private static class AddOrEditVenueTask extends AsyncTask<Void, Void, Venue> {
private AddVenueActivity mActivity;
private String[] mParams;
private String mVenueIdIfEditing;
private Exception mReason;
private Foursquared mFoursquared;
private String mErrorMsgForEditVenue;
public AddOrEditVenueTask(AddVenueActivity activity,
String[] params,
String venueIdIfEditing) {
mActivity = activity;
mParams = params;
mVenueIdIfEditing = venueIdIfEditing;
mFoursquared = (Foursquared) activity.getApplication();
mErrorMsgForEditVenue = activity.getResources().getString(
R.string.add_venue_activity_edit_venue_fail);
}
public void setActivity(AddVenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected Venue doInBackground(Void... params) {
try {
Foursquare foursquare = mFoursquared.getFoursquare();
Location location = mFoursquared.getLastKnownLocationOrThrow();
if (mVenueIdIfEditing == null) {
return foursquare.addVenue(
mParams[0], // name
mParams[1], // address
mParams[2], // cross street
mParams[3], // city
mParams[4], // state,
mParams[5], // zip
mParams[6], // phone
mParams[7], // category id
LocationUtils.createFoursquareLocation(location));
} else {
Response response =
foursquare.proposeedit(
mVenueIdIfEditing,
mParams[0], // name
mParams[1], // address
mParams[2], // cross street
mParams[3], // city
mParams[4], // state,
mParams[5], // zip
mParams[6], // phone
mParams[7], // category id
LocationUtils.createFoursquareLocation(location));
if (response != null && response.getValue().equals("ok")) {
// TODO: Come up with a better method than returning an empty venue on success.
return new Venue();
} else {
throw new Exception(mErrorMsgForEditVenue);
}
}
} catch (Exception e) {
Log.e(TAG, "Exception during add or edit venue.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Venue venue) {
if (DEBUG) Log.d(TAG, "onPostExecute()");
if (mActivity != null) {
mActivity.onAddOrEditVenueTaskComplete(venue, mVenueIdIfEditing, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onAddOrEditVenueTaskComplete(null, mVenueIdIfEditing, mReason);
}
}
}
private static class AddressLookupTask extends AsyncTask<Void, Void, AddressLookup> {
private AddVenueActivity mActivity;
private Exception mReason;
public AddressLookupTask(AddVenueActivity activity) {
mActivity = activity;
}
public void setActivity(AddVenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.setProgressBarIndeterminateVisibility(true);
}
@Override
protected AddressLookup doInBackground(Void... params) {
try {
Location location = ((Foursquared)mActivity.getApplication()).getLastKnownLocationOrThrow();
Geocoder geocoder = new Geocoder(mActivity);
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
Log.i(TAG, "Address found: " + addresses.toString());
return new AddressLookup(location, addresses.get(0));
} else {
Log.i(TAG, "No address could be found for current location.");
throw new FoursquareException("No address could be found for the current geolocation.");
}
} catch (Exception ex) {
Log.e(TAG, "Error during address lookup.", ex);
mReason = ex;
}
return null;
}
@Override
protected void onPostExecute(AddressLookup address) {
if (mActivity != null) {
mActivity.ooGetAddressLookupTaskComplete(address, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.ooGetAddressLookupTaskComplete(null, mReason);
}
}
}
private static class GetCategoriesTask extends AsyncTask<Void, Void, Group<Category>> {
private AddVenueActivity mActivity;
private Exception mReason;
public GetCategoriesTask(AddVenueActivity activity) {
mActivity = activity;
}
public void setActivity(AddVenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.setProgressBarIndeterminateVisibility(true);
}
@Override
protected Group<Category> doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.categories();
} catch (Exception e) {
if (DEBUG)
Log.d(TAG, "GetCategoriesTask: Exception doing send friend request.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Category> categories) {
if (DEBUG) Log.d(TAG, "GetCategoriesTask: onPostExecute()");
if (mActivity != null) {
mActivity.onGetCategoriesTaskComplete(categories, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onGetCategoriesTaskComplete(null,
new Exception("Get categories task request cancelled."));
}
}
}
private static class StateHolder {
private AddressLookupTask mTaskGetAddress;
private AddressLookup mAddressLookup;
private boolean mIsRunningTaskAddressLookup;
private GetCategoriesTask mTaskGetCategories;
private Group<Category> mCategories;
private boolean mIsRunningTaskGetCategories;
private AddOrEditVenueTask mTaskAddOrEditVenue;
private boolean mIsRunningTaskAddOrEditVenue;
private Category mChosenCategory;
private Venue mVenueBeingEdited;
private String mError;
public StateHolder() {
mCategories = new Group<Category>();
mIsRunningTaskAddressLookup = false;
mIsRunningTaskGetCategories = false;
mIsRunningTaskAddOrEditVenue = false;
mVenueBeingEdited = null;
}
public void setCategories(Group<Category> categories) {
mCategories = categories;
}
public void setAddressLookup(AddressLookup addressLookup) {
mAddressLookup = addressLookup;
}
public Group<Category> getCategories() {
return mCategories;
}
public AddressLookup getAddressLookup() {
return mAddressLookup;
}
public Venue getVenueBeingEdited() {
return mVenueBeingEdited;
}
public void setVenueBeingEdited(Venue venue) {
mVenueBeingEdited = venue;
}
public void startTaskGetCategories(AddVenueActivity activity) {
mIsRunningTaskGetCategories = true;
mTaskGetCategories = new GetCategoriesTask(activity);
mTaskGetCategories.execute();
}
public void startTaskAddressLookup(AddVenueActivity activity) {
mIsRunningTaskAddressLookup = true;
mTaskGetAddress = new AddressLookupTask(activity);
mTaskGetAddress.execute();
}
public void startTaskAddOrEditVenue(AddVenueActivity activity, String[] params,
String venueIdIfEditing) {
mIsRunningTaskAddOrEditVenue = true;
mTaskAddOrEditVenue = new AddOrEditVenueTask(activity, params, venueIdIfEditing);
mTaskAddOrEditVenue.execute();
}
public void setActivity(AddVenueActivity activity) {
if (mTaskGetCategories != null) {
mTaskGetCategories.setActivity(activity);
}
if (mTaskGetAddress != null) {
mTaskGetAddress.setActivity(activity);
}
if (mTaskAddOrEditVenue != null) {
mTaskAddOrEditVenue.setActivity(activity);
}
}
public void setIsRunningTaskAddressLookup(boolean isRunning) {
mIsRunningTaskAddressLookup = isRunning;
}
public void setIsRunningTaskGetCategories(boolean isRunning) {
mIsRunningTaskGetCategories = isRunning;
}
public void setIsRunningTaskAddOrEditVenue(boolean isRunning) {
mIsRunningTaskAddOrEditVenue = isRunning;
}
public boolean getIsRunningTaskAddressLookup() {
return mIsRunningTaskAddressLookup;
}
public boolean getIsRunningTaskGetCategories() {
return mIsRunningTaskGetCategories;
}
public boolean getIsRunningTaskAddOrEditVenue() {
return mIsRunningTaskAddOrEditVenue;
}
public Category getChosenCategory() {
return mChosenCategory;
}
public void setChosenCategory(Category category) {
mChosenCategory = category;
}
public String getError() {
return mError;
}
public void setError(String error) {
mError = error;
}
}
private static class AddressLookup {
private Location mLocation;
private Address mAddress;
public AddressLookup(Location location, Address address) {
mLocation = location;
mAddress = address;
}
public Location getLocation() {
return mLocation;
}
public Address getAddress() {
return mAddress;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_PICK_CATEGORY:
// 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.
CategoryPickerDialog dlg = new CategoryPickerDialog(
this,
mStateHolder.getCategories(),
((Foursquared)getApplication()));
dlg.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
CategoryPickerDialog dlg = (CategoryPickerDialog)dialog;
setChosenCategory(dlg.getChosenCategory());
removeDialog(DIALOG_PICK_CATEGORY);
}
});
return dlg;
case DIALOG_ERROR:
AlertDialog dlgInfo = new AlertDialog.Builder(this)
.setIcon(0)
.setTitle(getResources().getString(R.string.add_venue_progress_bar_title_edit_venue))
.setMessage(mStateHolder.getError()).create();
dlgInfo.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
removeDialog(DIALOG_ERROR);
}
});
return dlgInfo;
}
return null;
}
private void setChosenCategory(Category category) {
if (category == null) {
mCategoryTextView.setText(getResources().getString(
R.string.add_venue_activity_pick_category_label));
return;
}
try {
Bitmap bitmap = BitmapFactory.decodeStream(
((Foursquared)getApplication()).getRemoteResourceManager().getInputStream(
Uri.parse(category.getIconUrl())));
mCategoryImageView.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.e(TAG, "Error loading category icon.", e);
}
mCategoryTextView.setText(category.getNodeName());
// Record the chosen category.
mStateHolder.setChosenCategory(category);
if (canEnableSaveButton()) {
mAddOrEditVenueButton.setEnabled(canEnableSaveButton());
}
}
private boolean canEnableSaveButton() {
return mNameEditText.getText().length() > 0;
}
}
| 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.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 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Mayor;
import com.joelapenna.foursquare.types.Stats;
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.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.UserUtils;
import com.joelapenna.foursquared.util.VenueUtils;
import com.joelapenna.foursquared.widget.PhotoStrip;
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.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* We may be given a pre-fetched venue ready to display, or we might also get just
* a venue ID. If we only get a venue ID, then we need to fetch it immediately from
* the API.
*
* The activity will set an intent result in EXTRA_VENUE_RETURNED if the venue status
* changes as a result of a user modifying todos at the venue. Parent activities can
* check the returned venue to see if this status has changed to update their UI.
* For example, the NearbyVenues activity wants to show the todo corner png if the
* venue has a todo.
*
* The result will also be set if the venue is fully fetched if originally given only
* a venue id or partial venue object. This way the parent can also cache the full venue
* object for next time they want to display this venue activity.
*
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Replaced shout activity with CheckinGatherInfoActivity (3/10/2010).
* -Redesign from tabbed layout (9/15/2010).
*/
public class VenueActivity extends Activity {
private static final String TAG = "VenueActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int MENU_TIP_ADD = 1;
private static final int MENU_TODO_ADD = 2;
private static final int MENU_EDIT_VENUE = 3;
private static final int MENU_CALL = 4;
private static final int MENU_SHARE = 5;
private static final int RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE = 1;
private static final int RESULT_CODE_ACTIVITY_ADD_TIP = 2;
private static final int RESULT_CODE_ACTIVITY_ADD_TODO = 3;
private static final int RESULT_CODE_ACTIVITY_TIP = 4;
private static final int RESULT_CODE_ACTIVITY_TIPS = 5;
private static final int RESULT_CODE_ACTIVITY_TODO = 6;
private static final int RESULT_CODE_ACTIVITY_TODOS = 7;
public static final String INTENT_EXTRA_VENUE_ID = Foursquared.PACKAGE_NAME
+ ".VenueActivity.INTENT_EXTRA_VENUE_ID";
public static final String INTENT_EXTRA_VENUE_PARTIAL = Foursquared.PACKAGE_NAME
+ ".VenueActivity.INTENT_EXTRA_VENUE_PARTIAL";
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".VenueActivity.INTENT_EXTRA_VENUE";
public static final String EXTRA_VENUE_RETURNED = Foursquared.PACKAGE_NAME
+ ".VenueActivity.EXTRA_VENUE_RETURNED";
private StateHolder mStateHolder;
private Handler mHandler;
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
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);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.venue_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
mHandler = new Handler();
StateHolder holder = (StateHolder) getLastNonConfigurationInstance();
if (holder != null) {
mStateHolder = holder;
mStateHolder.setActivityForTasks(this);
prepareResultIntent();
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_FULL);
mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE));
} else if (getIntent().hasExtra(INTENT_EXTRA_VENUE_PARTIAL)) {
mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_PARTIAL);
mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE_PARTIAL));
mStateHolder.startTaskVenue(this);
} else if (getIntent().hasExtra(INTENT_EXTRA_VENUE_ID)) {
mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_ID);
mStateHolder.setVenueId(getIntent().getStringExtra(INTENT_EXTRA_VENUE_ID));
mStateHolder.startTaskVenue(this);
} else {
Log.e(TAG, "VenueActivity must be given a venue id or a venue parcel as intent extras.");
finish();
return;
}
}
mRrm = ((Foursquared) getApplication()).getRemoteResourceManager();
mResourcesObserver = new RemoteResourceManagerObserver();
mRrm.addObserver(mResourcesObserver);
ensureUi();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
mHandler.removeCallbacks(mRunnableMayorPhoto);
if (mRrm != null) {
mRrm.deleteObserver(mResourcesObserver);
}
}
@Override
public void onResume() {
super.onResume();
ensureUiCheckinButton();
// TODO: ensure mayor photo.
}
private void ensureUi() {
TextView tvVenueTitle = (TextView)findViewById(R.id.venueActivityName);
TextView tvVenueAddress = (TextView)findViewById(R.id.venueActivityAddress);
LinearLayout progress = (LinearLayout)findViewById(R.id.venueActivityDetailsProgress);
View viewMayor = findViewById(R.id.venueActivityMayor);
TextView tvMayorTitle = (TextView)findViewById(R.id.venueActivityMayorName);
TextView tvMayorText = (TextView)findViewById(R.id.venueActivityMayorText);
ImageView ivMayorPhoto = (ImageView)findViewById(R.id.venueActivityMayorPhoto);
ImageView ivMayorChevron = (ImageView)findViewById(R.id.venueActivityMayorChevron);
View viewCheckins = findViewById(R.id.venueActivityCheckins);
TextView tvPeopleText = (TextView)findViewById(R.id.venueActivityPeopleText);
PhotoStrip psPeoplePhotos = (PhotoStrip)findViewById(R.id.venueActivityPeoplePhotos);
View viewTips = findViewById(R.id.venueActivityTips);
TextView tvTipsText = (TextView)findViewById(R.id.venueActivityTipsText);
TextView tvTipsTextExtra = (TextView)findViewById(R.id.venueActivityTipsExtra);
ImageView ivTipsChevron = (ImageView)findViewById(R.id.venueActivityTipsChevron);
View viewMoreInfo = findViewById(R.id.venueActivityMoreInfo);
TextView tvMoreInfoText = (TextView)findViewById(R.id.venueActivityMoreTitle);
Venue venue = mStateHolder.getVenue();
if (mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_FULL ||
mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_PARTIAL) {
tvVenueTitle.setText(venue.getName());
tvVenueAddress.setText(StringFormatters.getVenueLocationFull(venue));
ensureUiCheckinButton();
if (mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_FULL) {
Stats stats = venue.getStats();
Mayor mayor = stats != null ? stats.getMayor() : null;
if (mayor != null) {
tvMayorTitle.setText(StringFormatters.getUserFullName(mayor.getUser()));
tvMayorText.setText(getResources().getString(R.string.venue_activity_mayor_text));
String photoUrl = mayor.getUser().getPhoto();
Uri uriPhoto = Uri.parse(photoUrl);
if (mRrm.exists(uriPhoto)) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(photoUrl)));
ivMayorPhoto.setImageBitmap(bitmap);
} catch (IOException e) {
}
} else {
ivMayorPhoto.setImageResource(UserUtils.getDrawableByGenderForUserThumbnail(mayor.getUser()));
ivMayorPhoto.setTag(photoUrl);
mRrm.request(uriPhoto);
}
ivMayorChevron.setVisibility(View.VISIBLE);
setClickHandlerMayor(viewMayor);
} else {
tvMayorTitle.setText(getResources().getString(R.string.venue_activity_mayor_name_none));
tvMayorText.setText(getResources().getString(R.string.venue_activity_mayor_text_none));
ivMayorChevron.setVisibility(View.INVISIBLE);
}
viewMayor.setVisibility(View.VISIBLE);
if (venue.getCheckins() != null && venue.getCheckins().size() > 0) {
int friendCount = getFriendCountAtVenue();
int rest = venue.getCheckins().size() - friendCount;
if (friendCount > 0 && rest == 0) {
// N friends are here
tvPeopleText.setText(getResources().getString(
friendCount == 1 ?
R.string.venue_activity_people_count_friend_single :
R.string.venue_activity_people_count_friend_plural,
friendCount));
} else if (friendCount > 0 && rest > 0) {
// N friends are here with N other people
if (friendCount == 1 && rest == 1) {
tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_single_single,
friendCount, rest));
} else if (friendCount == 1 && rest > 1) {
tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_single_plural,
friendCount, rest));
} else if (friendCount > 1 && rest == 1) {
tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_plural_single,
friendCount, rest));
} else {
tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_plural_plural,
friendCount, rest));
}
} else {
// N people are here
tvPeopleText.setText(getResources().getString(
venue.getCheckins().size() == 1 ?
R.string.venue_activity_people_count_single :
R.string.venue_activity_people_count_plural,
venue.getCheckins().size()));
}
psPeoplePhotos.setCheckinsAndRemoteResourcesManager(venue.getCheckins(), mRrm);
viewCheckins.setVisibility(View.VISIBLE);
setClickHandlerCheckins(viewCheckins);
} else {
viewCheckins.setVisibility(View.GONE);
}
if (venue.getTips() != null && venue.getTips().size() > 0) {
int tipCountFriends = getTipCountFriendsAtVenue();
if (tipCountFriends > 0) {
tvTipsText.setText(
getString(tipCountFriends == 1 ?
R.string.venue_activity_tip_count_friend_single :
R.string.venue_activity_tip_count_friend_plural,
tipCountFriends));
int rest = venue.getTips().size() - tipCountFriends;
if (rest > 0) {
tvTipsTextExtra.setText(
getString(R.string.venue_activity_tip_count_other_people, rest));
tvTipsTextExtra.setVisibility(View.VISIBLE);
}
} else {
tvTipsText.setText(
getString(venue.getTips().size() == 1 ?
R.string.venue_activity_tip_count_single :
R.string.venue_activity_tip_count_plural,
venue.getTips().size()));
tvTipsTextExtra.setVisibility(View.GONE);
}
ivTipsChevron.setVisibility(View.VISIBLE);
setClickHandlerTips(viewTips);
} else {
tvTipsText.setText(getResources().getString(R.string.venue_activity_tip_count_none));
tvTipsTextExtra.setVisibility(View.GONE);
ivTipsChevron.setVisibility(View.INVISIBLE);
}
viewTips.setVisibility(View.VISIBLE);
if (tvTipsTextExtra.getVisibility() != View.VISIBLE) {
tvTipsText.setPadding(tvTipsText.getPaddingLeft(), tvMoreInfoText.getPaddingTop(),
tvTipsText.getPaddingRight(), tvMoreInfoText.getPaddingBottom());
}
viewMoreInfo.setVisibility(View.VISIBLE);
setClickHandlerMoreInfo(viewMoreInfo);
progress.setVisibility(View.GONE);
}
}
ensureUiTodosHere();
ImageView ivSpecialHere = (ImageView)findViewById(R.id.venueActivitySpecialHere);
if (VenueUtils.getSpecialHere(venue)) {
ivSpecialHere.setVisibility(View.VISIBLE);
ivSpecialHere.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showWebViewForSpecial();
}
});
} else {
ivSpecialHere.setVisibility(View.GONE);
}
}
private void ensureUiCheckinButton() {
Button btnCheckin = (Button)findViewById(R.id.venueActivityButtonCheckin);
if (mStateHolder.getCheckedInHere()) {
btnCheckin.setEnabled(false);
} else {
if (mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_ID) {
btnCheckin.setEnabled(false);
} else {
btnCheckin.setEnabled(true);
btnCheckin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(
VenueActivity.this);
if (settings.getBoolean(Preferences.PREFERENCE_IMMEDIATE_CHECKIN, false)) {
startCheckinQuick();
} else {
startCheckin();
}
}
});
}
}
}
private void ensureUiTipAdded() {
Venue venue = mStateHolder.getVenue();
TextView tvTipsText = (TextView)findViewById(R.id.venueActivityTipsText);
ImageView ivTipsChevron = (ImageView)findViewById(R.id.venueActivityTipsChevron);
if (venue.getTips().size() == 1) {
tvTipsText.setText(getResources().getString(
R.string.venue_activity_tip_count_single, venue.getTips().size()));
} else {
tvTipsText.setText(getResources().getString(
R.string.venue_activity_tip_count_plural, venue.getTips().size()));
}
ivTipsChevron.setVisibility(View.VISIBLE);
}
private void ensureUiTodosHere() {
Venue venue = mStateHolder.getVenue();
RelativeLayout rlTodoHere = (RelativeLayout)findViewById(R.id.venueActivityTodoHere);
if (venue != null && venue.getHasTodo()) {
rlTodoHere.setVisibility(View.VISIBLE);
rlTodoHere.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showTodoHereActivity();
}
});
} else {
rlTodoHere.setVisibility(View.GONE);
}
}
private void setClickHandlerMayor(View view) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(VenueActivity.this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL,
mStateHolder.getVenue().getStats().getMayor().getUser());
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
startActivity(intent);
}
});
}
private void setClickHandlerCheckins(View view) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(VenueActivity.this, VenueCheckinsActivity.class);
intent.putExtra(VenueCheckinsActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivity(intent);
}
});
}
private void setClickHandlerTips(View view) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = null;
if (mStateHolder.getVenue().getTips().size() == 1) {
Venue venue = new Venue();
venue.setName(mStateHolder.getVenue().getName());
venue.setAddress(mStateHolder.getVenue().getAddress());
venue.setCrossstreet(mStateHolder.getVenue().getCrossstreet());
Tip tip = mStateHolder.getVenue().getTips().get(0);
tip.setVenue(venue);
intent = new Intent(VenueActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip);
intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false);
startActivityForResult(intent, RESULT_CODE_ACTIVITY_TIP);
} else {
intent = new Intent(VenueActivity.this, VenueTipsActivity.class);
intent.putExtra(VenueTipsActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivityForResult(intent, RESULT_CODE_ACTIVITY_TIPS);
}
}
});
}
private void setClickHandlerMoreInfo(View view) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(VenueActivity.this, VenueMapActivity.class);
intent.putExtra(VenueMapActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivity(intent);
}
});
}
private void prepareResultIntent() {
Venue venue = mStateHolder.getVenue();
Intent intent = new Intent();
if (venue != null) {
intent.putExtra(EXTRA_VENUE_RETURNED, venue);
}
setResult(Activity.RESULT_OK, intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_TIP_ADD, 1, R.string.venue_activity_menu_add_tip).setIcon(
R.drawable.ic_menu_venue_leave_tip);
menu.add(Menu.NONE, MENU_TODO_ADD, 2, R.string.venue_activity_menu_add_todo).setIcon(
R.drawable.ic_menu_venue_add_todo);
menu.add(Menu.NONE, MENU_EDIT_VENUE, 3, R.string.venue_activity_menu_flag).setIcon(
R.drawable.ic_menu_venue_flag);
menu.add(Menu.NONE, MENU_CALL, 4, R.string.venue_activity_menu_call).setIcon(
R.drawable.ic_menu_venue_contact);
menu.add(Menu.NONE, MENU_SHARE, 5, R.string.venue_activity_menu_share).setIcon(
R.drawable.ic_menu_venue_share);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean callEnabled = mStateHolder.getVenue() != null
&& !TextUtils.isEmpty(mStateHolder.getVenue().getPhone());
menu.findItem(MENU_CALL).setEnabled(callEnabled);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_TIP_ADD:
Intent intentTip = new Intent(VenueActivity.this, AddTipActivity.class);
intentTip.putExtra(AddTipActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivityForResult(intentTip, RESULT_CODE_ACTIVITY_ADD_TIP);
return true;
case MENU_TODO_ADD:
Intent intentTodo = new Intent(VenueActivity.this, AddTodoActivity.class);
intentTodo.putExtra(AddTodoActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivityForResult(intentTodo, RESULT_CODE_ACTIVITY_ADD_TODO);
return true;
case MENU_EDIT_VENUE:
Intent intentEditVenue = new Intent(this, EditVenueOptionsActivity.class);
intentEditVenue.putExtra(
EditVenueOptionsActivity.EXTRA_VENUE_PARCELABLE, mStateHolder.getVenue());
startActivity(intentEditVenue);
return true;
case MENU_CALL:
try {
Intent dial = new Intent();
dial.setAction(Intent.ACTION_DIAL);
dial.setData(Uri.parse("tel:" + mStateHolder.getVenue().getPhone()));
startActivity(dial);
} catch (Exception ex) {
Log.e(TAG, "Error starting phone dialer intent.", ex);
Toast.makeText(this, "Sorry, we couldn't find any app to place a phone call!",
Toast.LENGTH_SHORT).show();
}
return true;
case MENU_SHARE:
Intent intentShare = new Intent(this, VenueShareActivity.class);
intentShare.putExtra(VenueShareActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivity(intentShare);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTasks(null);
return mStateHolder;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE:
if (resultCode == Activity.RESULT_OK) {
mStateHolder.setCheckedInHere(true);
ensureUiCheckinButton();
}
break;
case RESULT_CODE_ACTIVITY_ADD_TIP:
if (resultCode == Activity.RESULT_OK) {
Tip tip = data.getParcelableExtra(AddTipActivity.EXTRA_TIP_RETURNED);
VenueUtils.addTip(mStateHolder.getVenue(), tip);
ensureUiTipAdded();
prepareResultIntent();
Toast.makeText(this, getResources().getString(R.string.venue_activity_tip_added_ok),
Toast.LENGTH_SHORT).show();
}
break;
case RESULT_CODE_ACTIVITY_ADD_TODO:
if (resultCode == Activity.RESULT_OK) {
Todo todo = data.getParcelableExtra(AddTodoActivity.EXTRA_TODO_RETURNED);
VenueUtils.addTodo(mStateHolder.getVenue(), todo.getTip(), todo);
ensureUiTodosHere();
prepareResultIntent();
Toast.makeText(this, getResources().getString(R.string.venue_activity_todo_added_ok),
Toast.LENGTH_SHORT).show();
}
break;
case RESULT_CODE_ACTIVITY_TIP:
case RESULT_CODE_ACTIVITY_TODO:
if (resultCode == Activity.RESULT_OK && 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;
VenueUtils.handleTipChange(mStateHolder.getVenue(), tip, todo);
ensureUiTodosHere();
prepareResultIntent();
}
break;
case RESULT_CODE_ACTIVITY_TIPS:
if (resultCode == Activity.RESULT_OK && data.hasExtra(VenueTipsActivity.INTENT_EXTRA_RETURN_VENUE)) {
Venue venue = (Venue)data.getParcelableExtra(VenueTipsActivity.INTENT_EXTRA_RETURN_VENUE);
VenueUtils.replaceTipsAndTodos(mStateHolder.getVenue(), venue);
ensureUiTodosHere();
prepareResultIntent();
}
break;
case RESULT_CODE_ACTIVITY_TODOS:
if (resultCode == Activity.RESULT_OK && data.hasExtra(VenueTodosActivity.INTENT_EXTRA_RETURN_VENUE)) {
Venue venue = (Venue)data.getParcelableExtra(VenueTodosActivity.INTENT_EXTRA_RETURN_VENUE);
VenueUtils.replaceTipsAndTodos(mStateHolder.getVenue(), venue);
ensureUiTodosHere();
prepareResultIntent();
}
break;
}
}
private void startCheckin() {
Intent intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class);
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_CHECKIN, true);
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.getVenue().getId());
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_NAME, mStateHolder.getVenue().getName());
startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE);
}
private void startCheckinQuick() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean tellFriends = settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, true);
boolean tellTwitter = settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, false);
boolean tellFacebook = settings.getBoolean(Preferences.PREFERENCE_FACEBOOK_CHECKIN, false);
Intent intent = new Intent(VenueActivity.this, CheckinExecuteActivity.class);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.getVenue().getId());
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_SHOUT, "");
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FRIENDS, tellFriends);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_TWITTER, tellTwitter);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK, tellFacebook);
startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE);
}
private void showWebViewForSpecial() {
Intent intent = new Intent(this, SpecialWebViewActivity.class);
intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_USERNAME,
PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_LOGIN, ""));
intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_PASSWORD,
PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_PASSWORD, ""));
intent.putExtra(SpecialWebViewActivity.EXTRA_SPECIAL_ID,
mStateHolder.getVenue().getSpecials().get(0).getId());
startActivity(intent);
}
private void showTodoHereActivity() {
Venue venue = new Venue();
venue.setName(mStateHolder.getVenue().getName());
venue.setAddress(mStateHolder.getVenue().getAddress());
venue.setCrossstreet(mStateHolder.getVenue().getCrossstreet());
Group<Todo> todos = mStateHolder.getVenue().getTodos();
for (Todo it : todos) {
it.getTip().setVenue(venue);
}
if (todos.size() == 1) {
Todo todo = (Todo) todos.get(0);
Intent intent = new Intent(VenueActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, todo.getTip());
intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false);
startActivityForResult(intent, RESULT_CODE_ACTIVITY_TODO);
} else if (todos.size() > 1) {
Intent intent = new Intent(VenueActivity.this, VenueTodosActivity.class);
intent.putExtra(VenueTodosActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivityForResult(intent, RESULT_CODE_ACTIVITY_TODOS);
}
}
private int getFriendCountAtVenue() {
int count = 0;
Venue venue = mStateHolder.getVenue();
if (venue.getCheckins() != null) {
for (Checkin it : venue.getCheckins()) {
User user = it.getUser();
if (UserUtils.isFriend(user)) {
count++;
}
}
}
return count;
}
private int getTipCountFriendsAtVenue() {
int count = 0;
Venue venue = mStateHolder.getVenue();
if (venue.getTips() != null) {
for (Tip it : venue.getTips()) {
User user = it.getUser();
if (UserUtils.isFriend(user)) {
count++;
}
}
}
return count;
}
private static class TaskVenue extends AsyncTask<String, Void, Venue> {
private VenueActivity mActivity;
private Exception mReason;
public TaskVenue(VenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
}
@Override
protected Venue doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared)mActivity.getApplication();
return foursquared.getFoursquare().venue(
params[0],
LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
} catch (Exception e) {
Log.e(TAG, "Error getting venue details.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Venue venue) {
if (mActivity != null) {
mActivity.mStateHolder.setIsRunningTaskVenue(false);
if (venue != null) {
mActivity.mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_FULL);
mActivity.mStateHolder.setVenue(venue);
mActivity.prepareResultIntent();
mActivity.ensureUi();
} else {
NotificationsUtil.ToastReasonForFailure(mActivity, mReason);
mActivity.finish();
}
}
}
@Override
protected void onCancelled() {
}
public void setActivity(VenueActivity activity) {
mActivity = activity;
}
}
private static final class StateHolder {
private Venue mVenue;
private String mVenueId;
private boolean mCheckedInHere;
private TaskVenue mTaskVenue;
private boolean mIsRunningTaskVenue;
private int mLoadType;
public static final int LOAD_TYPE_VENUE_ID = 0;
public static final int LOAD_TYPE_VENUE_PARTIAL = 1;
public static final int LOAD_TYPE_VENUE_FULL = 2;
public StateHolder() {
mIsRunningTaskVenue = false;
}
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
}
public void setVenueId(String venueId) {
mVenueId = venueId;
}
public boolean getCheckedInHere() {
return mCheckedInHere;
}
public void setCheckedInHere(boolean checkedInHere) {
mCheckedInHere = checkedInHere;
}
public void setIsRunningTaskVenue(boolean isRunningTaskVenue) {
mIsRunningTaskVenue = isRunningTaskVenue;
}
public void startTaskVenue(VenueActivity activity) {
if (!mIsRunningTaskVenue) {
mIsRunningTaskVenue = true;
mTaskVenue = new TaskVenue(activity);
if (mLoadType == LOAD_TYPE_VENUE_ID) {
mTaskVenue.execute(mVenueId);
} else if (mLoadType == LOAD_TYPE_VENUE_PARTIAL) {
mTaskVenue.execute(mVenue.getId());
}
}
}
public void setActivityForTasks(VenueActivity activity) {
if (mTaskVenue != null) {
mTaskVenue.setActivity(activity);
}
}
public int getLoadType() {
return mLoadType;
}
public void setLoadType(int loadType) {
mLoadType = loadType;
}
}
/**
* Handles population of the mayor photo. The strip of checkin photos has its own
* internal observer.
*/
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
mHandler.post(mRunnableMayorPhoto);
}
}
private Runnable mRunnableMayorPhoto = new Runnable() {
@Override
public void run() {
ImageView ivMayorPhoto = (ImageView)findViewById(R.id.venueActivityMayorPhoto);
if (ivMayorPhoto.getTag() != null) {
String mayorPhotoUrl = (String)ivMayorPhoto.getTag();
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(mayorPhotoUrl)));
ivMayorPhoto.setImageBitmap(bitmap);
ivMayorPhoto.setTag(null);
ivMayorPhoto.invalidate();
} catch (IOException ex) {
Log.e(TAG, "Error decoding mayor photo on notification, ignoring.", ex);
}
}
}
};
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.joelapenna.foursquared.widget.TipsListAdapter;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.Observable;
import java.util.Observer;
/**
* Shows a list of nearby tips. User can sort tips by friends-only.
*
* @date August 31, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TipsActivity extends LoadableListActivityWithViewAndHeader {
static final String TAG = "TipsActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int ACTIVITY_TIP = 500;
private StateHolder mStateHolder;
private TipsListAdapter mListAdapter;
private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver();
private View mLayoutEmpty;
private static final int MENU_REFRESH = 0;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
mStateHolder = new StateHolder();
mStateHolder.setFriendsOnly(true);
}
ensureUi();
// Friend tips is shown first by default so auto-fetch it if necessary.
if (!mStateHolder.getRanOnceTipsFriends()) {
mStateHolder.startTaskTips(this, true);
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver);
if (isFinishing()) {
mStateHolder.cancelTasks();
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void ensureUi() {
LayoutInflater inflater = LayoutInflater.from(this);
mLayoutEmpty = inflater.inflate(R.layout.tips_activity_empty, null);
mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
mListAdapter = new TipsListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item);
if (mStateHolder.getFriendsOnly()) {
mListAdapter.setGroup(mStateHolder.getTipsFriends());
if (mStateHolder.getTipsFriends().size() == 0) {
if (mStateHolder.getRanOnceTipsFriends()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
} else {
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
if (mStateHolder.getTipsEveryone().size() == 0) {
if (mStateHolder.getRanOnceTipsEveryone()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
}
SegmentedButton buttons = getHeaderButton();
buttons.clearButtons();
buttons.addButtons(
getString(R.string.tips_activity_btn_friends_only),
getString(R.string.tips_activity_btn_everyone));
if (mStateHolder.mFriendsOnly) {
buttons.setPushedButtonIndex(0);
} else {
buttons.setPushedButtonIndex(1);
}
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
if (index == 0) {
mStateHolder.setFriendsOnly(true);
mListAdapter.setGroup(mStateHolder.getTipsFriends());
if (mStateHolder.getTipsFriends().size() < 1) {
if (mStateHolder.getRanOnceTipsFriends()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(TipsActivity.this, true);
}
}
} else {
mStateHolder.setFriendsOnly(false);
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
if (mStateHolder.getTipsEveryone().size() < 1) {
if (mStateHolder.getRanOnceTipsEveryone()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(TipsActivity.this, false);
}
}
}
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
});
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(false);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tip tip = (Tip) parent.getAdapter().getItem(position);
Intent intent = new Intent(TipsActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip);
startActivityForResult(intent, ACTIVITY_TIP);
}
});
if (mStateHolder.getIsRunningTaskTipsFriends() ||
mStateHolder.getIsRunningTaskTipsEveryone()) {
setProgressBarIndeterminateVisibility(true);
} else {
setProgressBarIndeterminateVisibility(false);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh)
.setIcon(R.drawable.ic_menu_refresh);
MenuUtils.addPreferencesToMenu(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
mStateHolder.startTaskTips(this, mStateHolder.getFriendsOnly());
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// We don't care about the returned to-do (if any) since we're not bound
// to a venue in this activity for update. We just update the status member
// of the target tip.
if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) {
if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) {
Log.d(TAG, "onActivityResult(), return tip intent extra found, processing.");
updateTip((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED));
} else {
Log.d(TAG, "onActivityResult(), no return tip intent extra found.");
}
}
}
private void updateTip(Tip tip) {
mStateHolder.updateTip(tip);
mListAdapter.notifyDataSetInvalidated();
}
private void onStartTaskTips() {
if (mListAdapter != null) {
if (mStateHolder.getFriendsOnly()) {
mStateHolder.setIsRunningTaskTipsFriends(true);
mListAdapter.setGroup(mStateHolder.getTipsFriends());
} else {
mStateHolder.setIsRunningTaskTipsEveryone(true);
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
}
mListAdapter.notifyDataSetChanged();
}
setProgressBarIndeterminateVisibility(true);
setLoadingView();
}
private void onTaskTipsComplete(Group<Tip> group, boolean friendsOnly, Exception ex) {
SegmentedButton buttons = getHeaderButton();
boolean update = false;
if (group != null) {
if (friendsOnly) {
mStateHolder.setTipsFriends(group);
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsFriends());
update = true;
}
} else {
mStateHolder.setTipsEveryone(group);
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
update = true;
}
}
}
else {
if (friendsOnly) {
mStateHolder.setTipsFriends(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsFriends());
update = true;
}
} else {
mStateHolder.setTipsEveryone(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
update = true;
}
}
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (friendsOnly) {
mStateHolder.setIsRunningTaskTipsFriends(false);
mStateHolder.setRanOnceTipsFriends(true);
if (mStateHolder.getTipsFriends().size() == 0 &&
buttons.getSelectedButtonIndex() == 0) {
setEmptyView(mLayoutEmpty);
}
} else {
mStateHolder.setIsRunningTaskTipsEveryone(false);
mStateHolder.setRanOnceTipsEveryone(true);
if (mStateHolder.getTipsEveryone().size() == 0 &&
buttons.getSelectedButtonIndex() == 1) {
setEmptyView(mLayoutEmpty);
}
}
if (update) {
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
if (!mStateHolder.getIsRunningTaskTipsFriends() &&
!mStateHolder.getIsRunningTaskTipsEveryone()) {
setProgressBarIndeterminateVisibility(false);
}
}
/**
* Gets friends of the current user we're working for.
*/
private static class TaskTips extends AsyncTask<Void, Void, Group<Tip>> {
private TipsActivity mActivity;
private boolean mFriendsOnly;
private Exception mReason;
public TaskTips(TipsActivity activity, boolean friendsOnly) {
mActivity = activity;
mFriendsOnly = friendsOnly;
}
@Override
protected void onPreExecute() {
mActivity.onStartTaskTips();
}
@Override
protected Group<Tip> doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
Location loc = foursquared.getLastKnownLocation();
if (loc == null) {
try { Thread.sleep(3000); } catch (InterruptedException ex) {}
loc = foursquared.getLastKnownLocation();
if (loc == null) {
throw new FoursquareException("Your location could not be determined!");
}
}
return foursquare.tips(
LocationUtils.createFoursquareLocation(loc),
null,
mFriendsOnly ? "friends" : "nearby",
null,
30);
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Tip> tips) {
if (mActivity != null) {
mActivity.onTaskTipsComplete(tips, mFriendsOnly, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskTipsComplete(null, mFriendsOnly, mReason);
}
}
public void setActivity(TipsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
/** Tips by friends. */
private Group<Tip> mTipsFriends;
/** Tips by everyone. */
private Group<Tip> mTipsEveryone;
private TaskTips mTaskTipsFriends;
private TaskTips mTaskTipsEveryone;
private boolean mIsRunningTaskTipsFriends;
private boolean mIsRunningTaskTipsEveryone;
private boolean mFriendsOnly;
private boolean mRanOnceTipsFriends;
private boolean mRanOnceTipsEveryone;
public StateHolder() {
mIsRunningTaskTipsFriends = false;
mIsRunningTaskTipsEveryone = false;
mRanOnceTipsFriends = false;
mRanOnceTipsEveryone = false;
mTipsFriends = new Group<Tip>();
mTipsEveryone = new Group<Tip>();
mFriendsOnly = true;
}
public Group<Tip> getTipsFriends() {
return mTipsFriends;
}
public void setTipsFriends(Group<Tip> tipsFriends) {
mTipsFriends = tipsFriends;
}
public Group<Tip> getTipsEveryone() {
return mTipsEveryone;
}
public void setTipsEveryone(Group<Tip> tipsEveryone) {
mTipsEveryone = tipsEveryone;
}
public void startTaskTips(TipsActivity activity,
boolean friendsOnly) {
if (friendsOnly) {
if (mIsRunningTaskTipsFriends) {
return;
}
mIsRunningTaskTipsFriends = true;
mTaskTipsFriends = new TaskTips(activity, friendsOnly);
mTaskTipsFriends.execute();
} else {
if (mIsRunningTaskTipsEveryone) {
return;
}
mIsRunningTaskTipsEveryone = true;
mTaskTipsEveryone = new TaskTips(activity, friendsOnly);
mTaskTipsEveryone.execute();
}
}
public void setActivity(TipsActivity activity) {
if (mTaskTipsFriends != null) {
mTaskTipsFriends.setActivity(activity);
}
if (mTaskTipsEveryone != null) {
mTaskTipsEveryone.setActivity(activity);
}
}
public boolean getIsRunningTaskTipsFriends() {
return mIsRunningTaskTipsFriends;
}
public void setIsRunningTaskTipsFriends(boolean isRunning) {
mIsRunningTaskTipsFriends = isRunning;
}
public boolean getIsRunningTaskTipsEveryone() {
return mIsRunningTaskTipsEveryone;
}
public void setIsRunningTaskTipsEveryone(boolean isRunning) {
mIsRunningTaskTipsEveryone = isRunning;
}
public void cancelTasks() {
if (mTaskTipsFriends != null) {
mTaskTipsFriends.setActivity(null);
mTaskTipsFriends.cancel(true);
}
if (mTaskTipsEveryone != null) {
mTaskTipsEveryone.setActivity(null);
mTaskTipsEveryone.cancel(true);
}
}
public boolean getFriendsOnly() {
return mFriendsOnly;
}
public void setFriendsOnly(boolean friendsOnly) {
mFriendsOnly = friendsOnly;
}
public boolean getRanOnceTipsFriends() {
return mRanOnceTipsFriends;
}
public void setRanOnceTipsFriends(boolean ranOnce) {
mRanOnceTipsFriends = ranOnce;
}
public boolean getRanOnceTipsEveryone() {
return mRanOnceTipsEveryone;
}
public void setRanOnceTipsEveryone(boolean ranOnce) {
mRanOnceTipsEveryone = ranOnce;
}
public void updateTip(Tip tip) {
updateTipFromArray(tip, mTipsFriends);
updateTipFromArray(tip, mTipsEveryone);
}
private void updateTipFromArray(Tip tip, Group<Tip> target) {
for (Tip it : target) {
if (it.getId().equals(tip.getId())) {
it.setStatus(tip.getStatus());
break;
}
}
}
}
/**
* This is really just a dummy observer to get the GPS running
* since this is the new splash page. After getting a fix, we
* might want to stop registering this observer thereafter so
* it doesn't annoy the user too much.
*/
private class SearchLocationObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
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.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class LoginActivity extends Activity {
public static final String TAG = "LoginActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private AsyncTask<Void, Void, Boolean> mLoginTask;
private TextView mNewAccountTextView;
private EditText mPhoneUsernameEditText;
private EditText mPasswordEditText;
private ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login_activity);
Preferences.logoutUser( //
((Foursquared) getApplication()).getFoursquare(), //
PreferenceManager.getDefaultSharedPreferences(this).edit());
// Set up the UI.
ensureUi();
// Re-task if the request was cancelled.
mLoginTask = (LoginTask) getLastNonConfigurationInstance();
if (mLoginTask != null && mLoginTask.isCancelled()) {
if (DEBUG) Log.d(TAG, "LoginTask previously cancelled, trying again.");
mLoginTask = new LoginTask().execute();
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(false);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates();
}
@Override
public Object onRetainNonConfigurationInstance() {
if (DEBUG) Log.d(TAG, "onRetainNonConfigurationInstance()");
if (mLoginTask != null) {
mLoginTask.cancel(true);
}
return mLoginTask;
}
private ProgressDialog showProgressDialog() {
if (mProgressDialog == null) {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle(R.string.login_dialog_title);
dialog.setMessage(getString(R.string.login_dialog_message));
dialog.setIndeterminate(true);
dialog.setCancelable(true);
mProgressDialog = dialog;
}
mProgressDialog.show();
return mProgressDialog;
}
private void dismissProgressDialog() {
try {
mProgressDialog.dismiss();
} catch (IllegalArgumentException e) {
// We don't mind. android cleared it for us.
}
}
private void ensureUi() {
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mLoginTask = new LoginTask().execute();
}
});
mNewAccountTextView = (TextView) findViewById(R.id.newAccountTextView);
mNewAccountTextView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse(Foursquare.FOURSQUARE_MOBILE_SIGNUP)));
}
});
mPhoneUsernameEditText = ((EditText) findViewById(R.id.phoneEditText));
mPasswordEditText = ((EditText) findViewById(R.id.passwordEditText));
TextWatcher fieldValidatorTextWatcher = 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) {
button.setEnabled(phoneNumberEditTextFieldIsValid()
&& passwordEditTextFieldIsValid());
}
private boolean phoneNumberEditTextFieldIsValid() {
// This can be either a phone number or username so we don't
// care too much about the
// format.
return !TextUtils.isEmpty(mPhoneUsernameEditText.getText());
}
private boolean passwordEditTextFieldIsValid() {
return !TextUtils.isEmpty(mPasswordEditText.getText());
}
};
mPhoneUsernameEditText.addTextChangedListener(fieldValidatorTextWatcher);
mPasswordEditText.addTextChangedListener(fieldValidatorTextWatcher);
}
private class LoginTask extends AsyncTask<Void, Void, Boolean> {
private static final String TAG = "LoginTask";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Exception mReason;
@Override
protected void onPreExecute() {
if (DEBUG) Log.d(TAG, "onPreExecute()");
showProgressDialog();
}
@Override
protected Boolean doInBackground(Void... params) {
if (DEBUG) Log.d(TAG, "doInBackground()");
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
Editor editor = prefs.edit();
Foursquared foursquared = (Foursquared) getApplication();
Foursquare foursquare = foursquared.getFoursquare();
try {
String phoneNumber = mPhoneUsernameEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
Foursquare.Location location = null;
location = LocationUtils.createFoursquareLocation(
foursquared.getLastKnownLocation());
boolean loggedIn = Preferences.loginUser(foursquare, phoneNumber, password,
location, editor);
// Make sure prefs makes a round trip.
String userId = Preferences.getUserId(prefs);
if (TextUtils.isEmpty(userId)) {
if (DEBUG) Log.d(TAG, "Preference store calls failed");
throw new FoursquareException(getResources().getString(
R.string.login_failed_login_toast));
}
return loggedIn;
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "Caught Exception logging in.", e);
mReason = e;
Preferences.logoutUser(foursquare, editor);
return false;
}
}
@Override
protected void onPostExecute(Boolean loggedIn) {
if (DEBUG) Log.d(TAG, "onPostExecute(): " + loggedIn);
Foursquared foursquared = (Foursquared) getApplication();
if (loggedIn) {
sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_IN));
Toast.makeText(LoginActivity.this, getString(R.string.login_welcome_toast),
Toast.LENGTH_LONG).show();
// Launch the service to update any widgets, etc.
foursquared.requestStartService();
// Launch the main activity to let the user do anything.
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
// Be done with the activity.
finish();
} else {
sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_OUT));
NotificationsUtil.ToastReasonForFailure(LoginActivity.this, mReason);
}
dismissProgressDialog();
}
@Override
protected void onCancelled() {
dismissProgressDialog();
}
}
}
| 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.error.LocationException;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.providers.VenueQuerySuggestionsProvider;
import com.joelapenna.foursquared.util.Comparators;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.TabsUtil;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.VenueListAdapter;
import android.app.Activity;
import android.app.SearchManager;
import android.app.TabActivity;
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.os.Parcelable;
import android.provider.SearchRecentSuggestions;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Collections;
import java.util.Observable;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class SearchVenuesActivity extends TabActivity {
static final String TAG = "SearchVenuesActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String QUERY_NEARBY = null;
public static SearchResultsObservable searchResultsObservable;
private static final int MENU_SEARCH = 0;
private static final int MENU_REFRESH = 1;
private static final int MENU_NEARBY = 2;
private static final int MENU_ADD_VENUE = 3;
private static final int MENU_GROUP_SEARCH = 0;
private SearchTask mSearchTask;
private SearchHolder mSearchHolder = new SearchHolder();
private ListView mListView;
private LinearLayout mEmpty;
private TextView mEmptyText;
private ProgressBar mEmptyProgress;
private TabHost mTabHost;
private SeparatedListAdapter mListAdapter;
private boolean mIsShortcutPicker;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.search_venues_activity);
setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
searchResultsObservable = new SearchResultsObservable();
initTabHost();
initListViewAdapter();
// Watch to see if we've been called as a shortcut intent.
mIsShortcutPicker = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction());
if (getLastNonConfigurationInstance() != null) {
if (DEBUG) Log.d(TAG, "Restoring state.");
SearchHolder holder = (SearchHolder) getLastNonConfigurationInstance();
if (holder.results != null) {
mSearchHolder.query = holder.query;
setSearchResults(holder.results);
putSearchResultsInAdapter(holder.results);
}
} else {
onNewIntent(getIntent());
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(true);
if (mSearchHolder.results == null && mSearchTask == null) {
mSearchTask = (SearchTask) new SearchTask().execute();
}
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates();
if (isFinishing()) {
mListAdapter.removeObserver();
}
}
@Override
public void onStop() {
super.onStop();
if (mSearchTask != null) {
mSearchTask.cancel(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Always show these.
menu.add(MENU_GROUP_SEARCH, MENU_SEARCH, Menu.NONE, R.string.search_label) //
.setIcon(R.drawable.ic_menu_search) //
.setAlphabeticShortcut(SearchManager.MENU_KEY);
menu.add(MENU_GROUP_SEARCH, MENU_NEARBY, Menu.NONE, R.string.nearby_label) //
.setIcon(R.drawable.ic_menu_places);
menu.add(MENU_GROUP_SEARCH, MENU_REFRESH, Menu.NONE, R.string.refresh) //
.setIcon(R.drawable.ic_menu_refresh);
menu.add(MENU_GROUP_SEARCH, MENU_ADD_VENUE, Menu.NONE, R.string.nearby_menu_add_venue) //
.setIcon(R.drawable.ic_menu_add);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SEARCH:
onSearchRequested();
return true;
case MENU_NEARBY:
executeSearchTask(null);
return true;
case MENU_REFRESH:
executeSearchTask(mSearchHolder.query);
return true;
case MENU_ADD_VENUE:
Intent intent = new Intent(SearchVenuesActivity.this, AddVenueActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onNewIntent(Intent intent) {
if (intent != null) {
String action = intent.getAction();
String query = intent.getStringExtra(SearchManager.QUERY);
Log.i(TAG, "New Intent: action[" + action + "].");
if (!TextUtils.isEmpty(action)) {
if (action.equals(Intent.ACTION_CREATE_SHORTCUT)) {
Log.i(TAG, " action = create shortcut, user can click one of the current venues.");
} else if (action.equals(Intent.ACTION_VIEW)) {
if (!TextUtils.isEmpty(query)) {
Log.i(TAG, " action = view, query term provided, prepopulating search.");
startSearch(query, false, null, false);
} else {
Log.i(TAG, " action = view, but no query term provided, doing nothing.");
}
} else if (action.equals(Intent.ACTION_SEARCH) && !TextUtils.isEmpty(query)) {
Log.i(TAG, " action = search, query term provided, executing search immediately.");
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
VenueQuerySuggestionsProvider.AUTHORITY, VenueQuerySuggestionsProvider.MODE);
suggestions.saveRecentQuery(query, null);
executeSearchTask(query);
}
}
}
}
@Override
public Object onRetainNonConfigurationInstance() {
return mSearchHolder;
}
public void putSearchResultsInAdapter(Group<Group<Venue>> searchResults) {
mListAdapter.removeObserver();
mListAdapter = new SeparatedListAdapter(this);
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);
}
}
mListView.setAdapter(mListAdapter);
}
public void setSearchResults(Group<Group<Venue>> searchResults) {
if (DEBUG) Log.d(TAG, "Setting search results.");
mSearchHolder.results = searchResults;
searchResultsObservable.notifyObservers();
}
void executeSearchTask(String query) {
if (DEBUG) Log.d(TAG, "sendQuery()");
mSearchHolder.query = query;
// not going through set* because we don't want to notify search result
// observers.
mSearchHolder.results = null;
// If a task is already running, don't start a new one.
if (mSearchTask != null && mSearchTask.getStatus() != AsyncTask.Status.FINISHED) {
if (DEBUG) Log.d(TAG, "Query already running attempting to cancel: " + mSearchTask);
if (!mSearchTask.cancel(true) && !mSearchTask.isCancelled()) {
if (DEBUG) Log.d(TAG, "Unable to cancel search? Notifying the user.");
Toast.makeText(this, getString(R.string.search_already_in_progress_toast),
Toast.LENGTH_SHORT);
return;
}
}
mSearchTask = (SearchTask) new SearchTask().execute();
}
void startItemActivity(Venue venue) {
Intent intent = new Intent(SearchVenuesActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
startActivity(intent);
}
private void ensureSearchResults() {
if (mListAdapter.getCount() > 0) {
mEmpty.setVisibility(LinearLayout.GONE);
mListView.setVisibility(ViewGroup.VISIBLE);
} else {
mEmpty.setVisibility(LinearLayout.VISIBLE);
mEmptyProgress.setVisibility(ViewGroup.GONE);
mEmptyText.setText(R.string.no_search_results);
mListView.setVisibility(ViewGroup.GONE);
}
}
private void ensureTitle(boolean finished) {
if (finished) {
if (mSearchHolder.query == QUERY_NEARBY) {
setTitle(getString(R.string.title_search_finished_noquery));
} else {
setTitle(getString(R.string.title_search_finished, mSearchHolder.query));
}
} else {
if (mSearchHolder.query == QUERY_NEARBY) {
setTitle(getString(R.string.title_search_inprogress_noquery));
} else {
setTitle(getString(R.string.title_search_inprogress, mSearchHolder.query));
}
}
}
private void initListViewAdapter() {
if (mListView != null) {
throw new IllegalStateException("Trying to initialize already initialized ListView");
}
mEmpty = (LinearLayout) findViewById(R.id.empty);
mEmptyText = (TextView) findViewById(R.id.emptyText);
mEmptyProgress = (ProgressBar) findViewById(R.id.emptyProgress);
mListView = (ListView) findViewById(R.id.list);
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);
if (mIsShortcutPicker) {
setupShortcut(venue);
finish();
} else {
startItemActivity(venue);
}
finish();
}
});
}
protected void setupShortcut(Venue venue) {
// First, set up the shortcut intent. For this example, we simply create
// an intent that will bring us directly back to this activity. A more
// typical implementation would use a data Uri in order to display a more
// specific result, or a custom action in order to launch a specific operation.
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, VenueActivity.class.getName());
shortcutIntent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, venue.getId());
// Then, set up the container intent (the response to the caller)
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, venue.getName());
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this,
R.drawable.venue_shortcut_icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher
setResult(RESULT_OK, intent);
}
private void initTabHost() {
if (mTabHost != null) {
throw new IllegalStateException("Trying to intialize already initializd TabHost");
}
mTabHost = getTabHost();
TabsUtil.addTab(mTabHost, getString(R.string.tab_search_nav_venues),
R.drawable.tab_search_nav_venues_selector, 0, R.id.listviewLayout);
TabsUtil.addTab(mTabHost, getString(R.string.tab_search_nav_map),
R.drawable.tab_search_nav_map_selector,
1, new Intent(this, SearchVenuesMapActivity.class));
mTabHost.setCurrentTab(0);
// Fix layout for 1.5.
if (UiUtil.sdkVersion() < 4) {
FrameLayout flTabContent = (FrameLayout)findViewById(android.R.id.tabcontent);
flTabContent.setPadding(0, 0, 0, 0);
}
}
private class SearchTask extends AsyncTask<Void, Void, Group<Group<Venue>>> {
private Exception mReason = null;
@Override
public void onPreExecute() {
if (DEBUG) Log.d(TAG, "SearchTask: onPreExecute()");
setProgressBarIndeterminateVisibility(true);
ensureTitle(false);
}
@Override
public Group<Group<Venue>> doInBackground(Void... params) {
try {
return search();
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
public void onPostExecute(Group<Group<Venue>> groups) {
try {
if (groups == null) {
NotificationsUtil.ToastReasonForFailure(SearchVenuesActivity.this, mReason);
} else {
setSearchResults(groups);
putSearchResultsInAdapter(groups);
}
} finally {
setProgressBarIndeterminateVisibility(false);
ensureTitle(true);
ensureSearchResults();
}
}
public Group<Group<Venue>> search() throws FoursquareException, LocationException,
IOException {
Foursquare foursquare = ((Foursquared) getApplication()).getFoursquare();
Location location = ((Foursquared) getApplication()).getLastKnownLocationOrThrow();
Group<Group<Venue>> groups = foursquare.venues(LocationUtils
.createFoursquareLocation(location), mSearchHolder.query, 30);
for (int i = 0; i < groups.size(); i++) {
Collections.sort(groups.get(i), Comparators.getVenueDistanceComparator());
}
return groups;
}
}
private static class SearchHolder {
Group<Group<Venue>> results;
String query;
}
class SearchResultsObservable extends Observable {
@Override
public void notifyObservers(Object data) {
setChanged();
super.notifyObservers(data);
}
public Group<Group<Venue>> getSearchResults() {
return mSearchHolder.results;
}
public String getQuery() {
return mSearchHolder.query;
}
};
}
| 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.User;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.util.UserUtils;
import com.joelapenna.foursquared.widget.PhotoStrip;
import com.joelapenna.foursquared.widget.UserContactAdapter;
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.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* @date March 8, 2010.
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserDetailsActivity extends Activity {
private static final String TAG = "UserDetailsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int ACTIVITY_REQUEST_CODE_PINGS = 815;
private static final int ACTIVITY_REQUEST_CODE_FETCH_IMAGE = 816;
private static final int ACTIVITY_REQUEST_CODE_VIEW_AND_SET_IMAGE = 817;
public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME
+ ".UserDetailsActivity.EXTRA_USER_PARCEL";
public static final String EXTRA_USER_ID = Foursquared.PACKAGE_NAME
+ ".UserDetailsActivity.EXTRA_USER_ID";
public static final String EXTRA_SHOW_ADD_FRIEND_OPTIONS = Foursquared.PACKAGE_NAME
+ ".UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS";
private static final int LOAD_TYPE_USER_NONE = 0;
private static final int LOAD_TYPE_USER_ID = 1;
private static final int LOAD_TYPE_USER_PARTIAL = 2;
private static final int LOAD_TYPE_USER_FULL = 3;
private static final int MENU_REFRESH = 0;
private static final int MENU_CONTACT = 1;
private static final int MENU_PINGS = 2;
private static final int DIALOG_CONTACTS = 0;
private StateHolder mStateHolder;
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
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);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.user_details_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivityForTasks(this);
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(EXTRA_USER_PARCEL)) {
Log.i(TAG, "Starting " + TAG + " with full user parcel.");
User user = getIntent().getExtras().getParcelable(EXTRA_USER_PARCEL);
mStateHolder.setUser(user);
mStateHolder.setLoadType(LOAD_TYPE_USER_PARTIAL);
} else if (getIntent().hasExtra(EXTRA_USER_ID)) {
Log.i(TAG, "Starting " + TAG + " with user ID.");
User user = new User();
user.setId(getIntent().getExtras().getString(EXTRA_USER_ID));
mStateHolder.setUser(user);
mStateHolder.setLoadType(LOAD_TYPE_USER_ID);
} else {
Log.i(TAG, "Starting " + TAG + " as logged-in user.");
User user = new User();
user.setId(null);
mStateHolder.setUser(user);
mStateHolder.setLoadType(LOAD_TYPE_USER_ID);
}
mStateHolder.setIsLoggedInUser(
mStateHolder.getUser().getId() == null ||
mStateHolder.getUser().getId().equals(
((Foursquared) getApplication()).getUserId()));
}
mHandler = new Handler();
mRrm = ((Foursquared) getApplication()).getRemoteResourceManager();
mResourcesObserver = new RemoteResourceManagerObserver();
mRrm.addObserver(mResourcesObserver);
ensureUi();
if (mStateHolder.getLoadType() != LOAD_TYPE_USER_FULL &&
!mStateHolder.getIsRunningUserDetailsTask() &&
!mStateHolder.getRanOnce()) {
mStateHolder.startTaskUserDetails(this, mStateHolder.getUser().getId());
}
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mStateHolder.cancelTasks();
mHandler.removeCallbacks(mRunnableUpdateUserPhoto);
RemoteResourceManager rrm = ((Foursquared) getApplication()).getRemoteResourceManager();
rrm.deleteObserver(mResourcesObserver);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
private void ensureUi() {
int sdk = UiUtil.sdkVersion();
View viewProgressBar = findViewById(R.id.venueActivityDetailsProgress);
TextView tvUsername = (TextView)findViewById(R.id.userDetailsActivityUsername);
TextView tvLastSeen = (TextView)findViewById(R.id.userDetailsActivityHometownOrLastSeen);
Button btnFriend = (Button)findViewById(R.id.userDetailsActivityFriendButton);
View viewMayorships = findViewById(R.id.userDetailsActivityGeneralMayorships);
View viewBadges = findViewById(R.id.userDetailsActivityGeneralBadges);
View viewTips = findViewById(R.id.userDetailsActivityGeneralTips);
TextView tvMayorships = (TextView)findViewById(R.id.userDetailsActivityGeneralMayorshipsValue);
TextView tvBadges = (TextView)findViewById(R.id.userDetailsActivityGeneralBadgesValue);
TextView tvTips = (TextView)findViewById(R.id.userDetailsActivityGeneralTipsValue);
ImageView ivMayorshipsChevron = (ImageView)findViewById(R.id.userDetailsActivityGeneralMayorshipsChevron);
ImageView ivBadgesChevron = (ImageView)findViewById(R.id.userDetailsActivityGeneralBadgesChevron);
ImageView ivTipsChevron = (ImageView)findViewById(R.id.userDetailsActivityGeneralTipsChevron);
View viewCheckins = findViewById(R.id.userDetailsActivityCheckins);
View viewFriendsFollowers = findViewById(R.id.userDetailsActivityFriendsFollowers);
View viewAddFriends = findViewById(R.id.userDetailsActivityAddFriends);
View viewTodos = findViewById(R.id.userDetailsActivityTodos);
View viewFriends = findViewById(R.id.userDetailsActivityFriends);
TextView tvCheckins = (TextView)findViewById(R.id.userDetailsActivityCheckinsText);
ImageView ivCheckinsChevron = (ImageView)findViewById(R.id.userDetailsActivityCheckinsChevron);
TextView tvFriendsFollowers = (TextView)findViewById(R.id.userDetailsActivityFriendsFollowersText);
ImageView ivFriendsFollowersChevron = (ImageView)findViewById(R.id.userDetailsActivityFriendsFollowersChevron);
TextView tvTodos = (TextView)findViewById(R.id.userDetailsActivityTodosText);
ImageView ivTodos = (ImageView)findViewById(R.id.userDetailsActivityTodosChevron);
TextView tvFriends = (TextView)findViewById(R.id.userDetailsActivityFriendsText);
ImageView ivFriends = (ImageView)findViewById(R.id.userDetailsActivityFriendsChevron);
PhotoStrip psFriends = (PhotoStrip)findViewById(R.id.userDetailsActivityFriendsPhotos);
viewProgressBar.setVisibility(View.VISIBLE);
tvUsername.setText("");
tvLastSeen.setText("");
viewMayorships.setFocusable(false);
viewBadges.setFocusable(false);
viewTips.setFocusable(false);
tvMayorships.setText("0");
tvBadges.setText("0");
tvTips.setText("0");
ivMayorshipsChevron.setVisibility(View.INVISIBLE);
ivBadgesChevron.setVisibility(View.INVISIBLE);
ivTipsChevron.setVisibility(View.INVISIBLE);
btnFriend.setVisibility(View.INVISIBLE);
viewCheckins.setFocusable(false);
viewFriendsFollowers.setFocusable(false);
viewAddFriends.setFocusable(false);
viewTodos.setFocusable(false);
viewFriends.setFocusable(false);
viewCheckins.setVisibility(View.GONE);
viewFriendsFollowers.setVisibility(View.GONE);
viewAddFriends.setVisibility(View.GONE);
viewTodos.setVisibility(View.GONE);
viewFriends.setVisibility(View.GONE);
ivCheckinsChevron.setVisibility(View.INVISIBLE);
ivFriendsFollowersChevron.setVisibility(View.INVISIBLE);
ivTodos.setVisibility(View.INVISIBLE);
ivFriends.setVisibility(View.INVISIBLE);
psFriends.setVisibility(View.GONE);
tvCheckins.setText("");
tvFriendsFollowers.setText("");
tvTodos.setText("");
tvFriends.setText("");
if (mStateHolder.getLoadType() >= LOAD_TYPE_USER_PARTIAL) {
User user = mStateHolder.getUser();
ensureUiPhoto(user);
if (mStateHolder.getIsLoggedInUser() || UserUtils.isFriend(user)) {
tvUsername.setText(StringFormatters.getUserFullName(user));
} else {
tvUsername.setText(StringFormatters.getUserAbbreviatedName(user));
}
tvLastSeen.setText(user.getHometown());
if (mStateHolder.getIsLoggedInUser() ||
UserUtils.isFriend(user) ||
UserUtils.isFriendStatusPendingThem(user) ||
UserUtils.isFriendStatusFollowingThem(user)) {
btnFriend.setVisibility(View.INVISIBLE);
} else if (UserUtils.isFriendStatusPendingYou(user)) {
btnFriend.setVisibility(View.VISIBLE);
btnFriend.setText(getString(R.string.user_details_activity_friend_confirm));
btnFriend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mStateHolder.startTaskFriend(UserDetailsActivity.this, StateHolder.TASK_FRIEND_ACCEPT);
}
});
} else {
btnFriend.setVisibility(View.VISIBLE);
btnFriend.setText(getString(R.string.user_details_activity_friend_add));
btnFriend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
view.setEnabled(false);
mStateHolder.startTaskFriend(UserDetailsActivity.this, StateHolder.TASK_FRIEND_ADD);
}
});
}
if (mStateHolder.getLoadType() >= LOAD_TYPE_USER_FULL) {
viewProgressBar.setVisibility(View.GONE);
tvMayorships.setText(String.valueOf(user.getMayorCount()));
tvBadges.setText(String.valueOf(user.getBadgeCount()));
tvTips.setText(String.valueOf(user.getTipCount()));
if (user.getCheckin() != null && user.getCheckin().getVenue() != null) {
String fixed = getResources().getString(R.string.user_details_activity_last_seen);
String full = fixed + " " + user.getCheckin().getVenue().getName();
CharacterStyle bold = new StyleSpan(Typeface.BOLD);
SpannableString ss = new SpannableString(full);
ss.setSpan(bold, fixed.length(), full.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
tvLastSeen.setText(ss);
tvLastSeen.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
startVenueActivity();
}
});
}
if (user.getMayorships() != null && user.getMayorships().size() > 0) {
viewMayorships.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startMayorshipsActivity();
}
});
viewMayorships.setFocusable(true);
if (sdk > 3) {
ivMayorshipsChevron.setVisibility(View.VISIBLE);
}
}
if (user.getBadges() != null && user.getBadges().size() > 0) {
viewBadges.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startBadgesActivity();
}
});
viewBadges.setFocusable(true);
if (sdk > 3) {
ivBadgesChevron.setVisibility(View.VISIBLE);
}
}
if (user.getTipCount() > 0) {
viewTips.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startTipsActivity();
}
});
viewTips.setFocusable(true);
if (sdk > 3) {
ivTipsChevron.setVisibility(View.VISIBLE);
}
}
// The rest of the items depend on if we're viewing ourselves or not.
if (mStateHolder.getIsLoggedInUser()) {
viewCheckins.setVisibility(View.VISIBLE);
viewFriendsFollowers.setVisibility(View.VISIBLE);
viewAddFriends.setVisibility(View.VISIBLE);
tvCheckins.setText(
user.getCheckinCount() == 1 ?
getResources().getString(
R.string.user_details_activity_checkins_text_single, user.getCheckinCount()) :
getResources().getString(
R.string.user_details_activity_checkins_text_plural, user.getCheckinCount()));
if (user.getCheckinCount() > 0) {
viewCheckins.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startCheckinsActivity();
}
});
viewCheckins.setFocusable(true);
ivCheckinsChevron.setVisibility(View.VISIBLE);
}
if (user.getFollowerCount() > 0) {
tvFriendsFollowers.setText(
user.getFollowerCount() == 1 ?
getResources().getString(
R.string.user_details_activity_friends_followers_text_celeb_single,
user.getFollowerCount()) :
getResources().getString(
R.string.user_details_activity_friends_followers_text_celeb_plural,
user.getFollowerCount()));
if (user.getFriendCount() > 0) {
tvFriendsFollowers.setText(tvFriendsFollowers.getText() + ", ");
}
}
tvFriendsFollowers.setText(tvFriendsFollowers.getText().toString() +
(user.getFriendCount() == 1 ?
getResources().getString(
R.string.user_details_activity_friends_followers_text_single,
user.getFriendCount()) :
getResources().getString(
R.string.user_details_activity_friends_followers_text_plural,
user.getFriendCount())));
if (user.getFollowerCount() + user.getFriendCount() > 0) {
viewFriendsFollowers.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startFriendsFollowersActivity();
}
});
viewFriendsFollowers.setFocusable(true);
ivFriendsFollowersChevron.setVisibility(View.VISIBLE);
}
viewAddFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startAddFriendsActivity();
}
});
viewAddFriends.setFocusable(true);
} else {
viewTodos.setVisibility(View.VISIBLE);
viewFriends.setVisibility(View.VISIBLE);
tvTodos.setText(
user.getTodoCount() == 1 ?
getResources().getString(
R.string.user_details_activity_todos_text_single, user.getTodoCount()) :
getResources().getString(
R.string.user_details_activity_todos_text_plural, user.getTodoCount()));
if (user.getTodoCount() > 0 && UserUtils.isFriend(user)) {
viewTodos.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startTodosActivity();
}
});
viewTodos.setFocusable(true);
ivTodos.setVisibility(View.VISIBLE);
}
tvFriends.setText(
user.getFriendCount() == 1 ?
getResources().getString(
R.string.user_details_activity_friends_text_single,
user.getFriendCount()) :
getResources().getString(
R.string.user_details_activity_friends_text_plural,
user.getFriendCount()));
int friendsInCommon = user.getFriendsInCommon() == null ? 0 :
user.getFriendsInCommon().size();
if (friendsInCommon > 0) {
tvFriends.setText(tvFriends.getText().toString() +
(friendsInCommon == 1 ?
getResources().getString(
R.string.user_details_activity_friends_in_common_text_single,
friendsInCommon) :
getResources().getString(
R.string.user_details_activity_friends_in_common_text_plural,
friendsInCommon)));
}
if (user.getFriendCount() > 0) {
viewFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startFriendsInCommonActivity();
}
});
viewFriends.setFocusable(true);
ivFriends.setVisibility(View.VISIBLE);
}
if (friendsInCommon > 0) {
psFriends.setVisibility(View.VISIBLE);
psFriends.setUsersAndRemoteResourcesManager(user.getFriendsInCommon(), mRrm);
} else {
tvFriends.setPadding(tvFriends.getPaddingLeft(), tvTodos.getPaddingTop(),
tvFriends.getPaddingRight(), tvTodos.getPaddingBottom());
}
}
} else {
// Haven't done a full load.
if (mStateHolder.getRanOnce()) {
viewProgressBar.setVisibility(View.GONE);
}
}
} else {
// Haven't done a full load.
if (mStateHolder.getRanOnce()) {
viewProgressBar.setVisibility(View.GONE);
}
}
// Regardless of load state, if running a task, show titlebar progress bar.
if (mStateHolder.getIsTaskRunning()) {
setProgressBarIndeterminateVisibility(true);
} else {
setProgressBarIndeterminateVisibility(false);
}
// Disable friend button if running friend task.
if (mStateHolder.getIsRunningFriendTask()) {
btnFriend.setEnabled(false);
} else {
btnFriend.setEnabled(true);
}
}
private void ensureUiPhoto(User user) {
ImageView ivPhoto = (ImageView)findViewById(R.id.userDetailsActivityPhoto);
if (user == null || user.getPhoto() == null) {
ivPhoto.setImageResource(R.drawable.blank_boy);
return;
}
Uri uriPhoto = Uri.parse(user.getPhoto());
if (mRrm.exists(uriPhoto)) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(user
.getPhoto())));
ivPhoto.setImageBitmap(bitmap);
} catch (IOException e) {
setUserPhotoMissing(ivPhoto, user);
}
} else {
mRrm.request(uriPhoto);
setUserPhotoMissing(ivPhoto, user);
}
ivPhoto.postInvalidate();
ivPhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mStateHolder.getLoadType() == LOAD_TYPE_USER_FULL) {
User user = mStateHolder.getUser();
// If "_thumbs" exists, remove it to get the url of the
// full-size image.
String photoUrl = user.getPhoto().replace("_thumbs", "");
// If we're viewing our own page, clicking the thumbnail should send the user
// to our built-in image viewer. Here we can give them the option of setting
// a new photo for themselves.
Intent intent = new Intent(UserDetailsActivity.this, FetchImageForViewIntent.class);
intent.putExtra(FetchImageForViewIntent.IMAGE_URL, photoUrl);
intent.putExtra(FetchImageForViewIntent.PROGRESS_BAR_MESSAGE, getResources()
.getString(R.string.user_activity_fetch_full_image_message));
if (mStateHolder.getIsLoggedInUser()) {
intent.putExtra(FetchImageForViewIntent.LAUNCH_VIEW_INTENT_ON_COMPLETION, false);
startActivityForResult(intent, ACTIVITY_REQUEST_CODE_FETCH_IMAGE);
} else {
startActivity(intent);
}
}
}
});
}
private void setUserPhotoMissing(ImageView ivPhoto, User user) {
if (Foursquare.MALE.equals(user.getGender())) {
ivPhoto.setImageResource(R.drawable.blank_boy);
} else {
ivPhoto.setImageResource(R.drawable.blank_girl);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTasks(null);
return mStateHolder;
}
private void startBadgesActivity() {
if (mStateHolder.getUser() != null) {
Intent intent = new Intent(UserDetailsActivity.this, BadgesActivity.class);
intent.putParcelableArrayListExtra(BadgesActivity.EXTRA_BADGE_ARRAY_LIST_PARCEL,
mStateHolder.getUser().getBadges());
intent.putExtra(BadgesActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
}
private void startMayorshipsActivity() {
if (mStateHolder.getUser() != null) {
Intent intent = new Intent(UserDetailsActivity.this, UserMayorshipsActivity.class);
intent.putExtra(UserMayorshipsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(UserMayorshipsActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
}
private void startCheckinsActivity() {
Intent intent = new Intent(UserDetailsActivity.this, UserHistoryActivity.class);
intent.putExtra(UserHistoryActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
private void startFriendsFollowersActivity() {
User user = mStateHolder.getUser();
Intent intent = null;
if (user.getFollowerCount() > 0) {
intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsFollowersActivity.class);
intent.putExtra(UserDetailsFriendsFollowersActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
} else {
intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsActivity.class);
intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
}
startActivity(intent);
}
private void startAddFriendsActivity() {
Intent intent = new Intent(UserDetailsActivity.this, AddFriendsActivity.class);
startActivity(intent);
}
private void startFriendsInCommonActivity() {
User user = mStateHolder.getUser();
Intent intent = null;
if (user.getFriendsInCommon() != null && user.getFriendsInCommon().size() > 0) {
intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsInCommonActivity.class);
intent.putExtra(UserDetailsFriendsInCommonActivity.EXTRA_USER_PARCEL, mStateHolder.getUser());
} else {
intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsActivity.class);
intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
}
startActivity(intent);
}
private void startTodosActivity() {
Intent intent = new Intent(UserDetailsActivity.this, TodosActivity.class);
intent.putExtra(TodosActivity.INTENT_EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(TodosActivity.INTENT_EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
private void startTipsActivity() {
Intent intent = new Intent(UserDetailsActivity.this, UserDetailsTipsActivity.class);
intent.putExtra(UserDetailsTipsActivity.INTENT_EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(UserDetailsTipsActivity.INTENT_EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
private void startVenueActivity() {
User user = mStateHolder.getUser();
if (user.getCheckin() != null &&
user.getCheckin().getVenue() != null) {
Intent intent = new Intent(this, VenueActivity.class);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, user.getCheckin().getVenue());
startActivity(intent);
}
}
@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);
if (mStateHolder.getIsLoggedInUser()) {
MenuUtils.addPreferencesToMenu(this, menu);
} else {
menu.add(Menu.NONE, MENU_CONTACT, Menu.NONE, R.string.user_details_activity_friends_menu_contact)
.setIcon(R.drawable.ic_menu_user_contact);
if (UserUtils.isFriend(mStateHolder.getUser())) {
menu.add(Menu.NONE, MENU_PINGS, Menu.NONE, R.string.user_details_activity_friends_menu_pings)
.setIcon(android.R.drawable.ic_menu_rotate);
}
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
User user = mStateHolder.getUser();
MenuItem refresh = menu.findItem(MENU_REFRESH);
MenuItem contact = menu.findItem(MENU_CONTACT);
MenuItem pings = menu.findItem(MENU_PINGS);
if (!mStateHolder.getIsRunningUserDetailsTask()) {
refresh.setEnabled(true);
if (contact != null) {
boolean contactEnabled =
!TextUtils.isEmpty(user.getFacebook()) ||
!TextUtils.isEmpty(user.getTwitter()) ||
!TextUtils.isEmpty(user.getEmail()) ||
!TextUtils.isEmpty(user.getPhone());
contact.setEnabled(contactEnabled);
}
if (pings != null) {
pings.setEnabled(true);
}
} else {
refresh.setEnabled(false);
if (contact != null) {
contact.setEnabled(false);
}
if (pings != null) {
pings.setEnabled(false);
}
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
mStateHolder.startTaskUserDetails(this, mStateHolder.getUser().getId());
return true;
case MENU_CONTACT:
showDialog(DIALOG_CONTACTS);
return true;
case MENU_PINGS:
Intent intentPings = new Intent(this, UserDetailsPingsActivity.class);
intentPings.putExtra(UserDetailsPingsActivity.EXTRA_USER_PARCEL, mStateHolder.getUser());
startActivityForResult(intentPings, ACTIVITY_REQUEST_CODE_PINGS);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_REQUEST_CODE_PINGS:
if (resultCode == Activity.RESULT_OK) {
User user = (User)data.getParcelableExtra(UserDetailsPingsActivity.EXTRA_USER_RETURNED);
if (user != null) {
mStateHolder.getUser().getSettings().setGetPings(user.getSettings().getGetPings());
}
}
break;
case ACTIVITY_REQUEST_CODE_FETCH_IMAGE:
if (resultCode == Activity.RESULT_OK) {
String imagePath = data.getStringExtra(FetchImageForViewIntent.EXTRA_SAVED_IMAGE_PATH_RETURNED);
if (mStateHolder.getIsLoggedInUser() && !TextUtils.isEmpty(imagePath)) {
Intent intent = new Intent(this, FullSizeImageActivity.class);
intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_IMAGE_PATH, imagePath);
intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_ALLOW_SET_NEW_PHOTO, true);
startActivityForResult(intent, ACTIVITY_REQUEST_CODE_VIEW_AND_SET_IMAGE);
}
}
break;
case ACTIVITY_REQUEST_CODE_VIEW_AND_SET_IMAGE:
if (resultCode == Activity.RESULT_OK) {
String imageUrl = data.getStringExtra(FullSizeImageActivity.INTENT_RETURN_NEW_PHOTO_URL);
if (!TextUtils.isEmpty(imageUrl)) {
mStateHolder.getUser().setPhoto(imageUrl);
ensureUiPhoto(mStateHolder.getUser());
}
}
break;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_CONTACTS:
final UserContactAdapter adapter = new UserContactAdapter(this, mStateHolder.getUser());
AlertDialog dlgInfo = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.user_details_activity_friends_menu_contact))
.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlg, int pos) {
UserContactAdapter.Action action = (UserContactAdapter.Action)adapter.getItem(pos);
switch (action.getActionId()) {
case UserContactAdapter.Action.ACTION_ID_SMS:
UiUtil.startSmsIntent(UserDetailsActivity.this, mStateHolder.getUser().getPhone());
break;
case UserContactAdapter.Action.ACTION_ID_EMAIL:
UiUtil.startEmailIntent(UserDetailsActivity.this, mStateHolder.getUser().getEmail());
break;
case UserContactAdapter.Action.ACTION_ID_PHONE:
UiUtil.startDialer(UserDetailsActivity.this, mStateHolder.getUser().getPhone());
break;
case UserContactAdapter.Action.ACTION_ID_TWITTER:
UiUtil.startWebIntent(UserDetailsActivity.this, "http://www.twitter.com/" +
mStateHolder.getUser().getTwitter());
break;
case UserContactAdapter.Action.ACTION_ID_FACEBOOK:
UiUtil.startWebIntent(UserDetailsActivity.this, "http://www.facebook.com/profile.php?id=" +
mStateHolder.getUser().getFacebook());
break;
}
}
})
.create();
return dlgInfo;
}
return null;
}
private void onUserDetailsTaskComplete(User user, Exception ex) {
mStateHolder.setIsRunningUserDetailsTask(false);
mStateHolder.setRanOnce(true);
if (user != null) {
mStateHolder.setUser(user);
mStateHolder.setLoadType(LOAD_TYPE_USER_FULL);
} else if (ex != null) {
NotificationsUtil.ToastReasonForFailure(this, ex);
} else {
Toast.makeText(this, "A surprising new error has occurred!", Toast.LENGTH_SHORT).show();
}
ensureUi();
}
/**
* Even if the caller supplies us with a User object parcelable, it won't
* have all the badge etc extra info in it. As soon as the activity starts,
* we launch this task to fetch a full user object, and merge it with
* whatever is already supplied in mUser.
*/
private static class UserDetailsTask extends AsyncTask<String, Void, User> {
private UserDetailsActivity mActivity;
private Exception mReason;
public UserDetailsTask(UserDetailsActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.ensureUi();
}
@Override
protected User doInBackground(String... params) {
try {
return ((Foursquared) mActivity.getApplication()).getFoursquare().user(
params[0],
true,
true,
true,
LocationUtils.createFoursquareLocation(((Foursquared) mActivity
.getApplication()).getLastKnownLocation()));
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(User user) {
if (mActivity != null) {
mActivity.onUserDetailsTaskComplete(user, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onUserDetailsTaskComplete(null, mReason);
}
}
public void setActivity(UserDetailsActivity activity) {
mActivity = activity;
}
}
private void onFriendTaskComplete(User user, int action, Exception ex) {
mStateHolder.setIsRunningFriendTask(false);
// The api isn't returning an updated friend status flag here, so we'll
// overwrite it manually for now, assuming success if the user object
// was not null.
User userCurrent = mStateHolder.getUser();
if (user != null) {
switch (action) {
case StateHolder.TASK_FRIEND_ACCEPT:
userCurrent.setFirstname(user.getFirstname());
userCurrent.setLastname(user.getLastname());
userCurrent.setFriendstatus("friend");
break;
case StateHolder.TASK_FRIEND_ADD:
userCurrent.setFriendstatus("pendingthem");
break;
}
} else {
NotificationsUtil.ToastReasonForFailure(this, ex);
}
ensureUi();
}
private static class FriendTask extends AsyncTask<Void, Void, User> {
private UserDetailsActivity mActivity;
private String mUserId;
private int mAction;
private Exception mReason;
public FriendTask(UserDetailsActivity activity, String userId, int action) {
mActivity = activity;
mUserId = userId;
mAction = action;
}
@Override
protected void onPreExecute() {
mActivity.ensureUi();
}
@Override
protected User doInBackground(Void... params) {
Foursquare foursquare = ((Foursquared) mActivity.getApplication()).getFoursquare();
try {
switch (mAction) {
case StateHolder.TASK_FRIEND_ACCEPT:
return foursquare.friendApprove(mUserId);
case StateHolder.TASK_FRIEND_ADD:
return foursquare.friendSendrequest(mUserId);
default:
throw new FoursquareException("Unknown action type supplied.");
}
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(User user) {
if (mActivity != null) {
mActivity.onFriendTaskComplete(user, mAction, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onFriendTaskComplete(null, mAction, mReason);
}
}
public void setActivity(UserDetailsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
public static final int TASK_FRIEND_ACCEPT = 0;
public static final int TASK_FRIEND_ADD = 1;
private User mUser;
private boolean mIsLoggedInUser;
private UserDetailsTask mTaskUserDetails;
private boolean mIsRunningUserDetailsTask;
private boolean mRanOnce;
private int mLoadType;
private FriendTask mTaskFriend;
private boolean mIsRunningFriendTask;
public StateHolder() {
mIsRunningUserDetailsTask = false;
mIsRunningFriendTask = false;
mIsLoggedInUser = false;
mRanOnce = false;
mLoadType = LOAD_TYPE_USER_NONE;
}
public boolean getIsLoggedInUser() {
return mIsLoggedInUser;
}
public void setIsLoggedInUser(boolean isLoggedInUser) {
mIsLoggedInUser = isLoggedInUser;
}
public User getUser() {
return mUser;
}
public void setUser(User user) {
mUser = user;
}
public int getLoadType() {
return mLoadType;
}
public void setLoadType(int loadType) {
mLoadType = loadType;
}
public void startTaskUserDetails(UserDetailsActivity activity, String userId) {
if (!mIsRunningUserDetailsTask) {
mIsRunningUserDetailsTask = true;
mTaskUserDetails = new UserDetailsTask(activity);
mTaskUserDetails.execute(userId);
}
}
public void startTaskFriend(UserDetailsActivity activity, int action) {
if (!mIsRunningFriendTask) {
mIsRunningFriendTask = true;
mTaskFriend = new FriendTask(activity, mUser.getId(), action);
mTaskFriend.execute();
}
}
public void setActivityForTasks(UserDetailsActivity activity) {
if (mTaskUserDetails != null) {
mTaskUserDetails.setActivity(activity);
}
if (mTaskFriend != null) {
mTaskFriend.setActivity(activity);
}
}
public boolean getIsRunningUserDetailsTask() {
return mIsRunningUserDetailsTask;
}
public void setIsRunningUserDetailsTask(boolean isRunning) {
mIsRunningUserDetailsTask = isRunning;
}
public boolean getRanOnce() {
return mRanOnce;
}
public void setRanOnce(boolean ranOnce) {
mRanOnce = ranOnce;
}
public boolean getIsRunningFriendTask() {
return mIsRunningFriendTask;
}
public void setIsRunningFriendTask(boolean isRunning) {
mIsRunningFriendTask = isRunning;
}
public void cancelTasks() {
if (mTaskUserDetails != null) {
mTaskUserDetails.setActivity(null);
mTaskUserDetails.cancel(true);
}
if (mTaskFriend != null) {
mTaskFriend.setActivity(null);
mTaskFriend.cancel(true);
}
}
public boolean getIsTaskRunning() {
return mIsRunningUserDetailsTask || mIsRunningFriendTask;
}
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
mHandler.post(mRunnableUpdateUserPhoto);
}
}
private Runnable mRunnableUpdateUserPhoto = new Runnable() {
@Override
public void run() {
ensureUiPhoto(mStateHolder.getUser());
}
};
}
| 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.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.StringFormatters;
/**
* Lets the user add a todo for a venue.
*
* @date September 16, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class AddTodoActivity extends Activity {
private static final String TAG = "AddTodoActivity";
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".AddTodoActivity.INTENT_EXTRA_VENUE";
public static final String EXTRA_TODO_RETURNED = Foursquared.PACKAGE_NAME
+ ".AddTodoActivity.EXTRA_TODO_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo_activity);
StateHolder holder = (StateHolder) getLastNonConfigurationInstance();
if (holder != null) {
mStateHolder = holder;
mStateHolder.setActivityForTasks(this);
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE));
} else {
Log.e(TAG, "AddTodoActivity must be given a venue parcel as intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTasks(null);
return mStateHolder;
}
private void ensureUi() {
TextView tvVenueName = (TextView)findViewById(R.id.addTodoActivityVenueName);
tvVenueName.setText(mStateHolder.getVenue().getName());
TextView tvVenueAddress = (TextView)findViewById(R.id.addTodoActivityVenueAddress);
tvVenueAddress.setText(StringFormatters.getVenueLocationCrossStreetOrCity(
mStateHolder.getVenue()));
Button btn = (Button) findViewById(R.id.addTodoActivityButton);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.addTodoActivityText);
String text = et.getText().toString();
mStateHolder.startTaskAddTodo(AddTodoActivity.this, mStateHolder.getVenue().getId(), text);
}
});
if (mStateHolder.getIsRunningTaskVenue()) {
startProgressBar();
}
}
private void startProgressBar() {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, "",
getResources().getString(R.string.add_tip_todo_activity_progress_message));
mDlgProgress.setCancelable(true);
mDlgProgress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Log.e(TAG, "User cancelled add todo.");
mStateHolder.cancelTasks();
}
});
}
mDlgProgress.show();
setProgressBarIndeterminateVisibility(true);
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
setProgressBarIndeterminateVisibility(false);
}
private static class TaskAddTodo extends AsyncTask<Void, Void, Todo> {
private AddTodoActivity mActivity;
private String mVenueId;
private String mTipText;
private Exception mReason;
public TaskAddTodo(AddTodoActivity activity, String venueId, String tipText) {
mActivity = activity;
mVenueId = venueId;
mTipText = tipText;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected Todo doInBackground(Void... params) {
try {
// If the user entered optional text, we need to use one endpoint,
// if not, we need to use mark/todo.
Foursquared foursquared = (Foursquared)mActivity.getApplication();
Todo todo = null;
if (!TextUtils.isEmpty(mTipText)) {
// The returned tip won't have the user object or venue attached to it
// as part of the response. The venue is the parent venue and the user
// is the logged-in user.
Tip tip = foursquared.getFoursquare().addTip(
mVenueId, mTipText, "todo",
LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
// So fetch the full tip for convenience.
Tip tipFull = foursquared.getFoursquare().tipDetail(tip.getId());
// The addtip API returns a tip instead of a todo, unlike the mark/todo endpoint,
// so we create a dummy todo object for now to wrap the tip.
String now = StringFormatters.createServerDateFormatV1();
todo = new Todo();
todo.setId("id_" + now);
todo.setCreated(now);
todo.setTip(tipFull);
Log.i(TAG, "Added todo with wrapper ID: " + todo.getId());
} else {
// No text, so in this case we need to mark the venue itself as a todo.
todo = foursquared.getFoursquare().markTodoVenue(mVenueId);
Log.i(TAG, "Added todo with ID: " + todo.getId());
}
return todo;
} catch (Exception e) {
Log.e(TAG, "Error adding tip.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Todo todo) {
mActivity.stopProgressBar();
mActivity.mStateHolder.setIsRunningTaskAddTip(false);
if (todo != null) {
Intent intent = new Intent();
intent.putExtra(EXTRA_TODO_RETURNED, todo);
mActivity.setResult(Activity.RESULT_OK, intent);
mActivity.finish();
} else {
NotificationsUtil.ToastReasonForFailure(mActivity, mReason);
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
}
@Override
protected void onCancelled() {
mActivity.stopProgressBar();
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
public void setActivity(AddTodoActivity activity) {
mActivity = activity;
}
}
private static final class StateHolder {
private Venue mVenue;
private TaskAddTodo mTaskAddTodo;
private boolean mIsRunningTaskAddTip;
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
}
public boolean getIsRunningTaskVenue() {
return mIsRunningTaskAddTip;
}
public void setIsRunningTaskAddTip(boolean isRunningTaskAddTip) {
mIsRunningTaskAddTip = isRunningTaskAddTip;
}
public void startTaskAddTodo(AddTodoActivity activity, String venueId, String text) {
mIsRunningTaskAddTip = true;
mTaskAddTodo = new TaskAddTodo(activity, venueId, text);
mTaskAddTodo.execute();
}
public void setActivityForTasks(AddTodoActivity activity) {
if (mTaskAddTodo != null) {
mTaskAddTodo.setActivity(activity);
}
}
public void cancelTasks() {
if (mTaskAddTodo != null) {
mTaskAddTodo.cancel(true);
}
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.providers;
import android.content.SearchRecentSuggestionsProvider;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueQuerySuggestionsProvider extends SearchRecentSuggestionsProvider {
public static final String AUTHORITY = "com.joelapenna.foursquared.providers.VenueQuerySuggestionsProvider";
public static final int MODE = DATABASE_MODE_QUERIES;
public VenueQuerySuggestionsProvider() {
super();
setupSuggestions(AUTHORITY, MODE);
}
}
| Java |
/**
* Copyright 2010 Tauno Talimaa
*/
package com.joelapenna.foursquared.providers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.error.LocationException;
import com.joelapenna.foursquared.location.BestLocationListener;
import com.joelapenna.foursquared.location.LocationUtils;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
/**
* A ContentProvider for Foursquare search results.
*
* @author Tauno Talimaa (tauntz@gmail.com)
*/
public class GlobalSearchProvider extends ContentProvider {
// TODO: Implement search for friends by name/phone number/twitter ID when
// API is implemented in Foursquare.java
private static final String TAG = GlobalSearchProvider.class.getSimpleName();
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final String[] QSB_COLUMNS = {
"_id", SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_QUERY,
SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
SearchManager.SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING,
SearchManager.SUGGEST_COLUMN_INTENT_DATA, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
};
private static final int URI_TYPE_QUERY = 1;
private static final int URI_TYPE_SHORTCUT = 2;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(Foursquared.PACKAGE_NAME, SearchManager.SUGGEST_URI_PATH_QUERY + "/*",
URI_TYPE_QUERY);
sUriMatcher.addURI(Foursquared.PACKAGE_NAME,
SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", URI_TYPE_SHORTCUT);
}
public static final String VENUE_DIRECTORY = "venue";
public static final String FRIEND_DIRECTORY = "friend";
// TODO: Use the argument from SUGGEST_PARAMETER_LIMIT from the Uri passed
// to query() instead of the hardcoded value (this is available starting
// from API level 5)
private static final int VENUE_QUERY_LIMIT = 30;
private Foursquare mFoursquare;
@Override
public boolean onCreate() {
synchronized (this) {
if (mFoursquare == null) mFoursquare = Foursquared.createFoursquare(getContext());
}
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
String query = uri.getLastPathSegment();
MatrixCursor cursor = new MatrixCursor(QSB_COLUMNS);
switch (sUriMatcher.match(uri)) {
case URI_TYPE_QUERY:
if (DEBUG) {
Log.d(TAG, "Global search for venue name: " + query);
}
Group<Group<Venue>> venueGroups;
try {
venueGroups = mFoursquare.venues(LocationUtils
.createFoursquareLocation(getBestRecentLocation()), query,
VENUE_QUERY_LIMIT);
} catch (FoursquareError e) {
if (DEBUG) Log.e(TAG, "Could not get venue list for query: " + query, e);
return cursor;
} catch (FoursquareException e) {
if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e);
return cursor;
} catch (LocationException e) {
if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e);
return cursor;
} catch (IOException e) {
if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e);
return cursor;
}
for (int groupIndex = 0; groupIndex < venueGroups.size(); groupIndex++) {
Group<Venue> venueGroup = venueGroups.get(groupIndex);
if (DEBUG) {
Log.d(TAG, venueGroup.size() + " results for group: "
+ venueGroup.getType());
}
for (int venueIndex = 0; venueIndex < venueGroup.size(); venueIndex++) {
Venue venue = venueGroup.get(venueIndex);
if (DEBUG) {
Log.d(TAG, "Venue " + venueIndex + ": " + venue.getName() + " ("
+ venue.getAddress() + ")");
}
cursor.addRow(new Object[] {
venue.getId(),
com.joelapenna.foursquared.R.drawable.venue_shortcut_icon,
venue.getName(), venue.getAddress(), venue.getName(),
venue.getId(), "true", VENUE_DIRECTORY, venue.getId()
});
}
}
break;
case URI_TYPE_SHORTCUT:
if (DEBUG) {
Log.d(TAG, "Global search for venue ID: " + query);
}
Venue venue;
try {
venue = mFoursquare.venue(query, LocationUtils
.createFoursquareLocation(getBestRecentLocation()));
} catch (FoursquareError e) {
if (DEBUG) Log.e(TAG, "Could not get venue details for venue ID: " + query, e);
return cursor;
} catch (LocationException e) {
if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e);
return cursor;
} catch (FoursquareException e) {
if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e);
return cursor;
} catch (IOException e) {
if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e);
return cursor;
}
if (DEBUG) {
Log.d(TAG, "Updated venue details: " + venue.getName() + " ("
+ venue.getAddress() + ")");
}
cursor.addRow(new Object[] {
venue.getId(), com.joelapenna.foursquared.R.drawable.venue_shortcut_icon,
venue.getName(), venue.getAddress(), venue.getName(), venue.getId(),
"true", VENUE_DIRECTORY, venue.getId()
});
break;
case UriMatcher.NO_MATCH:
if (DEBUG) {
Log.d(TAG, "No matching URI for: " + uri);
}
break;
}
return cursor;
}
@Override
public String getType(Uri uri) {
return SearchManager.SUGGEST_MIME_TYPE;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
/**
* Convenience method for getting the most recent Location
*
* @return the most recent Locations
* @throws LocationException when no recent Location could be determined
*/
private Location getBestRecentLocation() throws LocationException {
BestLocationListener locationListener = new BestLocationListener();
locationListener.updateLastKnownLocation((LocationManager) getContext().getSystemService(
Context.LOCATION_SERVICE));
Location location = locationListener.getLastKnownLocation();
if (location != null) {
return location;
}
throw new LocationException();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.util.IconUtils;
import com.joelapenna.foursquared.app.FoursquaredService;
import com.joelapenna.foursquared.error.LocationException;
import com.joelapenna.foursquared.location.BestLocationListener;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.JavaLoggingHandler;
import com.joelapenna.foursquared.util.NullDiskCache;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import android.app.Application;
import android.appwidget.AppWidgetManager;
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.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Foursquared extends Application {
private static final String TAG = "Foursquared";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
static {
Logger.getLogger("com.joelapenna.foursquare").addHandler(new JavaLoggingHandler());
Logger.getLogger("com.joelapenna.foursquare").setLevel(Level.ALL);
}
public static final String PACKAGE_NAME = "com.joelapenna.foursquared";
public static final String INTENT_ACTION_LOGGED_OUT = "com.joelapenna.foursquared.intent.action.LOGGED_OUT";
public static final String INTENT_ACTION_LOGGED_IN = "com.joelapenna.foursquared.intent.action.LOGGED_IN";
private String mVersion = null;
private TaskHandler mTaskHandler;
private HandlerThread mTaskThread;
private SharedPreferences mPrefs;
private RemoteResourceManager mRemoteResourceManager;
private Foursquare mFoursquare;
private BestLocationListener mBestLocationListener = new BestLocationListener();
private boolean mIsFirstRun;
@Override
public void onCreate() {
Log.i(TAG, "Using Debug Server:\t" + FoursquaredSettings.USE_DEBUG_SERVER);
Log.i(TAG, "Using Dumpcatcher:\t" + FoursquaredSettings.USE_DUMPCATCHER);
Log.i(TAG, "Using Debug Log:\t" + DEBUG);
mVersion = getVersionString(this);
// Check if this is a new install by seeing if our preference file exists on disk.
mIsFirstRun = checkIfIsFirstRun();
// Setup Prefs (to load dumpcatcher)
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// Setup some defaults in our preferences if not set yet.
Preferences.setupDefaults(mPrefs, getResources());
// If we're on a high density device, request higher res images. This singleton
// is picked up by the parsers to replace their icon urls with high res versions.
float screenDensity = getApplicationContext().getResources().getDisplayMetrics().density;
IconUtils.get().setRequestHighDensityIcons(screenDensity > 1.0f);
// Setup Dumpcatcher - We've outgrown this infrastructure but we'll
// leave its calls in place for the day that someone pays for some
// appengine quota.
// if (FoursquaredSettings.USE_DUMPCATCHER) {
// Resources resources = getResources();
// new DumpcatcherHelper(Preferences.createUniqueId(mPrefs), resources);
// }
// Sometimes we want the application to do some work on behalf of the
// Activity. Lets do that
// asynchronously.
mTaskThread = new HandlerThread(TAG + "-AsyncThread");
mTaskThread.start();
mTaskHandler = new TaskHandler(mTaskThread.getLooper());
// Set up storage cache.
loadResourceManagers();
// Catch sdcard state changes
new MediaCardStateBroadcastReceiver().register();
// Catch logins or logouts.
new LoggedInOutBroadcastReceiver().register();
// Log into Foursquare, if we can.
loadFoursquare();
}
public boolean isReady() {
return getFoursquare().hasLoginAndPassword() && !TextUtils.isEmpty(getUserId());
}
public Foursquare getFoursquare() {
return mFoursquare;
}
public String getUserId() {
return Preferences.getUserId(mPrefs);
}
public String getUserName() {
return Preferences.getUserName(mPrefs);
}
public String getUserEmail() {
return Preferences.getUserEmail(mPrefs);
}
public String getUserGender() {
return Preferences.getUserGender(mPrefs);
}
public String getVersion() {
if (mVersion != null) {
return mVersion;
} else {
return "";
}
}
public String getLastSeenChangelogVersion() {
return Preferences.getLastSeenChangelogVersion(mPrefs);
}
public void storeLastSeenChangelogVersion(String version) {
Preferences.storeLastSeenChangelogVersion(mPrefs.edit(), version);
}
public boolean getUseNativeImageViewerForFullScreenImages() {
return Preferences.getUseNativeImageViewerForFullScreenImages(mPrefs);
}
public RemoteResourceManager getRemoteResourceManager() {
return mRemoteResourceManager;
}
public BestLocationListener requestLocationUpdates(boolean gps) {
mBestLocationListener.register(
(LocationManager) getSystemService(Context.LOCATION_SERVICE), gps);
return mBestLocationListener;
}
public BestLocationListener requestLocationUpdates(Observer observer) {
mBestLocationListener.addObserver(observer);
mBestLocationListener.register(
(LocationManager) getSystemService(Context.LOCATION_SERVICE), true);
return mBestLocationListener;
}
public void removeLocationUpdates() {
mBestLocationListener
.unregister((LocationManager) getSystemService(Context.LOCATION_SERVICE));
}
public void removeLocationUpdates(Observer observer) {
mBestLocationListener.deleteObserver(observer);
this.removeLocationUpdates();
}
public Location getLastKnownLocation() {
return mBestLocationListener.getLastKnownLocation();
}
public Location getLastKnownLocationOrThrow() throws LocationException {
Location location = mBestLocationListener.getLastKnownLocation();
if (location == null) {
throw new LocationException();
}
return location;
}
public void clearLastKnownLocation() {
mBestLocationListener.clearLastKnownLocation();
}
public void requestStartService() {
mTaskHandler.sendMessage( //
mTaskHandler.obtainMessage(TaskHandler.MESSAGE_START_SERVICE));
}
public void requestUpdateUser() {
mTaskHandler.sendEmptyMessage(TaskHandler.MESSAGE_UPDATE_USER);
}
private void loadFoursquare() {
// Try logging in and setting up foursquare oauth, then user
// credentials.
if (FoursquaredSettings.USE_DEBUG_SERVER) {
mFoursquare = new Foursquare(Foursquare.createHttpApi("10.0.2.2:8080", mVersion, false));
} else {
mFoursquare = new Foursquare(Foursquare.createHttpApi(mVersion, false));
}
if (FoursquaredSettings.DEBUG) Log.d(TAG, "loadCredentials()");
String phoneNumber = mPrefs.getString(Preferences.PREFERENCE_LOGIN, null);
String password = mPrefs.getString(Preferences.PREFERENCE_PASSWORD, null);
mFoursquare.setCredentials(phoneNumber, password);
if (mFoursquare.hasLoginAndPassword()) {
sendBroadcast(new Intent(INTENT_ACTION_LOGGED_IN));
} else {
sendBroadcast(new Intent(INTENT_ACTION_LOGGED_OUT));
}
}
/**
* Provides static access to a Foursquare instance. This instance is
* initiated without user credentials.
*
* @param context the context to use when constructing the Foursquare
* instance
* @return the Foursquare instace
*/
public static Foursquare createFoursquare(Context context) {
String version = getVersionString(context);
if (FoursquaredSettings.USE_DEBUG_SERVER) {
return new Foursquare(Foursquare.createHttpApi("10.0.2.2:8080", version, false));
} else {
return new Foursquare(Foursquare.createHttpApi(version, false));
}
}
/**
* Constructs the version string of the application.
*
* @param context the context to use for getting package info
* @return the versions string of the application
*/
private static String getVersionString(Context context) {
// Get a version string for the app.
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(PACKAGE_NAME, 0);
return PACKAGE_NAME + ":" + String.valueOf(pi.versionCode);
} catch (NameNotFoundException e) {
if (DEBUG) Log.d(TAG, "Could not retrieve package info", e);
throw new RuntimeException(e);
}
}
private void loadResourceManagers() {
// We probably don't have SD card access if we get an
// IllegalStateException. If it did, lets
// at least have some sort of disk cache so that things don't npe when
// trying to access the
// resource managers.
try {
if (DEBUG) Log.d(TAG, "Attempting to load RemoteResourceManager(cache)");
mRemoteResourceManager = new RemoteResourceManager("cache");
} catch (IllegalStateException e) {
if (DEBUG) Log.d(TAG, "Falling back to NullDiskCache for RemoteResourceManager");
mRemoteResourceManager = new RemoteResourceManager(new NullDiskCache());
}
}
public boolean getIsFirstRun() {
return mIsFirstRun;
}
private boolean checkIfIsFirstRun() {
File file = new File(
"/data/data/com.joelapenna.foursquared/shared_prefs/com.joelapenna.foursquared_preferences.xml");
return !file.exists();
}
/**
* Set up resource managers on the application depending on SD card state.
*
* @author Joe LaPenna (joe@joelapenna.com)
*/
private class MediaCardStateBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG)
Log
.d(TAG, "Media state changed, reloading resource managers:"
+ intent.getAction());
if (Intent.ACTION_MEDIA_UNMOUNTED.equals(intent.getAction())) {
getRemoteResourceManager().shutdown();
loadResourceManagers();
} else if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())) {
loadResourceManagers();
}
}
public void register() {
// Register our media card broadcast receiver so we can
// enable/disable the cache as
// appropriate.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
// intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
// intentFilter.addAction(Intent.ACTION_MEDIA_SHARED);
// intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
// intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
// intentFilter.addAction(Intent.ACTION_MEDIA_NOFS);
// intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
// intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addDataScheme("file");
registerReceiver(this, intentFilter);
}
}
private class LoggedInOutBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (INTENT_ACTION_LOGGED_IN.equals(intent.getAction())) {
requestUpdateUser();
}
}
public void register() {
// Register our media card broadcast receiver so we can
// enable/disable the cache as
// appropriate.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(INTENT_ACTION_LOGGED_IN);
intentFilter.addAction(INTENT_ACTION_LOGGED_OUT);
registerReceiver(this, intentFilter);
}
}
private class TaskHandler extends Handler {
private static final int MESSAGE_UPDATE_USER = 1;
private static final int MESSAGE_START_SERVICE = 2;
public TaskHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (DEBUG) Log.d(TAG, "handleMessage: " + msg.what);
switch (msg.what) {
case MESSAGE_UPDATE_USER:
try {
// Update user info
Log.d(TAG, "Updating user.");
// Use location when requesting user information, if we
// have it.
Foursquare.Location location = LocationUtils
.createFoursquareLocation(getLastKnownLocation());
User user = getFoursquare().user(
null, false, false, false, location);
Editor editor = mPrefs.edit();
Preferences.storeUser(editor, user);
editor.commit();
if (location == null) {
// Pump the location listener, we don't have a
// location in our listener yet.
Log.d(TAG, "Priming Location from user city.");
Location primeLocation = new Location("foursquare");
// Very inaccurate, right?
primeLocation.setTime(System.currentTimeMillis());
mBestLocationListener.updateLocation(primeLocation);
}
} catch (FoursquareError e) {
if (DEBUG) Log.d(TAG, "FoursquareError", e);
// TODO Auto-generated catch block
} catch (FoursquareException e) {
if (DEBUG) Log.d(TAG, "FoursquareException", e);
// TODO Auto-generated catch block
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "IOException", e);
// TODO Auto-generated catch block
}
return;
case MESSAGE_START_SERVICE:
Intent serviceIntent = new Intent(Foursquared.this, FoursquaredService.class);
serviceIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
startService(serviceIntent);
return;
}
}
}
}
| 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.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 2008 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.preferences.Preferences;
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.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -added notifications settings (May 21, 2010).
* -removed user update, moved to NotificationSettingsActivity (June 2, 2010)
*/
public class PreferenceActivity extends android.preference.PreferenceActivity {
private static final String TAG = "PreferenceActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int DIALOG_TOS_PRIVACY = 1;
private static final int DIALOG_PROFILE_SETTINGS = 2;
private static final String URL_TOS = "http://foursquare.com/legal/terms";
private static final String URL_PRIVACY = "http://foursquare.com/legal/privacy";
private SharedPreferences mPrefs;
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));
addPreferencesFromResource(R.xml.preferences);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Preference advanceSettingsPreference = getPreferenceScreen().findPreference(
Preferences.PREFERENCE_ADVANCED_SETTINGS);
advanceSettingsPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
((Foursquared) getApplication()).requestUpdateUser();
return false;
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (DEBUG) Log.d(TAG, "onPreferenceTreeClick");
String key = preference.getKey();
if (Preferences.PREFERENCE_LOGOUT.equals(key)) {
mPrefs.edit().clear().commit();
// TODO: If we re-implement oAuth, we'll have to call
// clearAllCrendentials here.
((Foursquared) getApplication()).getFoursquare().setCredentials(null, null);
Intent intent = new Intent(this, LoginActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_CLEAR_TOP);
sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_OUT));
} else if (Preferences.PREFERENCE_ADVANCED_SETTINGS.equals(key)) {
startActivity(new Intent( //
Intent.ACTION_VIEW, Uri.parse(Foursquare.FOURSQUARE_PREFERENCES)));
} else if (Preferences.PREFERENCE_HELP.equals(key)) {
Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra(WebViewActivity.INTENT_EXTRA_URL, "http://foursquare.com/help/android");
startActivity(intent);
} else if (Preferences.PREFERENCE_SEND_FEEDBACK.equals(key)) {
startActivity(new Intent(this, SendLogActivity.class));
} else if (Preferences.PREFERENCE_FRIEND_ADD.equals(key)) {
startActivity(new Intent(this, AddFriendsActivity.class));
} else if (Preferences.PREFERENCE_FRIEND_REQUESTS.equals(key)) {
startActivity(new Intent(this, FriendRequestsActivity.class));
} else if (Preferences.PREFERENCE_CHANGELOG.equals(key)) {
startActivity(new Intent(this, ChangelogActivity.class));
} else if (Preferences.PREFERENCE_PINGS.equals(key)) {
startActivity(new Intent(this, PingsSettingsActivity.class));
} else if (Preferences.PREFERENCE_TOS_PRIVACY.equals(key)) {
showDialog(DIALOG_TOS_PRIVACY);
} else if (Preferences.PREFERENCE_PROFILE_SETTINGS.equals(key)) {
showDialog(DIALOG_PROFILE_SETTINGS);
}
return true;
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_TOS_PRIVACY:
ArrayAdapter<String> adapterTos = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
adapterTos.add(getResources().getString(R.string.preference_activity_tos));
adapterTos.add(getResources().getString(R.string.preference_activity_privacy));
AlertDialog dlgInfo = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.preference_activity_tos_privacy_dlg_title))
.setAdapter(adapterTos, new OnClickListener() {
@Override
public void onClick(DialogInterface dlg, int pos) {
Intent intent = new Intent(PreferenceActivity.this, WebViewActivity.class);
switch (pos) {
case 0:
intent.putExtra(WebViewActivity.INTENT_EXTRA_URL, URL_TOS);
break;
case 1:
intent.putExtra(WebViewActivity.INTENT_EXTRA_URL, URL_PRIVACY);
break;
default:
return;
}
startActivity(intent);
}
})
.create();
return dlgInfo;
case DIALOG_PROFILE_SETTINGS:
String userId = ((Foursquared) getApplication()).getUserId();
String userName = ((Foursquared) getApplication()).getUserName();
String userEmail = ((Foursquared) getApplication()).getUserEmail();
LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.settings_user_info,
(ViewGroup) findViewById(R.id.settings_user_info_layout_root));
TextView tvUserId = (TextView)layout.findViewById(R.id.settings_user_info_label_user_id);
TextView tvUserName = (TextView)layout.findViewById(R.id.settings_user_info_label_user_name);
TextView tvUserEmail = (TextView)layout.findViewById(R.id.settings_user_info_label_user_email);
tvUserId.setText(userId);
tvUserName.setText(userName);
tvUserEmail.setText(userEmail);
AlertDialog dlgProfileSettings = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.preference_activity_profile_settings_dlg_title))
.setView(layout)
.create();
return dlgProfileSettings;
}
return null;
}
}
| 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.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Stats;
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.widget.MapCalloutView;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class SearchVenuesMapActivity extends MapActivity {
public static final String TAG = "SearchVenuesMapActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private String mTappedVenueId;
private Observer mSearchResultsObserver;
private MapCalloutView mCallout;
private MapView mMapView;
private MapController mMapController;
private VenueItemizedOverlay mVenueItemizedOverlay;
private MyLocationOverlay mMyLocationOverlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_map_activity);
initMap();
mCallout = (MapCalloutView) findViewById(R.id.map_callout);
mCallout.setVisibility(View.GONE);
mCallout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SearchVenuesMapActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, mTappedVenueId);
startActivity(intent);
}
});
mSearchResultsObserver = new Observer() {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Observed search results change.");
clearMap();
loadSearchResults(SearchVenuesActivity.searchResultsObservable.getSearchResults());
recenterMap();
}
};
}
@Override
public void onResume() {
super.onResume();
if (DEBUG) Log.d(TAG, "onResume()");
mMyLocationOverlay.enableMyLocation();
// mMyLocationOverlay.enableCompass(); // Disabled due to a sdk 1.5 emulator bug
clearMap();
loadSearchResults(SearchVenuesActivity.searchResultsObservable.getSearchResults());
recenterMap();
SearchVenuesActivity.searchResultsObservable.addObserver(mSearchResultsObserver);
}
@Override
public void onPause() {
super.onPause();
if (DEBUG) Log.d(TAG, "onPause()");
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
SearchVenuesActivity.searchResultsObservable.deleteObserver(mSearchResultsObserver);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
private void initMap() {
mMapView = (MapView)findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mMyLocationOverlay);
mMyLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
if (DEBUG) Log.d(TAG, "runOnFirstFix()");
mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
mMapView.getController().setZoom(16);
}
});
}
private void loadSearchResults(Group<Group<Venue>> searchResults) {
if (searchResults == null) {
if (DEBUG) Log.d(TAG, "no search results. Not loading.");
return;
}
if (DEBUG) Log.d(TAG, "Loading search results");
// Put our location on the map.
mMapView.getOverlays().add(mMyLocationOverlay);
Group<Venue> mappableVenues = new Group<Venue>();
mappableVenues.setType("Mappable Venues");
// For each group of venues.
final int groupCount = searchResults.size();
for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
Group<Venue> group = searchResults.get(groupIndex);
// For each venue group
final int venueCount = group.size();
for (int venueIndex = 0; venueIndex < venueCount; venueIndex++) {
Venue venue = group.get(venueIndex);
if (VenueUtils.hasValidLocation(venue)) {
mappableVenues.add(venue);
}
}
}
// Construct the venues overlay and attach it if we have a mappable set of venues.
if (mappableVenues.size() > 0) {
mVenueItemizedOverlay = new VenueItemizedOverlayWithButton( //
this.getResources().getDrawable(R.drawable.map_marker_blue), //
this.getResources().getDrawable(R.drawable.map_marker_blue_muted));
mVenueItemizedOverlay.setGroup(mappableVenues);
mMapView.getOverlays().add(mVenueItemizedOverlay);
}
}
private void clearMap() {
if (DEBUG) Log.d(TAG, "clearMap()");
mMapView.getOverlays().clear();
mMapView.postInvalidate();
}
private void recenterMap() {
if (DEBUG) Log.d(TAG, "Recentering map.");
GeoPoint center = mMyLocationOverlay.getMyLocation();
// if we have venues in a search result, focus on those.
if (mVenueItemizedOverlay != null && mVenueItemizedOverlay.size() > 0) {
if (DEBUG) Log.d(TAG, "Centering on venues: "
+ String.valueOf(mVenueItemizedOverlay.getLatSpanE6()) + " "
+ String.valueOf(mVenueItemizedOverlay.getLonSpanE6()));
mMapController.setCenter(mVenueItemizedOverlay.getCenter());
mMapController.zoomToSpan(mVenueItemizedOverlay.getLatSpanE6(), mVenueItemizedOverlay
.getLonSpanE6());
} else if (center != null
&& SearchVenuesActivity.searchResultsObservable.getQuery() == SearchVenuesActivity.QUERY_NEARBY) {
if (DEBUG) Log.d(TAG, "recenterMap via MyLocation as we are doing a nearby search");
mMapController.animateTo(center);
mMapController.zoomToSpan(center.getLatitudeE6(), center.getLongitudeE6());
} else if (center != null) {
if (DEBUG) Log.d(TAG, "Fallback, recenterMap via MyLocation overlay");
mMapController.animateTo(center);
mMapController.setZoom(16);
return;
}
}
private class VenueItemizedOverlayWithButton extends VenueItemizedOverlay {
public static final String TAG = "VenueItemizedOverlayWithButton";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Drawable mBeenThereMarker;
public VenueItemizedOverlayWithButton(Drawable defaultMarker, Drawable beenThereMarker) {
super(defaultMarker);
mBeenThereMarker = boundCenterBottom(beenThereMarker);
}
@Override
public OverlayItem createItem(int i) {
VenueOverlayItem item = (VenueOverlayItem)super.createItem(i);
Stats stats = item.getVenue().getStats();
if (stats != null && stats.getBeenhere() != null && stats.getBeenhere().me()) {
if (DEBUG) Log.d(TAG, "using the beenThereMarker for: " + item.getVenue());
item.setMarker(mBeenThereMarker);
}
return item;
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (DEBUG) Log.d(TAG, "onTap: " + this + " " + p + " " + mapView);
mCallout.setVisibility(View.GONE);
return super.onTap(p, mapView);
}
@Override
protected boolean onTap(int i) {
if (DEBUG) Log.d(TAG, "onTap: " + this + " " + i);
VenueOverlayItem item = (VenueOverlayItem)getItem(i);
mTappedVenueId = item.getVenue().getId();
mCallout.setTitle(item.getVenue().getName());
mCallout.setMessage(item.getVenue().getAddress());
mCallout.setVisibility(View.VISIBLE);
return true;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
/**
* Acts as an interface to the TabSpec class for setting the content view.
* The level 3 SDK doesn't support setting a View for the content sections
* of the tab, so we can only use the big native tab style. The level 4
* SDK and up support specifying a custom view for the tab.
*
* @date March 9, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class TabsUtil4 {
private TabsUtil4() {
}
public static void setTabIndicator(TabSpec spec, View view) {
spec.setIndicator(view);
}
public static int getTabCount(TabHost tabHost) {
return tabHost.getTabWidget().getTabCount();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.FoursquaredSettings;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Observable;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.GZIPInputStream;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
class RemoteResourceFetcher extends Observable {
public static final String TAG = "RemoteResourceFetcher";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private DiskCache mResourceCache;
private ExecutorService mExecutor;
private HttpClient mHttpClient;
private ConcurrentHashMap<Request, Callable<Request>> mActiveRequestsMap = new ConcurrentHashMap<Request, Callable<Request>>();
public RemoteResourceFetcher(DiskCache cache) {
mResourceCache = cache;
mHttpClient = createHttpClient();
mExecutor = Executors.newCachedThreadPool();
}
@Override
public void notifyObservers(Object data) {
setChanged();
super.notifyObservers(data);
}
public Future<Request> fetch(Uri uri, String hash) {
Request request = new Request(uri, hash);
synchronized (mActiveRequestsMap) {
Callable<Request> fetcher = newRequestCall(request);
if (mActiveRequestsMap.putIfAbsent(request, fetcher) == null) {
if (DEBUG) Log.d(TAG, "issuing new request for: " + uri);
return mExecutor.submit(fetcher);
} else {
if (DEBUG) Log.d(TAG, "Already have a pending request for: " + uri);
}
}
return null;
}
public void shutdown() {
mExecutor.shutdownNow();
}
private Callable<Request> newRequestCall(final Request request) {
return new Callable<Request>() {
public Request call() {
try {
if (DEBUG) Log.d(TAG, "Requesting: " + request.uri);
HttpGet httpGet = new HttpGet(request.uri.toString());
httpGet.addHeader("Accept-Encoding", "gzip");
HttpResponse response = mHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream is = getUngzippedContent(entity);
mResourceCache.store(request.hash, is);
if (DEBUG) Log.d(TAG, "Request successful: " + request.uri);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "IOException", e);
} finally {
if (DEBUG) Log.d(TAG, "Request finished: " + request.uri);
mActiveRequestsMap.remove(request);
notifyObservers(request.uri);
}
return request;
}
};
}
/**
* Gets the input stream from a response entity. If the entity is gzipped then this will get a
* stream over the uncompressed data.
*
* @param entity the entity whose content should be read
* @return the input stream to read from
* @throws IOException
*/
public static InputStream getUngzippedContent(HttpEntity entity) throws IOException {
InputStream responseStream = entity.getContent();
if (responseStream == null) {
return responseStream;
}
Header header = entity.getContentEncoding();
if (header == null) {
return responseStream;
}
String contentEncoding = header.getValue();
if (contentEncoding == null) {
return responseStream;
}
if (contentEncoding.contains("gzip")) {
responseStream = new GZIPInputStream(responseStream);
}
return responseStream;
}
/**
* Create a thread-safe client. This client does not do redirecting, to allow us to capture
* correct "error" codes.
*
* @return HttpClient
*/
public static final DefaultHttpClient createHttpClient() {
// Shamelessly cribbed from AndroidHttpClient
HttpParams params = new BasicHttpParams();
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
// Default connection and socket timeout of 10 seconds. Tweak to taste.
HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
HttpConnectionParams.setSoTimeout(params, 10 * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192);
// Sets up the http part of the service.
final SchemeRegistry supportedSchemes = new SchemeRegistry();
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
final SocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", sf, 80));
final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,
supportedSchemes);
return new DefaultHttpClient(ccm, params);
}
private static class Request {
Uri uri;
String hash;
public Request(Uri requestUri, String requestHash) {
uri = requestUri;
hash = requestHash;
}
@Override
public int hashCode() {
return hash.hashCode();
}
}
}
| Java |
/**
* Copyright 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.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 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.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 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.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 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 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.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 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 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 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 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 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 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import java.text.ParseException;
import java.util.Comparator;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Updated getVenueDistanceComparator() to do numeric comparison. (2010-03-23)
*/
public class Comparators {
private static Comparator<Venue> sVenueDistanceComparator = null;
private static Comparator<User> sUserRecencyComparator = null;
private static Comparator<Checkin> sCheckinRecencyComparator = null;
private static Comparator<Checkin> sCheckinDistanceComparator = null;
private static Comparator<Tip> sTipRecencyComparator = null;
public static Comparator<Venue> getVenueDistanceComparator() {
if (sVenueDistanceComparator == null) {
sVenueDistanceComparator = new Comparator<Venue>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Venue object1, Venue object2) {
// TODO: In practice we're pretty much guaranteed to get valid locations
// from foursquare, but.. what if we don't, what's a good fail behavior
// here?
try {
int d1 = Integer.parseInt(object1.getDistance());
int d2 = Integer.parseInt(object2.getDistance());
if (d1 < d2) {
return -1;
} else if (d1 > d2) {
return 1;
} else {
return 0;
}
} catch (NumberFormatException ex) {
return object1.getDistance().compareTo(object2.getDistance());
}
}
};
}
return sVenueDistanceComparator;
}
public static Comparator<Venue> getVenueNameComparator() {
if (sVenueDistanceComparator == null) {
sVenueDistanceComparator = new Comparator<Venue>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Venue object1, Venue object2) {
return object1.getName().toLowerCase().compareTo(
object2.getName().toLowerCase());
}
};
}
return sVenueDistanceComparator;
}
public static Comparator<User> getUserRecencyComparator() {
if (sUserRecencyComparator == null) {
sUserRecencyComparator = new Comparator<User>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(User object1, User object2) {
try {
return StringFormatters.DATE_FORMAT.parse(object2.getCreated()).compareTo(
StringFormatters.DATE_FORMAT.parse(object1.getCreated()));
} catch (ParseException e) {
return 0;
}
}
};
}
return sUserRecencyComparator;
}
public static Comparator<Checkin> getCheckinRecencyComparator() {
if (sCheckinRecencyComparator == null) {
sCheckinRecencyComparator = new Comparator<Checkin>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Checkin object1, Checkin object2) {
try {
return StringFormatters.DATE_FORMAT.parse(object2.getCreated()).compareTo(
StringFormatters.DATE_FORMAT.parse(object1.getCreated()));
} catch (ParseException e) {
return 0;
}
}
};
}
return sCheckinRecencyComparator;
}
public static Comparator<Checkin> getCheckinDistanceComparator() {
if (sCheckinDistanceComparator == null) {
sCheckinDistanceComparator = new Comparator<Checkin>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Checkin object1, Checkin object2) {
try {
int d1 = Integer.parseInt(object1.getDistance());
int d2 = Integer.parseInt(object2.getDistance());
if (d1 > d2) {
return 1;
} else if (d2 > d1) {
return -1;
} else {
return 0;
}
} catch (NumberFormatException ex) {
return 0;
}
}
};
}
return sCheckinDistanceComparator;
}
public static Comparator<Tip> getTipRecencyComparator() {
if (sTipRecencyComparator == null) {
sTipRecencyComparator = new Comparator<Tip>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Tip object1, Tip object2) {
try {
return StringFormatters.DATE_FORMAT.parse(object2.getCreated()).compareTo(
StringFormatters.DATE_FORMAT.parse(object1.getCreated()));
} catch (ParseException e) {
return 0;
}
}
};
}
return sTipRecencyComparator;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import 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 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* @date July 24, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class ImageUtils {
private ImageUtils() {
}
public static void resampleImageAndSaveToNewLocation(String pathInput, String pathOutput)
throws Exception
{
Bitmap bmp = resampleImage(pathInput, 640);
OutputStream out = new FileOutputStream(pathOutput);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
}
public static Bitmap resampleImage(String path, int maxDim)
throws Exception {
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bfo);
BitmapFactory.Options optsDownSample = new BitmapFactory.Options();
optsDownSample.inSampleSize = getClosestResampleSize(bfo.outWidth, bfo.outHeight, maxDim);
Bitmap bmpt = BitmapFactory.decodeFile(path, optsDownSample);
Matrix m = new Matrix();
if (bmpt.getWidth() > maxDim || bmpt.getHeight() > maxDim) {
BitmapFactory.Options optsScale = getResampling(bmpt.getWidth(), bmpt.getHeight(), maxDim);
m.postScale((float)optsScale.outWidth / (float)bmpt.getWidth(),
(float)optsScale.outHeight / (float)bmpt.getHeight());
}
int sdk = new Integer(Build.VERSION.SDK).intValue();
if (sdk > 4) {
int rotation = ExifUtils.getExifRotation(path);
if (rotation != 0) {
m.postRotate(rotation);
}
}
return Bitmap.createBitmap(bmpt, 0, 0, bmpt.getWidth(), bmpt.getHeight(), m, true);
}
private static BitmapFactory.Options getResampling(int cx, int cy, int max) {
float scaleVal = 1.0f;
BitmapFactory.Options bfo = new BitmapFactory.Options();
if (cx > cy) {
scaleVal = (float)max / (float)cx;
}
else if (cy > cx) {
scaleVal = (float)max / (float)cy;
}
else {
scaleVal = (float)max / (float)cx;
}
bfo.outWidth = (int)(cx * scaleVal + 0.5f);
bfo.outHeight = (int)(cy * scaleVal + 0.5f);
return bfo;
}
private static int getClosestResampleSize(int cx, int cy, int maxDim) {
int max = Math.max(cx, cy);
int resample = 1;
for (resample = 1; resample < Integer.MAX_VALUE; resample++) {
if (resample * maxDim > max) {
resample--;
break;
}
}
if (resample > 0) {
return resample;
}
return 1;
}
public static BitmapFactory.Options getBitmapDims(String path) throws Exception {
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bfo);
return bfo;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.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.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 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.PreferenceActivity;
import com.joelapenna.foursquared.R;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
/**
* Collection of common functions which are called from the menu
*
* @author Alex Volovoy (avolovoy@gmail.com)
*/
public class MenuUtils {
// Common menu items
private static final int MENU_PREFERENCES = -1;
private static final int MENU_GROUP_SYSTEM = 20;
public static void addPreferencesToMenu(Context context, Menu menu) {
Intent intent = new Intent(context, PreferenceActivity.class);
menu.add(MENU_GROUP_SYSTEM, MENU_PREFERENCES, Menu.CATEGORY_SECONDARY,
R.string.preferences_label).setIcon(R.drawable.ic_menu_preferences).setIntent(
intent);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.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 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.app.Activity;
import android.database.Cursor;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
/**
* Implementation of address book functions for sdk level 5 and above.
*
* @date February 14, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class AddressBookUtils5 extends AddressBookUtils {
public AddressBookUtils5() {
}
@Override
public String getAllContactsPhoneNumbers(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] { Contacts._ID, Phone.NUMBER };
Cursor c = activity.managedQuery(Phone.CONTENT_URI, PROJECTION, null, null, null);
if (c.moveToFirst()) {
sb.append(c.getString(1));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(1));
}
}
return sb.toString();
}
@Override
public String getAllContactsEmailAddresses(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] { Email.DATA };
Cursor c = activity.managedQuery(Email.CONTENT_URI, PROJECTION, null, null, null);
if (c.moveToFirst()) {
sb.append(c.getString(0));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(0));
}
}
return sb.toString();
}
@Override
public AddressBookEmailBuilder getAllContactsEmailAddressesInfo(Activity activity) {
String[] PROJECTION = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, Email.DATA };
Cursor c = activity.managedQuery(Email.CONTENT_URI, PROJECTION, null, null, null);
// We give a list of emails: markww@gmail.com,johndoe@gmail.com,janedoe@gmail.com
// We get back only a list of emails of users that exist on the system (johndoe@gmail.com)
// Iterate over all those returned users, on each iteration, remove from our hashmap.
// Can now use the left over hashmap, which is still in correct order to display invites.
AddressBookEmailBuilder bld = new AddressBookEmailBuilder();
if (c.moveToFirst()) {
bld.addContact(c.getString(1), c.getString(2));
while (c.moveToNext()) {
bld.addContact(c.getString(1), c.getString(2));
}
}
c.close();
return bld;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import 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.foursquare.Foursquare;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import java.io.IOException;
import java.util.Observable;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class UserUtils {
public static void ensureUserPhoto(final Context context, final User user, final boolean DEBUG,
final String TAG) {
Activity activity = ((Activity) context);
final ImageView photo = (ImageView) activity.findViewById(R.id.photo);
if (user.getPhoto() == null) {
photo.setImageResource(R.drawable.blank_boy);
return;
}
final Uri photoUri = Uri.parse(user.getPhoto());
if (photoUri != null) {
RemoteResourceManager userPhotosManager = ((Foursquared) activity.getApplication())
.getRemoteResourceManager();
try {
Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager
.getInputStream(photoUri));
photo.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "photo not already retrieved, requesting: " + photoUri);
userPhotosManager.addObserver(new RemoteResourceManager.ResourceRequestObserver(
photoUri) {
@Override
public void requestReceived(Observable observable, Uri uri) {
observable.deleteObserver(this);
updateUserPhoto(context, photo, uri, user, DEBUG, TAG);
}
});
userPhotosManager.request(photoUri);
}
}
}
private static void updateUserPhoto(Context context, final ImageView photo, final Uri uri,
final User user, final boolean DEBUG, final String TAG) {
final Activity activity = ((Activity) context);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
if (DEBUG) Log.d(TAG, "Loading user photo: " + uri);
RemoteResourceManager userPhotosManager = ((Foursquared) activity
.getApplication()).getRemoteResourceManager();
Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager
.getInputStream(uri));
photo.setImageBitmap(bitmap);
if (DEBUG) Log.d(TAG, "Loaded user photo: " + uri);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "Unable to load user photo: " + uri);
if (Foursquare.MALE.equals(user.getGender())) {
photo.setImageResource(R.drawable.blank_boy);
} else {
photo.setImageResource(R.drawable.blank_girl);
}
} catch (Exception e) {
Log.d(TAG, "Ummm............", e);
}
}
});
}
public static boolean isFriend(User user) {
if (user == null) {
return false;
} else if (TextUtils.isEmpty(user.getFriendstatus())) {
return false;
} else if (user.getFriendstatus().equals("friend")) {
return true;
} else {
return false;
}
}
public static boolean isFollower(User user) {
if (user == null) {
return false;
} else if (TextUtils.isEmpty(user.getFriendstatus())) {
return false;
} else if (user.getFriendstatus().equals("pendingyou")) {
return true;
} else {
return false;
}
}
public static boolean isFriendStatusPendingYou(User user) {
return user != null && user.getFriendstatus() != null &&
user.getFriendstatus().equals("pendingyou");
}
public static boolean isFriendStatusPendingThem(User user) {
return user != null && user.getFriendstatus() != null &&
user.getFriendstatus().equals("pendingthem");
}
public static boolean isFriendStatusFollowingThem(User user) {
return user != null && user.getFriendstatus() != null &&
user.getFriendstatus().equals("followingthem");
}
public static int getDrawableForMeTabByGender(String gender) {
if (gender != null && gender.equals("female")) {
return R.drawable.tab_main_nav_me_girl_selector;
} else {
return R.drawable.tab_main_nav_me_boy_selector;
}
}
public static int getDrawableForMeMenuItemByGender(String gender) {
if (gender == null) {
return R.drawable.ic_menu_myinfo_boy;
} else if (gender.equals("female")) {
return R.drawable.ic_menu_myinfo_girl;
} else {
return R.drawable.ic_menu_myinfo_boy;
}
}
public static boolean getCanHaveFollowers(User user) {
if (user.getTypes() != null && user.getTypes().size() > 0) {
if (user.getTypes().contains("canHaveFollowers")) {
return true;
}
}
return false;
}
public static int getDrawableByGenderForUserThumbnail(User user) {
String gender = user.getGender();
if (gender != null && gender.equals("female")) {
return R.drawable.blank_girl;
} else {
return R.drawable.blank_boy;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
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.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Presents the user with a list of different methods for adding foursquare
* friends.
*
* @date February 11, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class AddFriendsActivity extends Activity {
private static final String TAG = "AddFriendsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
setContentView(R.layout.add_friends_activity);
Button btnAddFriendsByAddressBook = (Button) findViewById(R.id.findFriendsByAddressBook);
btnAddFriendsByAddressBook.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_ADDRESSBOOK);
startActivity(intent);
}
});
Button btnAddFriendsByFacebook = (Button) findViewById(R.id.findFriendsByFacebook);
btnAddFriendsByFacebook.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_FACEBOOK);
startActivity(intent);
}
});
Button btnAddFriendsByTwitter = (Button) findViewById(R.id.findFriendsByTwitter);
btnAddFriendsByTwitter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_TWITTERNAME);
startActivity(intent);
}
});
Button btnAddFriendsByName = (Button) findViewById(R.id.findFriendsByNameOrPhoneNumber);
btnAddFriendsByName.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_NAME_OR_PHONE);
startActivity(intent);
}
});
Button btnInviteFriends = (Button) findViewById(R.id.findFriendsInvite);
btnInviteFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_ADDRESSBOOK_INVITE);
startActivity(intent);
}
});
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquared.location.LocationUtils;
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.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;
/**
* Can be called to execute a shout. Should be presented with the transparent
* dialog theme to appear only as a progress bar. When execution is complete, a
* toast will be shown with a success or error message.
*
* 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 shout worked, and will
* setResult(RESULT_CANCELED) if it did not work.
*
* @date March 10, 2010
* @author Mark Wyszomierski (markww@gmail.com).
*/
public class ShoutExecuteActivity extends Activity {
public static final String TAG = "ShoutExecuteActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_SHOUT = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_SHOUT";
public static final String INTENT_EXTRA_TELL_FRIENDS = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_TELL_FRIENDS";
public static final String INTENT_EXTRA_TELL_FOLLOWERS = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_TELL_FOLLOWERS";
public static final String INTENT_EXTRA_TELL_TWITTER = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_TELL_TWITTER";
public static final String INTENT_EXTRA_TELL_FACEBOOK = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK";
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();
Foursquared foursquared = (Foursquared) getApplication();
Location location = foursquared.getLastKnownLocation();
mStateHolder.startTask(
this,
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.shout_action_label),
getResources().getString(R.string.shout_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;
}
}
private void onShoutComplete(CheckinResult result, Exception ex) {
mStateHolder.setIsRunning(false);
stopProgressBar();
if (result != null) {
Toast.makeText(this, getResources().getString(R.string.shout_exceute_activity_result),
Toast.LENGTH_LONG).show();
setResult(Activity.RESULT_OK);
} else {
NotificationsUtil.ToastReasonForFailure(this, ex);
setResult(Activity.RESULT_CANCELED);
}
finish();
}
private static class ShoutTask extends AsyncTask<Void, Void, CheckinResult> {
private ShoutExecuteActivity mActivity;
private Location mLocation;
private String mShout;
private boolean mTellFriends;
private boolean mTellFollowers;
private boolean mTellTwitter;
private boolean mTellFacebook;
private Exception mReason;
public ShoutTask(ShoutExecuteActivity activity,
Location location,
String shout,
boolean tellFriends,
boolean tellFollowers,
boolean tellTwitter,
boolean tellFacebook) {
mActivity = activity;
mLocation = location;
mShout = shout;
mTellFriends = tellFriends;
mTellFollowers = tellFollowers;
mTellTwitter = tellTwitter;
mTellFacebook = tellFacebook;
}
public void setActivity(ShoutExecuteActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar(mActivity.getResources().getString(
R.string.shout_action_label), mActivity.getResources().getString(
R.string.shout_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(
null,
null,
LocationUtils.createFoursquareLocation(mLocation),
mShout,
!mTellFriends, // (isPrivate)
mTellFollowers,
mTellTwitter,
mTellFacebook);
return result;
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "ShoutTask: Exception checking in.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(CheckinResult result) {
if (DEBUG) Log.d(TAG, "ShoutTask: onPostExecute()");
if (mActivity != null) {
mActivity.onShoutComplete(result, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onShoutComplete(null, new Exception(
"Shout cancelled."));
}
}
}
private static class StateHolder {
private ShoutTask mTask;
private boolean mIsRunning;
public StateHolder() {
mIsRunning = false;
}
public void startTask(ShoutExecuteActivity activity,
Location location,
String shout,
boolean tellFriends,
boolean tellFollowers,
boolean tellTwitter,
boolean tellFacebook) {
mIsRunning = true;
mTask = new ShoutTask(activity, location, shout, tellFriends, tellFollowers,
tellTwitter, tellFacebook);
mTask.execute();
}
public void setActivity(ShoutExecuteActivity activity) {
if (mTask != null) {
mTask.setActivity(activity);
}
}
public boolean getIsRunning() {
return mIsRunning;
}
public void setIsRunning(boolean isRunning) {
mIsRunning = isRunning;
}
public void cancelTasks() {
if (mTask != null && mIsRunning) {
mTask.setActivity(null);
mTask.cancel(true);
}
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
/**
* @date August 2, 2010.
* @author Mark Wyszomierski (markww@gmail.com).
*
*/
public class WebViewActivity extends Activity {
private static final String TAG = "WebViewActivity";
public static final String INTENT_EXTRA_URL = Foursquared.PACKAGE_NAME
+ ".WebViewActivity.INTENT_EXTRA_URL";
private WebView mWebView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
mWebView = new WebView(this);
mWebView.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT));
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new EmbeddedWebViewClient());
if (getIntent().getStringExtra(INTENT_EXTRA_URL) != null) {
mWebView.loadUrl(getIntent().getStringExtra(INTENT_EXTRA_URL));
} else {
Log.e(TAG, "Missing url in intent extras.");
finish();
return;
}
setContentView(mWebView);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class EmbeddedWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
setProgressBarIndeterminateVisibility(true);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
setProgressBarIndeterminateVisibility(false);
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.LinearLayout;
/**
* Renders the result of a checkin using a CheckinResult object. This is called
* from CheckinExecuteActivity. It would be nicer to put this in another activity,
* but right now the CheckinResult is quite large and would require a good amount
* of work to add serializers for all its inner classes. This wouldn't be a huge
* problem, but maintaining it as the classes evolve could more trouble than it's
* worth.
*
* The only way the user can dismiss this dialog is by hitting the 'back' key.
* CheckingExecuteActivity depends on this so it knows when to finish() itself.
*
* @date March 3, 2010.
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*
*/
public class WebViewDialog extends Dialog
{
private WebView mWebView;
private String mTitle;
private String mContent;
public WebViewDialog(Context context, String title, String content) {
super(context, R.style.ThemeCustomDlgBase_ThemeCustomDlg);
mTitle = title;
mContent = content;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview_dialog);
setTitle(mTitle);
mWebView = (WebView)findViewById(R.id.webView);
mWebView.loadDataWithBaseURL("--", mContent, "text/html", "utf-8", "");
LinearLayout llMain = (LinearLayout)findViewById(R.id.llMain);
inflateDialog(llMain);
}
/**
* Force-inflates a dialog main linear-layout to take max available screen space even though
* contents might not occupy full screen size.
*/
public static void inflateDialog(LinearLayout layout) {
WindowManager wm = (WindowManager) layout.getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
layout.setMinimumWidth(display.getWidth() - 30);
layout.setMinimumHeight(display.getHeight() - 40);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.TipUtils;
/**
* Shows actions a user can perform on a tip, which includes marking a tip
* as a to-do, marking a tip as done, un-marking a tip. Marking a tip as
* a to-do will generate a to-do, which has the tip as a child object.
*
* The intent will return a Tip object and a Todo object (if the final state
* of the tip was marked as a Todo). In the case where a Todo is returned,
* the Tip will be the representation as found within the Todo object.
*
* If the user does not modify the tip, no intent data is returned. If the
* final state of the tip was not marked as a to-do, the Todo object is
* not returned.
*
* @date September 2, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class TipActivity extends Activity {
private static final String TAG = "TipActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_TIP_PARCEL = Foursquared.PACKAGE_NAME
+ ".TipActivity.EXTRA_TIP_PARCEL";
public static final String EXTRA_VENUE_CLICKABLE = Foursquared.PACKAGE_NAME
+ ".TipActivity.EXTRA_VENUE_CLICKABLE";
/**
* Always returned if the user modifies the tip in any way. Captures the
* new <status> attribute of the tip. It may not have been changed by the
* user.
*/
public static final String EXTRA_TIP_RETURNED = Foursquared.PACKAGE_NAME
+ ".TipActivity.EXTRA_TIP_RETURNED";
/**
* If the user marks the tip as to-do as the final state, then a to-do object
* will also be returned here. The to-do object has the same tip object as
* returned in EXTRA_TIP_PARCEL_RETURNED as a child member.
*/
public static final String EXTRA_TODO_RETURNED = Foursquared.PACKAGE_NAME
+ ".TipActivity.EXTRA_TODO_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tip_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivityForTipTask(this);
setPreparedResultIntent();
} else {
mStateHolder = new StateHolder();
if (getIntent().getExtras() != null) {
if (getIntent().hasExtra(EXTRA_TIP_PARCEL)) {
Tip tip = getIntent().getExtras().getParcelable(EXTRA_TIP_PARCEL);
mStateHolder.setTip(tip);
} else {
Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras.");
finish();
return;
}
if (getIntent().hasExtra(EXTRA_VENUE_CLICKABLE)) {
mStateHolder.setVenueClickable(
getIntent().getBooleanExtra(EXTRA_VENUE_CLICKABLE, true));
}
} else {
Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public void onResume() {
super.onResume();
if (mStateHolder.getIsRunningTipTask()) {
startProgressBar();
}
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
stopProgressBar();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTipTask(null);
return mStateHolder;
}
private void ensureUi() {
Tip tip = mStateHolder.getTip();
Venue venue = tip.getVenue();
LinearLayout llHeader = (LinearLayout)findViewById(R.id.tipActivityHeaderView);
if (mStateHolder.getVenueClickable()) {
llHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showVenueDetailsActivity(mStateHolder.getTip().getVenue());
}
});
}
ImageView ivVenueChevron = (ImageView)findViewById(R.id.tipActivityVenueChevron);
if (mStateHolder.getVenueClickable()) {
ivVenueChevron.setVisibility(View.VISIBLE);
} else {
ivVenueChevron.setVisibility(View.INVISIBLE);
}
TextView tvTitle = (TextView)findViewById(R.id.tipActivityName);
TextView tvAddress = (TextView)findViewById(R.id.tipActivityAddress);
if (venue != null) {
tvTitle.setText(venue.getName());
tvAddress.setText(
venue.getAddress() +
(TextUtils.isEmpty(venue.getCrossstreet()) ?
"" : " (" + venue.getCrossstreet() + ")"));
} else {
tvTitle.setText("");
tvAddress.setText("");
}
TextView tvBody = (TextView)findViewById(R.id.tipActivityBody);
tvBody.setText(tip.getText());
String created = getResources().getString(
R.string.tip_activity_created,
StringFormatters.getTipAge(getResources(), tip.getCreated()));
TextView tvDate = (TextView)findViewById(R.id.tipActivityDate);
tvDate.setText(created);
TextView tvAuthor = (TextView)findViewById(R.id.tipActivityAuthor);
if (tip.getUser() != null) {
tvAuthor.setText(tip.getUser().getFirstname());
tvAuthor.setClickable(true);
tvAuthor.setFocusable(true);
tvAuthor.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showUserDetailsActivity(mStateHolder.getTip().getUser());
}
});
tvDate.setText(tvDate.getText() + getResources().getString(
R.string.tip_activity_created_by));
} else {
tvAuthor.setText("");
}
Button btn1 = (Button)findViewById(R.id.tipActivityyAddTodoList);
Button btn2 = (Button)findViewById(R.id.tipActivityIveDoneThis);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onBtnTodo();
}
});
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onBtnDone();
}
});
updateButtonStates();
}
private void onBtnTodo() {
Tip tip = mStateHolder.getTip();
if (TipUtils.isTodo(tip)) {
mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(),
TipTask.ACTION_UNMARK_TODO);
} else {
mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(),
TipTask.ACTION_TODO);
}
}
private void onBtnDone() {
Tip tip = mStateHolder.getTip();
if (TipUtils.isDone(tip)) {
mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(),
TipTask.ACTION_UNMARK_DONE);
} else {
mStateHolder.startTipTask(TipActivity.this, mStateHolder.getTip().getId(),
TipTask.ACTION_DONE);
}
}
private void updateButtonStates() {
Button btn1 = (Button)findViewById(R.id.tipActivityyAddTodoList);
Button btn2 = (Button)findViewById(R.id.tipActivityIveDoneThis);
TextView tv = (TextView)findViewById(R.id.tipActivityCongrats);
Tip tip = mStateHolder.getTip();
if (TipUtils.isTodo(tip)) {
btn1.setText(getResources().getString(R.string.tip_activity_btn_tip_1)); // "REMOVE FROM MY TO-DO LIST"
btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_2)); // "I'VE DONE THIS"
btn1.setVisibility(View.VISIBLE);
tv.setVisibility(View.GONE);
} else if (TipUtils.isDone(tip)) {
tv.setText(getResources().getString(R.string.tip_activity_btn_tip_4)); // "CONGRATS! YOU'VE DONE THIS"
btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_3)); // "UNDO THIS"
btn1.setVisibility(View.GONE);
tv.setVisibility(View.VISIBLE);
} else {
btn1.setText(getResources().getString(R.string.tip_activity_btn_tip_0)); // "ADD TO MY TO-DO LIST"
btn2.setText(getResources().getString(R.string.tip_activity_btn_tip_2)); // "I'VE DONE THIS"
btn1.setVisibility(View.VISIBLE);
tv.setVisibility(View.GONE);
}
}
private void showUserDetailsActivity(User user) {
Intent intent = new Intent(this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, user.getId());
startActivity(intent);
}
private void showVenueDetailsActivity(Venue venue) {
Intent intent = new Intent(this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
startActivity(intent);
}
private void startProgressBar() {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, "",
getResources().getString(R.string.tip_activity_progress_message));
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
private void prepareResultIntent(Tip tip, Todo todo) {
Intent intent = new Intent();
intent.putExtra(EXTRA_TIP_RETURNED, tip);
if (todo != null) {
intent.putExtra(EXTRA_TODO_RETURNED, todo); // tip is also a part of the to-do.
}
mStateHolder.setPreparedResult(intent);
setPreparedResultIntent();
}
private void setPreparedResultIntent() {
if (mStateHolder.getPreparedResult() != null) {
setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult());
}
}
private void onTipTaskComplete(FoursquareType tipOrTodo, int type, Exception ex) {
stopProgressBar();
mStateHolder.setIsRunningTipTask(false);
if (tipOrTodo != null) {
// When the tip and todo are serialized into the intent result, the
// link between them will be lost, they'll appear as two separate
// tip object instances (ids etc will all be the same though).
if (tipOrTodo instanceof Tip) {
Tip tip = (Tip)tipOrTodo;
mStateHolder.setTip(tip);
prepareResultIntent(tip, null);
} else {
Todo todo = (Todo)tipOrTodo;
Tip tip = todo.getTip();
mStateHolder.setTip(tip);
prepareResultIntent(tip, todo);
}
} else if (ex != null) {
Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Error updating tip!", Toast.LENGTH_LONG).show();
}
ensureUi();
}
private static class TipTask extends AsyncTask<String, Void, FoursquareType> {
private TipActivity mActivity;
private String mTipId;
private int mTask;
private Exception mReason;
public static final int ACTION_TODO = 0;
public static final int ACTION_DONE = 1;
public static final int ACTION_UNMARK_TODO = 2;
public static final int ACTION_UNMARK_DONE = 3;
public TipTask(TipActivity activity, String tipid, int task) {
mActivity = activity;
mTipId = tipid;
mTask = task;
}
public void setActivity(TipActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected FoursquareType doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
switch (mTask) {
case ACTION_TODO:
return foursquare.markTodo(mTipId); // returns a todo.
case ACTION_DONE:
return foursquare.markDone(mTipId); // returns a tip.
case ACTION_UNMARK_TODO:
return foursquare.unmarkTodo(mTipId); // returns a tip
case ACTION_UNMARK_DONE:
return foursquare.unmarkDone(mTipId); // returns a tip
default:
return null;
}
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "TipTask: Exception performing tip task.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(FoursquareType tipOrTodo) {
if (DEBUG) Log.d(TAG, "TipTask: onPostExecute()");
if (mActivity != null) {
mActivity.onTipTaskComplete(tipOrTodo, mTask, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTipTaskComplete(null, mTask, new Exception("Tip task cancelled."));
}
}
}
private static class StateHolder {
private Tip mTip;
private TipTask mTipTask;
private boolean mIsRunningTipTask;
private boolean mVenueClickable;
private Intent mPreparedResult;
public StateHolder() {
mTip = null;
mPreparedResult = null;
mIsRunningTipTask = false;
mVenueClickable = true;
}
public Tip getTip() {
return mTip;
}
public void setTip(Tip tip) {
mTip = tip;
}
public void startTipTask(TipActivity activity, String tipId, int task) {
mIsRunningTipTask = true;
mTipTask = new TipTask(activity, tipId, task);
mTipTask.execute();
}
public void setActivityForTipTask(TipActivity activity) {
if (mTipTask != null) {
mTipTask.setActivity(activity);
}
}
public void setIsRunningTipTask(boolean isRunningTipTask) {
mIsRunningTipTask = isRunningTipTask;
}
public boolean getIsRunningTipTask() {
return mIsRunningTipTask;
}
public boolean getVenueClickable() {
return mVenueClickable;
}
public void setVenueClickable(boolean venueClickable) {
mVenueClickable = venueClickable;
}
public Intent getPreparedResult() {
return mPreparedResult;
}
public void setPreparedResult(Intent intent) {
mPreparedResult = intent;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Settings;
import com.joelapenna.foursquare.types.User;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* Lets the user set pings on/off for a given friend.
*
* @date September 25, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class UserDetailsPingsActivity extends Activity {
private static final String TAG = "UserDetailsPingsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME
+ ".UserDetailsPingsActivity.EXTRA_USER_PARCEL";
public static final String EXTRA_USER_RETURNED = Foursquared.PACKAGE_NAME
+ ".UserDetailsPingsActivity.EXTRA_USER_RETURNED";
private StateHolder mStateHolder;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.user_details_pings_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
setPreparedResultIntent();
} else {
mStateHolder = new StateHolder();
if (getIntent().getExtras() != null) {
if (getIntent().hasExtra(EXTRA_USER_PARCEL)) {
User user = getIntent().getExtras().getParcelable(EXTRA_USER_PARCEL);
mStateHolder.setUser(user);
} else {
Log.e(TAG, TAG + " requires a user pareclable in its intent extras.");
finish();
return;
}
} else {
Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void ensureUi() {
User user = mStateHolder.getUser();
TextView tv = (TextView)findViewById(R.id.userDetailsPingsActivityDescription);
Button btn = (Button)findViewById(R.id.userDetailsPingsActivityButton);
if (user.getSettings().getGetPings()) {
tv.setText(getString(R.string.user_details_pings_activity_description_on,
user.getFirstname()));
btn.setText(getString(R.string.user_details_pings_activity_pings_off,
user.getFirstname()));
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
mStateHolder.startPingsTask(UserDetailsPingsActivity.this, false);
}
});
} else {
tv.setText(getString(R.string.user_details_pings_activity_description_off,
user.getFirstname()));
btn.setText(getString(R.string.user_details_pings_activity_pings_on,
user.getFirstname()));
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
v.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
mStateHolder.startPingsTask(UserDetailsPingsActivity.this, true);
}
});
}
if (mStateHolder.getIsRunningTaskPings()) {
btn.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
} else {
btn.setEnabled(true);
setProgressBarIndeterminateVisibility(false);
}
}
private void setPreparedResultIntent() {
if (mStateHolder.getPreparedResult() != null) {
setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult());
}
}
private void prepareResultIntent() {
Intent intent = new Intent();
intent.putExtra(EXTRA_USER_RETURNED, mStateHolder.getUser());
mStateHolder.setPreparedResult(intent);
setPreparedResultIntent();
}
private void onTaskPingsComplete(Settings settings, String userId, boolean on, Exception ex) {
mStateHolder.setIsRunningTaskPings(false);
// The api is returning pings = false for all cases, so manually overwrite,
// assume a non-null settings object is success.
if (settings != null) {
settings.setGetPings(on);
mStateHolder.setSettingsResult(settings);
prepareResultIntent();
} else {
Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show();
}
ensureUi();
}
private static class TaskPings extends AsyncTask<Void, Void, Settings> {
private UserDetailsPingsActivity mActivity;
private String mUserId;
private boolean mOn;
private Exception mReason;
public TaskPings(UserDetailsPingsActivity activity, String userId, boolean on) {
mActivity = activity;
mUserId = userId;
mOn = on;
}
public void setActivity(UserDetailsPingsActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.ensureUi();
}
@Override
protected Settings doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.setpings(mUserId, mOn);
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "TipTask: Exception performing tip task.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Settings settings) {
if (mActivity != null) {
mActivity.onTaskPingsComplete(settings, mUserId, mOn, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskPingsComplete(null, mUserId, mOn, new FoursquareException("Tip task cancelled."));
}
}
}
private static class StateHolder {
private User mUser;
private boolean mIsRunningTask;
private Intent mPreparedResult;
private TaskPings mTaskPings;
public StateHolder() {
mPreparedResult = null;
mIsRunningTask = false;
}
public User getUser() {
return mUser;
}
public void setUser(User user) {
mUser = user;
}
public void setSettingsResult(Settings settings) {
mUser.getSettings().setGetPings(settings.getGetPings());
}
public void startPingsTask(UserDetailsPingsActivity activity, boolean on) {
if (!mIsRunningTask) {
mIsRunningTask = true;
mTaskPings = new TaskPings(activity, mUser.getId(), on);
mTaskPings.execute();
}
}
public void setActivity(UserDetailsPingsActivity activity) {
if (mTaskPings != null) {
mTaskPings.setActivity(activity);
}
}
public void setIsRunningTaskPings(boolean isRunning) {
mIsRunningTask = isRunning;
}
public boolean getIsRunningTaskPings() {
return mIsRunningTask;
}
public Intent getPreparedResult() {
return mPreparedResult;
}
public void setPreparedResult(Intent intent) {
mPreparedResult = intent;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.app.LoadableListActivity;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.widget.FriendListAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
/**
* Shows a list of friends for the user id passed as an intent extra.
*
* @date March 9, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserDetailsFriendsActivity extends LoadableListActivity {
static final String TAG = "UserDetailsFriendsActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_USER_ID = Foursquared.PACKAGE_NAME
+ ".UserDetailsFriendsActivity.EXTRA_USER_ID";
public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME
+ ".UserDetailsFriendsActivity.EXTRA_USER_NAME";
public static final String EXTRA_SHOW_ADD_FRIEND_OPTIONS = Foursquared.PACKAGE_NAME
+ ".UserDetailsFriendsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS";
private StateHolder mStateHolder;
private FriendListAdapter mListAdapter;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivityForTaskFriends(this);
} else {
if (getIntent().hasExtra(EXTRA_USER_ID) && getIntent().hasExtra(EXTRA_USER_NAME)) {
mStateHolder = new StateHolder(
getIntent().getStringExtra(EXTRA_USER_ID),
getIntent().getStringExtra(EXTRA_USER_NAME));
} else {
Log.e(TAG, TAG + " requires a userid and username in its intent extras.");
finish();
return;
}
mStateHolder.startTaskFriends(this);
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mStateHolder.cancelTasks();
mListAdapter.removeObserver();
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTaskFriends(null);
return mStateHolder;
}
private void ensureUi() {
mListAdapter = new FriendListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
mListAdapter.setGroup(mStateHolder.getFriends());
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
User user = (User) parent.getAdapter().getItem(position);
Intent intent = new Intent(UserDetailsFriendsActivity.this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user);
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
startActivity(intent);
}
});
if (mStateHolder.getIsRunningFriendsTask()) {
setLoadingView();
} else if (mStateHolder.getFetchedFriendsOnce() && mStateHolder.getFriends().size() == 0) {
setEmptyView();
}
setTitle(getString(R.string.user_details_friends_activity_title, mStateHolder.getUsername()));
}
private void onFriendsTaskComplete(Group<User> group, Exception ex) {
mListAdapter.removeObserver();
mListAdapter = new FriendListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
if (group != null) {
mStateHolder.setFriends(group);
mListAdapter.setGroup(mStateHolder.getFriends());
getListView().setAdapter(mListAdapter);
}
else {
mStateHolder.setFriends(new Group<User>());
mListAdapter.setGroup(mStateHolder.getFriends());
getListView().setAdapter(mListAdapter);
NotificationsUtil.ToastReasonForFailure(this, ex);
}
mStateHolder.setIsRunningFriendsTask(false);
mStateHolder.setFetchedFriendsOnce(true);
// TODO: We can probably tighten this up by just calling ensureUI() again.
if (mStateHolder.getFriends().size() == 0) {
setEmptyView();
}
}
/**
* Gets friends of the current user we're working for.
*/
private static class FriendsTask extends AsyncTask<String, Void, Group<User>> {
private UserDetailsFriendsActivity mActivity;
private Exception mReason;
public FriendsTask(UserDetailsFriendsActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.setLoadingView();
}
@Override
protected Group<User> doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.friends(
params[0], LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<User> users) {
if (mActivity != null) {
mActivity.onFriendsTaskComplete(users, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onFriendsTaskComplete(null, mReason);
}
}
public void setActivity(UserDetailsFriendsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private String mUserId;
private String mUsername;
private Group<User> mFriends;
private FriendsTask mTaskFriends;
private boolean mIsRunningFriendsTask;
private boolean mFetchedFriendsOnce;
public StateHolder(String userId, String username) {
mUserId = userId;
mUsername = username;
mIsRunningFriendsTask = false;
mFetchedFriendsOnce = false;
mFriends = new Group<User>();
}
public String getUsername() {
return mUsername;
}
public Group<User> getFriends() {
return mFriends;
}
public void setFriends(Group<User> friends) {
mFriends = friends;
}
public void startTaskFriends(UserDetailsFriendsActivity activity) {
mIsRunningFriendsTask = true;
mTaskFriends = new FriendsTask(activity);
mTaskFriends.execute(mUserId);
}
public void setActivityForTaskFriends(UserDetailsFriendsActivity activity) {
if (mTaskFriends != null) {
mTaskFriends.setActivity(activity);
}
}
public void setIsRunningFriendsTask(boolean isRunning) {
mIsRunningFriendsTask = isRunning;
}
public boolean getIsRunningFriendsTask() {
return mIsRunningFriendsTask;
}
public void setFetchedFriendsOnce(boolean fetchedOnce) {
mFetchedFriendsOnce = fetchedOnce;
}
public boolean getFetchedFriendsOnce() {
return mFetchedFriendsOnce;
}
public void cancelTasks() {
if (mTaskFriends != null) {
mTaskFriends.setActivity(null);
mTaskFriends.cancel(true);
}
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.app.LoadableListActivity;
import com.joelapenna.foursquared.location.BestLocationListener;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.VenueUtils;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.VenueListAdapter;
import android.app.Activity;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Refactored to allow NearbyVenuesMapActivity to list to search results.
*/
public class NearbyVenuesActivity extends LoadableListActivity {
static final String TAG = "NearbyVenuesActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_STARTUP_GEOLOC_DELAY = Foursquared.PACKAGE_NAME
+ ".NearbyVenuesActivity.INTENT_EXTRA_STARTUP_GEOLOC_DELAY";
private static final int MENU_REFRESH = 0;
private static final int MENU_ADD_VENUE = 1;
private static final int MENU_SEARCH = 2;
private static final int MENU_MAP = 3;
private static final int RESULT_CODE_ACTIVITY_VENUE = 1;
private StateHolder mStateHolder = new StateHolder();
private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver();
private ListView mListView;
private SeparatedListAdapter mListAdapter;
private LinearLayout mFooterView;
private TextView mTextViewFooter;
private Handler mHandler;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
mHandler = new Handler();
mListView = getListView();
mListAdapter = new SeparatedListAdapter(this);
mListView.setAdapter(mListAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Venue venue = (Venue) parent.getAdapter().getItem(position);
startItemActivity(venue);
}
});
// We can dynamically add a footer to our loadable listview.
LayoutInflater inflater = LayoutInflater.from(this);
mFooterView = (LinearLayout)inflater.inflate(R.layout.geo_loc_address_view, null);
mTextViewFooter = (TextView)mFooterView.findViewById(R.id.footerTextView);
LinearLayout llMain = (LinearLayout)findViewById(R.id.main);
llMain.addView(mFooterView);
// Check if we're returning from a configuration change.
if (getLastNonConfigurationInstance() != null) {
if (DEBUG) Log.d(TAG, "Restoring state.");
mStateHolder = (StateHolder) getLastNonConfigurationInstance();
mStateHolder.setActivity(this);
} else {
mStateHolder = new StateHolder();
mStateHolder.setQuery("");
}
// Start a new search if one is not running or we have no results.
if (mStateHolder.getIsRunningTask()) {
setProgressBarIndeterminateVisibility(true);
putSearchResultsInAdapter(mStateHolder.getResults());
ensureTitle(false);
} else if (mStateHolder.getResults().size() == 0) {
long firstLocDelay = 0L;
if (getIntent().getExtras() != null) {
firstLocDelay = getIntent().getLongExtra(INTENT_EXTRA_STARTUP_GEOLOC_DELAY, 0L);
}
startTask(firstLocDelay);
} else {
onTaskComplete(mStateHolder.getResults(), mStateHolder.getReverseGeoLoc(), null);
}
populateFooter(mStateHolder.getReverseGeoLoc());
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public void onResume() {
super.onResume();
if (DEBUG) Log.d(TAG, "onResume");
((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver);
if (isFinishing()) {
mStateHolder.cancelAllTasks();
mListAdapter.removeObserver();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) //
.setIcon(R.drawable.ic_menu_refresh);
menu.add(Menu.NONE, MENU_SEARCH, Menu.NONE, R.string.search_label) //
.setIcon(R.drawable.ic_menu_search) //
.setAlphabeticShortcut(SearchManager.MENU_KEY);
menu.add(Menu.NONE, MENU_ADD_VENUE, Menu.NONE, R.string.nearby_menu_add_venue) //
.setIcon(R.drawable.ic_menu_add);
// Shows a map of all nearby venues, works but not going into this version.
//menu.add(Menu.NONE, MENU_MAP, Menu.NONE, "Map")
// .setIcon(R.drawable.ic_menu_places);
MenuUtils.addPreferencesToMenu(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
if (mStateHolder.getIsRunningTask() == false) {
startTask();
}
return true;
case MENU_SEARCH:
Intent intent = new Intent(NearbyVenuesActivity.this, SearchVenuesActivity.class);
intent.setAction(Intent.ACTION_SEARCH);
startActivity(intent);
return true;
case MENU_ADD_VENUE:
startActivity(new Intent(NearbyVenuesActivity.this, AddVenueActivity.class));
return true;
case MENU_MAP:
startActivity(new Intent(NearbyVenuesActivity.this, NearbyVenuesMapActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public int getNoSearchResultsStringId() {
return R.string.no_nearby_venues;
}
public void putSearchResultsInAdapter(Group<Group<Venue>> searchResults) {
if (DEBUG) Log.d(TAG, "putSearchResultsInAdapter");
mListAdapter.removeObserver();
mListAdapter = new SeparatedListAdapter(this);
if (searchResults != null && searchResults.size() > 0) {
int groupCount = searchResults.size();
for (int groupsIndex = 0; groupsIndex < groupCount; groupsIndex++) {
Group<Venue> group = searchResults.get(groupsIndex);
if (group.size() > 0) {
VenueListAdapter groupAdapter = new VenueListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
groupAdapter.setGroup(group);
if (DEBUG) Log.d(TAG, "Adding Section: " + group.getType());
mListAdapter.addSection(group.getType(), groupAdapter);
}
}
} else {
setEmptyView();
}
mListView.setAdapter(mListAdapter);
}
private void startItemActivity(Venue venue) {
Intent intent = new Intent(NearbyVenuesActivity.this, VenueActivity.class);
if (mStateHolder.isFullyLoadedVenue(venue.getId())) {
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE, venue);
} else {
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
}
startActivityForResult(intent, RESULT_CODE_ACTIVITY_VENUE);
}
private void ensureTitle(boolean finished) {
if (finished) {
setTitle(getString(R.string.title_search_finished_noquery));
} else {
setTitle(getString(R.string.title_search_inprogress_noquery));
}
}
private void populateFooter(String reverseGeoLoc) {
mFooterView.setVisibility(View.VISIBLE);
mTextViewFooter.setText(reverseGeoLoc);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_CODE_ACTIVITY_VENUE:
if (resultCode == Activity.RESULT_OK && data.hasExtra(VenueActivity.EXTRA_VENUE_RETURNED)) {
Venue venue = (Venue)data.getParcelableExtra(VenueActivity.EXTRA_VENUE_RETURNED);
mStateHolder.updateVenue(venue);
mListAdapter.notifyDataSetInvalidated();
}
break;
}
}
private long getClearGeolocationOnSearch() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean cacheGeolocation = settings.getBoolean(Preferences.PREFERENCE_CACHE_GEOLOCATION_FOR_SEARCHES, true);
if (cacheGeolocation) {
return 0L;
} else {
Foursquared foursquared = ((Foursquared) getApplication());
foursquared.clearLastKnownLocation();
foursquared.removeLocationUpdates(mSearchLocationObserver);
foursquared.requestLocationUpdates(mSearchLocationObserver);
return 2000L;
}
}
/** If location changes, auto-start a nearby venues search. */
private class SearchLocationObserver implements Observer {
private boolean mRequestedFirstSearch = false;
@Override
public void update(Observable observable, Object data) {
Location location = (Location) data;
// Fire a search if we haven't done so yet.
if (!mRequestedFirstSearch
&& ((BestLocationListener) observable).isAccurateEnough(location)) {
mRequestedFirstSearch = true;
if (mStateHolder.getIsRunningTask() == false) {
// Since we were told by the system that location has changed, no need to make the
// task wait before grabbing the current location.
mHandler.post(new Runnable() {
public void run() {
startTask(0L);
}
});
}
}
}
}
private void startTask() {
startTask(getClearGeolocationOnSearch());
}
private void startTask(long geoLocDelayTimeInMs) {
if (mStateHolder.getIsRunningTask() == false) {
setProgressBarIndeterminateVisibility(true);
ensureTitle(false);
if (mStateHolder.getResults().size() == 0) {
setLoadingView("");
}
mStateHolder.startTask(this, mStateHolder.getQuery(), geoLocDelayTimeInMs);
}
}
private void onTaskComplete(Group<Group<Venue>> result, String reverseGeoLoc, Exception ex) {
if (result != null) {
mStateHolder.setResults(result);
mStateHolder.setReverseGeoLoc(reverseGeoLoc);
} else {
mStateHolder.setResults(new Group<Group<Venue>>());
NotificationsUtil.ToastReasonForFailure(NearbyVenuesActivity.this, ex);
}
populateFooter(mStateHolder.getReverseGeoLoc());
putSearchResultsInAdapter(mStateHolder.getResults());
setProgressBarIndeterminateVisibility(false);
ensureTitle(true);
mStateHolder.cancelAllTasks();
}
/** Handles the work of finding nearby venues. */
private static class SearchTask extends AsyncTask<Void, Void, Group<Group<Venue>>> {
private NearbyVenuesActivity mActivity;
private Exception mReason = null;
private String mQuery;
private long mSleepTimeInMs;
private Foursquare mFoursquare;
private String mReverseGeoLoc; // Filled in after execution.
private String mNoLocException;
private String mLabelNearby;
public SearchTask(NearbyVenuesActivity activity, String query, long sleepTimeInMs) {
super();
mActivity = activity;
mQuery = query;
mSleepTimeInMs = sleepTimeInMs;
mFoursquare = ((Foursquared)activity.getApplication()).getFoursquare();
mNoLocException = activity.getResources().getString(R.string.nearby_venues_no_location);
mLabelNearby = activity.getResources().getString(R.string.nearby_venues_label_nearby);
}
@Override
public void onPreExecute() {
}
@Override
public Group<Group<Venue>> doInBackground(Void... params) {
try {
// If the user has chosen to clear their geolocation on each search, wait briefly
// for a new fix to come in. The two-second wait time is arbitrary and can be
// changed to something more intelligent.
if (mSleepTimeInMs > 0L) {
Thread.sleep(mSleepTimeInMs);
}
// Get last known location.
Location location = ((Foursquared) mActivity.getApplication()).getLastKnownLocation();
if (location == null) {
throw new FoursquareException(mNoLocException);
}
// Get the venues.
Group<Group<Venue>> results = mFoursquare.venues(LocationUtils
.createFoursquareLocation(location), mQuery, 30);
// Try to get our reverse geolocation.
mReverseGeoLoc = getGeocode(mActivity, location);
return results;
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
public void onPostExecute(Group<Group<Venue>> groups) {
if (mActivity != null) {
mActivity.onTaskComplete(groups, mReverseGeoLoc, mReason);
}
}
private String getGeocode(Context context, Location location) {
Geocoder geocoded = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoded.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
StringBuilder sb = new StringBuilder(128);
sb.append(mLabelNearby);
sb.append(" ");
sb.append(address.getAddressLine(0));
if (addresses.size() > 1) {
sb.append(", ");
sb.append(address.getAddressLine(1));
}
if (addresses.size() > 2) {
sb.append(", ");
sb.append(address.getAddressLine(2));
}
if (!TextUtils.isEmpty(address.getLocality())) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(address.getLocality());
}
return sb.toString();
}
} catch (Exception ex) {
if (DEBUG) Log.d(TAG, "SearchTask: error geocoding current location.", ex);
}
return null;
}
public void setActivity(NearbyVenuesActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private Group<Group<Venue>> mResults;
private String mQuery;
private String mReverseGeoLoc;
private SearchTask mSearchTask;
private Set<String> mFullyLoadedVenueIds;
public StateHolder() {
mResults = new Group<Group<Venue>>();
mSearchTask = null;
mFullyLoadedVenueIds = new HashSet<String>();
}
public String getQuery() {
return mQuery;
}
public void setQuery(String query) {
mQuery = query;
}
public String getReverseGeoLoc() {
return mReverseGeoLoc;
}
public void setReverseGeoLoc(String reverseGeoLoc) {
mReverseGeoLoc = reverseGeoLoc;
}
public Group<Group<Venue>> getResults() {
return mResults;
}
public void setResults(Group<Group<Venue>> results) {
mResults = results;
}
public void startTask(NearbyVenuesActivity activity, String query, long sleepTimeInMs) {
mSearchTask = new SearchTask(activity, query, sleepTimeInMs);
mSearchTask.execute();
}
public boolean getIsRunningTask() {
return mSearchTask != null;
}
public void cancelAllTasks() {
if (mSearchTask != null) {
mSearchTask.cancel(true);
mSearchTask = null;
}
}
public void setActivity(NearbyVenuesActivity activity) {
if (mSearchTask != null) {
mSearchTask.setActivity(activity);
}
}
public void updateVenue(Venue venue) {
for (Group<Venue> it : mResults) {
for (int j = 0; j < it.size(); j++) {
if (it.get(j).getId().equals(venue.getId())) {
// The /venue api call does not supply the venue's distance value,
// so replace it manually here.
Venue replaced = it.get(j);
Venue replacer = VenueUtils.cloneVenue(venue);
replacer.setDistance(replaced.getDistance());
it.set(j, replacer);
mFullyLoadedVenueIds.add(replacer.getId());
}
}
}
}
public boolean isFullyLoadedVenue(String vid) {
return mFullyLoadedVenueIds.contains(vid);
}
}
}
| Java |
package com.joelapenna.foursquared.location;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import java.util.Date;
import java.util.List;
import java.util.Observable;
public class BestLocationListener extends Observable implements LocationListener {
private static final String TAG = "BestLocationListener";
private static final boolean DEBUG = FoursquaredSettings.LOCATION_DEBUG;
public static final long LOCATION_UPDATE_MIN_TIME = 0;
public static final long LOCATION_UPDATE_MIN_DISTANCE = 0;
public static final long SLOW_LOCATION_UPDATE_MIN_TIME = 1000 * 60 * 5;
public static final long SLOW_LOCATION_UPDATE_MIN_DISTANCE = 50;
public static final float REQUESTED_FIRST_SEARCH_ACCURACY_IN_METERS = 100.0f;
public static final int REQUESTED_FIRST_SEARCH_MAX_DELTA_THRESHOLD = 1000 * 60 * 5;
public static final long LOCATION_UPDATE_MAX_DELTA_THRESHOLD = 1000 * 60 * 5;
private Location mLastLocation;
public BestLocationListener() {
super();
}
@Override
public void onLocationChanged(Location location) {
if (DEBUG) Log.d(TAG, "onLocationChanged: " + location);
updateLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
// do nothing.
}
@Override
public void onProviderEnabled(String provider) {
// do nothing.
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// do nothing.
}
synchronized public void onBestLocationChanged(Location location) {
if (DEBUG) Log.d(TAG, "onBestLocationChanged: " + location);
mLastLocation = location;
setChanged();
notifyObservers(location);
}
synchronized public Location getLastKnownLocation() {
return mLastLocation;
}
synchronized public void clearLastKnownLocation() {
mLastLocation = null;
}
public void updateLocation(Location location) {
if (DEBUG) {
Log.d(TAG, "updateLocation: Old: " + mLastLocation);
Log.d(TAG, "updateLocation: New: " + location);
}
// Cases where we only have one or the other.
if (location != null && mLastLocation == null) {
if (DEBUG) Log.d(TAG, "updateLocation: Null last location");
onBestLocationChanged(location);
return;
} else if (location == null) {
if (DEBUG) Log.d(TAG, "updated location is null, doing nothing");
return;
}
long now = new Date().getTime();
long locationUpdateDelta = now - location.getTime();
long lastLocationUpdateDelta = now - mLastLocation.getTime();
boolean locationIsInTimeThreshold = locationUpdateDelta <= LOCATION_UPDATE_MAX_DELTA_THRESHOLD;
boolean lastLocationIsInTimeThreshold = lastLocationUpdateDelta <= LOCATION_UPDATE_MAX_DELTA_THRESHOLD;
boolean locationIsMostRecent = locationUpdateDelta <= lastLocationUpdateDelta;
boolean accuracyComparable = location.hasAccuracy() || mLastLocation.hasAccuracy();
boolean locationIsMostAccurate = false;
if (accuracyComparable) {
// If we have only one side of the accuracy, that one is more
// accurate.
if (location.hasAccuracy() && !mLastLocation.hasAccuracy()) {
locationIsMostAccurate = true;
} else if (!location.hasAccuracy() && mLastLocation.hasAccuracy()) {
locationIsMostAccurate = false;
} else {
// If we have both accuracies, do a real comparison.
locationIsMostAccurate = location.getAccuracy() <= mLastLocation.getAccuracy();
}
}
if (DEBUG) {
Log.d(TAG, "locationIsMostRecent:\t\t\t" + locationIsMostRecent);
Log.d(TAG, "locationUpdateDelta:\t\t\t" + locationUpdateDelta);
Log.d(TAG, "lastLocationUpdateDelta:\t\t" + lastLocationUpdateDelta);
Log.d(TAG, "locationIsInTimeThreshold:\t\t" + locationIsInTimeThreshold);
Log.d(TAG, "lastLocationIsInTimeThreshold:\t" + lastLocationIsInTimeThreshold);
Log.d(TAG, "accuracyComparable:\t\t\t" + accuracyComparable);
Log.d(TAG, "locationIsMostAccurate:\t\t" + locationIsMostAccurate);
}
// Update location if its more accurate and w/in time threshold or if
// the old location is
// too old and this update is newer.
if (accuracyComparable && locationIsMostAccurate && locationIsInTimeThreshold) {
onBestLocationChanged(location);
} else if (locationIsInTimeThreshold && !lastLocationIsInTimeThreshold) {
onBestLocationChanged(location);
}
}
public boolean isAccurateEnough(Location location) {
if (location != null && location.hasAccuracy()
&& location.getAccuracy() <= REQUESTED_FIRST_SEARCH_ACCURACY_IN_METERS) {
long locationUpdateDelta = new Date().getTime() - location.getTime();
if (locationUpdateDelta < REQUESTED_FIRST_SEARCH_MAX_DELTA_THRESHOLD) {
if (DEBUG) Log.d(TAG, "Location is accurate: " + location.toString());
return true;
}
}
if (DEBUG) Log.d(TAG, "Location is not accurate: " + String.valueOf(location));
return false;
}
public void register(LocationManager locationManager, boolean gps) {
if (DEBUG) Log.d(TAG, "Registering this location listener: " + this.toString());
long updateMinTime = SLOW_LOCATION_UPDATE_MIN_TIME;
long updateMinDistance = SLOW_LOCATION_UPDATE_MIN_DISTANCE;
if (gps) {
updateMinTime = LOCATION_UPDATE_MIN_TIME;
updateMinDistance = LOCATION_UPDATE_MIN_DISTANCE;
}
List<String> providers = locationManager.getProviders(true);
int providersCount = providers.size();
for (int i = 0; i < providersCount; i++) {
String providerName = providers.get(i);
if (locationManager.isProviderEnabled(providerName)) {
updateLocation(locationManager.getLastKnownLocation(providerName));
}
// Only register with GPS if we've explicitly allowed it.
if (gps || !LocationManager.GPS_PROVIDER.equals(providerName)) {
locationManager.requestLocationUpdates(providerName, updateMinTime,
updateMinDistance, this);
}
}
}
public void unregister(LocationManager locationManager) {
if (DEBUG) Log.d(TAG, "Unregistering this location listener: " + this.toString());
locationManager.removeUpdates(this);
}
/**
* Updates the current location with the last known location without
* registering any location listeners.
*
* @param locationManager the LocationManager instance from which to
* retrieve the latest known location
*/
synchronized public void updateLastKnownLocation(LocationManager locationManager) {
List<String> providers = locationManager.getProviders(true);
for (int i = 0, providersCount = providers.size(); i < providersCount; i++) {
String providerName = providers.get(i);
if (locationManager.isProviderEnabled(providerName)) {
updateLocation(locationManager.getLastKnownLocation(providerName));
}
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.location;
import com.joelapenna.foursquare.Foursquare.Location;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class LocationUtils {
public static final Location createFoursquareLocation(android.location.Location location) {
if (location == null) {
return new Location(null, null, null, null, null);
}
String geolat = null;
if (location.getLatitude() != 0.0) {
geolat = String.valueOf(location.getLatitude());
}
String geolong = null;
if (location.getLongitude() != 0.0) {
geolong = String.valueOf(location.getLongitude());
}
String geohacc = null;
if (location.hasAccuracy()) {
geohacc = String.valueOf(location.getAccuracy());
}
String geoalt = null;
if (location.hasAccuracy()) {
geoalt = String.valueOf(location.hasAltitude());
}
return new Location(geolat, geolong, geohacc, null, geoalt);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.StringFormatters;
/**
* Lets the user add a tip to a venue.
*
* @date September 16, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class AddTipActivity extends Activity {
private static final String TAG = "AddTipActivity";
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".AddTipActivity.INTENT_EXTRA_VENUE";
public static final String EXTRA_TIP_RETURNED = Foursquared.PACKAGE_NAME
+ ".AddTipActivity.EXTRA_TIP_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_tip_activity);
StateHolder holder = (StateHolder) getLastNonConfigurationInstance();
if (holder != null) {
mStateHolder = holder;
mStateHolder.setActivityForTasks(this);
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE));
} else {
Log.e(TAG, "AddTipActivity must be given a venue parcel as intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTasks(null);
return mStateHolder;
}
private void ensureUi() {
TextView tvVenueName = (TextView)findViewById(R.id.addTipActivityVenueName);
tvVenueName.setText(mStateHolder.getVenue().getName());
TextView tvVenueAddress = (TextView)findViewById(R.id.addTipActivityVenueAddress);
tvVenueAddress.setText(StringFormatters.getVenueLocationCrossStreetOrCity(
mStateHolder.getVenue()));
Button btn = (Button) findViewById(R.id.addTipActivityButton);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.addTipActivityText);
String text = et.getText().toString();
if (!TextUtils.isEmpty(text)) {
mStateHolder.startTaskAddTip(AddTipActivity.this, mStateHolder.getVenue().getId(), text);
} else {
Toast.makeText(AddTipActivity.this, text, Toast.LENGTH_SHORT).show();
}
}
});
if (mStateHolder.getIsRunningTaskVenue()) {
startProgressBar();
}
}
private void startProgressBar() {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, "",
getResources().getString(R.string.add_tip_todo_activity_progress_message));
mDlgProgress.setCancelable(true);
mDlgProgress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Log.e(TAG, "User cancelled add tip.");
mStateHolder.cancelTasks();
}
});
}
mDlgProgress.show();
setProgressBarIndeterminateVisibility(true);
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
setProgressBarIndeterminateVisibility(false);
}
private static class TaskAddTip extends AsyncTask<Void, Void, Tip> {
private AddTipActivity mActivity;
private String mVenueId;
private String mTipText;
private Exception mReason;
public TaskAddTip(AddTipActivity activity, String venueId, String tipText) {
mActivity = activity;
mVenueId = venueId;
mTipText = tipText;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected Tip doInBackground(Void... params) {
try {
// The returned tip won't have the user object or venue attached to it
// as part of the response. The venue is the parent venue and the user
// is the logged-in user.
Foursquared foursquared = (Foursquared)mActivity.getApplication();
Tip tip = foursquared.getFoursquare().addTip(
mVenueId, mTipText, "tip",
LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
// So fetch the full tip for convenience.
Tip tipFull = foursquared.getFoursquare().tipDetail(tip.getId());
return tipFull;
} catch (Exception e) {
Log.e(TAG, "Error adding tip.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Tip tip) {
mActivity.stopProgressBar();
mActivity.mStateHolder.setIsRunningTaskAddTip(false);
if (tip != null) {
Intent intent = new Intent();
intent.putExtra(EXTRA_TIP_RETURNED, tip);
mActivity.setResult(Activity.RESULT_OK, intent);
mActivity.finish();
} else {
NotificationsUtil.ToastReasonForFailure(mActivity, mReason);
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
}
@Override
protected void onCancelled() {
mActivity.stopProgressBar();
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
public void setActivity(AddTipActivity activity) {
mActivity = activity;
}
}
private static final class StateHolder {
private Venue mVenue;
private TaskAddTip mTaskAddTip;
private boolean mIsRunningTaskAddTip;
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
}
public boolean getIsRunningTaskVenue() {
return mIsRunningTaskAddTip;
}
public void setIsRunningTaskAddTip(boolean isRunningTaskAddTip) {
mIsRunningTaskAddTip = isRunningTaskAddTip;
}
public void startTaskAddTip(AddTipActivity activity, String venueId, String text) {
mIsRunningTaskAddTip = true;
mTaskAddTip = new TaskAddTip(activity, venueId, text);
mTaskAddTip.execute();
}
public void setActivityForTasks(AddTipActivity activity) {
if (mTaskAddTip != null) {
mTaskAddTip.setActivity(activity);
}
}
public void cancelTasks() {
if (mTaskAddTip != null) {
mTaskAddTip.cancel(true);
}
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.