code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * TODO put header */ package eu.lighthouselabs.obd.reader.io; import java.io.IOException; import java.util.ArrayList; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.LocationManager; import android.os.Binder; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import eu.lighthouselabs.obd.commands.ObdCommand; import eu.lighthouselabs.obd.commands.protocol.EchoOffObdCommand; import eu.lighthouselabs.obd.commands.protocol.LineFeedOffObdCommand; import eu.lighthouselabs.obd.commands.protocol.ObdResetCommand; import eu.lighthouselabs.obd.commands.protocol.SelectProtocolObdCommand; import eu.lighthouselabs.obd.commands.protocol.TimeoutObdCommand; import eu.lighthouselabs.obd.commands.temperature.AmbientAirTemperatureObdCommand; import eu.lighthouselabs.obd.enums.ObdProtocols; import eu.lighthouselabs.obd.reader.IPostListener; import eu.lighthouselabs.obd.reader.IPostMonitor; import eu.lighthouselabs.obd.reader.R; import eu.lighthouselabs.obd.reader.activity.ConfigActivity; import eu.lighthouselabs.obd.reader.activity.MainActivity; import eu.lighthouselabs.obd.reader.io.ObdCommandJob.ObdCommandJobState; /** * This service is primarily responsible for establishing and maintaining a * permanent connection between the device where the application runs and a more * OBD Bluetooth interface. * * Secondarily, it will serve as a repository of ObdCommandJobs and at the same * time the application state-machine. */ public class ObdGatewayService extends Service { private static final String TAG = "ObdGatewayService"; private IPostListener _callback = null; private final Binder _binder = new LocalBinder(); private AtomicBoolean _isRunning = new AtomicBoolean(false); private NotificationManager _notifManager; private BlockingQueue<ObdCommandJob> _queue = new LinkedBlockingQueue<ObdCommandJob>(); private AtomicBoolean _isQueueRunning = new AtomicBoolean(false); private Long _queueCounter = 0L; private BluetoothDevice _dev = null; private BluetoothSocket _sock = null; /* * http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html * #createRfcommSocketToServiceRecord(java.util.UUID) * * "Hint: If you are connecting to a Bluetooth serial board then try using * the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB. However if * you are connecting to an Android peer then please generate your own * unique UUID." */ private static final UUID MY_UUID = UUID .fromString("00001101-0000-1000-8000-00805F9B34FB"); /** * As long as the service is bound to another component, say an Activity, it * will remain alive. */ @Override public IBinder onBind(Intent intent) { return _binder; } @Override public void onCreate() { _notifManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); showNotification(); } @Override public void onDestroy() { stopService(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "Received start id " + startId + ": " + intent); /* * Register listener Start OBD connection */ startService(); /* * We want this service to continue running until it is explicitly * stopped, so return sticky. */ return START_STICKY; } private void startService() { Log.d(TAG, "Starting service.."); /* * Retrieve preferences */ SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); /* * Let's get the remote Bluetooth device */ String remoteDevice = prefs.getString( ConfigActivity.BLUETOOTH_LIST_KEY, null); if (remoteDevice == null || "".equals(remoteDevice)) { Toast.makeText(this, "No Bluetooth device selected", Toast.LENGTH_LONG).show(); // log error Log.e(TAG, "No Bluetooth device has been selected."); // TODO kill this service gracefully stopService(); } final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); _dev = btAdapter.getRemoteDevice(remoteDevice); /* * TODO put this as deprecated Determine if upload is enabled */ // boolean uploadEnabled = prefs.getBoolean( // ConfigActivity.UPLOAD_DATA_KEY, false); // String uploadUrl = null; // if (uploadEnabled) { // uploadUrl = prefs.getString(ConfigActivity.UPLOAD_URL_KEY, // null); // } /* * Get GPS */ LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); boolean gps = prefs.getBoolean(ConfigActivity.ENABLE_GPS_KEY, false); /* * TODO clean * * Get more preferences */ int period = ConfigActivity.getUpdatePeriod(prefs); double ve = ConfigActivity.getVolumetricEfficieny(prefs); double ed = ConfigActivity.getEngineDisplacement(prefs); boolean imperialUnits = prefs.getBoolean( ConfigActivity.IMPERIAL_UNITS_KEY, false); ArrayList<ObdCommand> cmds = ConfigActivity.getObdCommands(prefs); /* * Establish Bluetooth connection * * Because discovery is a heavyweight procedure for the Bluetooth * adapter, this method should always be called before attempting to * connect to a remote device with connect(). Discovery is not managed * by the Activity, but is run as a system service, so an application * should always call cancel discovery even if it did not directly * request a discovery, just to be sure. If Bluetooth state is not * STATE_ON, this API will return false. * * see * http://developer.android.com/reference/android/bluetooth/BluetoothAdapter * .html#cancelDiscovery() */ Log.d(TAG, "Stopping Bluetooth discovery."); btAdapter.cancelDiscovery(); Toast.makeText(this, "Starting OBD connection..", Toast.LENGTH_SHORT); try { startObdConnection(); } catch (Exception e) { Log.e(TAG, "There was an error while establishing connection. -> " + e.getMessage()); // in case of failure, stop this service. stopService(); } } /** * Start and configure the connection to the OBD interface. * * @throws IOException */ private void startObdConnection() throws IOException { Log.d(TAG, "Starting OBD connection.."); // Instantiate a BluetoothSocket for the remote device and connect it. _sock = _dev.createRfcommSocketToServiceRecord(MY_UUID); _sock.connect(); // Let's configure the connection. Log.d(TAG, "Queing jobs for connection configuration.."); queueJob(new ObdCommandJob(new ObdResetCommand())); queueJob(new ObdCommandJob(new EchoOffObdCommand())); /* * Will send second-time based on tests. * * TODO this can be done w/o having to queue jobs by just issuing * command.run(), command.getResult() and validate the result. */ queueJob(new ObdCommandJob(new EchoOffObdCommand())); queueJob(new ObdCommandJob(new LineFeedOffObdCommand())); queueJob(new ObdCommandJob(new TimeoutObdCommand(62))); // For now set protocol to AUTO queueJob(new ObdCommandJob(new SelectProtocolObdCommand( ObdProtocols.AUTO))); // Job for returning dummy data queueJob(new ObdCommandJob(new AmbientAirTemperatureObdCommand())); Log.d(TAG, "Initialization jobs queued."); // Service is running.. _isRunning.set(true); // Set queue execution counter _queueCounter = 0L; } /** * Runs the queue until the service is stopped */ private void _executeQueue() { Log.d(TAG, "Executing queue.."); _isQueueRunning.set(true); while (!_queue.isEmpty()) { ObdCommandJob job = null; try { job = _queue.take(); // log job Log.d(TAG, "Taking job[" + job.getId() + "] from queue.."); if (job.getState().equals(ObdCommandJobState.NEW)) { Log.d(TAG, "Job state is NEW. Run it.."); job.setState(ObdCommandJobState.RUNNING); job.getCommand().run(_sock.getInputStream(), _sock.getOutputStream()); } else { // log not new job Log.e(TAG, "Job state was not new, so it shouldn't be in queue. BUG ALERT!"); } } catch (Exception e) { job.setState(ObdCommandJobState.EXECUTION_ERROR); Log.e(TAG, "Failed to run command. -> " + e.getMessage()); } if (job != null) { Log.d(TAG, "Job is finished."); job.setState(ObdCommandJobState.FINISHED); _callback.stateUpdate(job); } } _isQueueRunning.set(false); } /** * This method will add a job to the queue while setting its ID to the * internal queue counter. * * @param job * @return */ public Long queueJob(ObdCommandJob job) { _queueCounter++; Log.d(TAG, "Adding job[" + _queueCounter + "] to queue.."); job.setId(_queueCounter); try { _queue.put(job); } catch (InterruptedException e) { job.setState(ObdCommandJobState.QUEUE_ERROR); // log error Log.e(TAG, "Failed to queue job."); } Log.d(TAG, "Job queued successfully."); return _queueCounter; } /** * Stop OBD connection and queue processing. */ public void stopService() { Log.d(TAG, "Stopping service.."); clearNotification(); _queue.removeAll(_queue); // TODO is this safe? _isQueueRunning.set(false); _callback = null; _isRunning.set(false); // close socket try { _sock.close(); } catch (IOException e) { Log.e(TAG, e.getMessage()); } // kill service stopSelf(); } /** * Show a notification while this service is running. */ private void showNotification() { // Set the icon, scrolling text and timestamp Notification notification = new Notification(R.drawable.icon, getText(R.string.service_started), System.currentTimeMillis()); // Launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, getText(R.string.notification_label), getText(R.string.service_started), contentIntent); // Send the notification. _notifManager.notify(R.string.service_started, notification); } /** * Clear notification. */ private void clearNotification() { _notifManager.cancel(R.string.service_started); } /** * TODO put description */ public class LocalBinder extends Binder implements IPostMonitor { public void setListener(IPostListener callback) { _callback = callback; } public boolean isRunning() { return _isRunning.get(); } public void executeQueue() { _executeQueue(); } public void addJobToQueue(ObdCommandJob job) { Log.d(TAG, "Adding job [" + job.getCommand().getName() + "] to queue."); _queue.add(job); if (!_isQueueRunning.get()) _executeQueue(); } } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/io/ObdGatewayService.java
Java
asf20
11,253
/* * TODO put header */ package eu.lighthouselabs.obd.reader.io; import eu.lighthouselabs.obd.commands.ObdCommand; /** * This class represents a job that ObdGatewayService will have to execute and * maintain until the job is finished. It is, thereby, the application * representation of an ObdCommand instance plus a state that will be * interpreted and manipulated by ObdGatewayService. */ public class ObdCommandJob { private Long _id; private ObdCommand _command; private ObdCommandJobState _state; /** * Default ctor. * * @param id the ID of the job. * @param command the ObdCommand to encapsulate. */ public ObdCommandJob(ObdCommand command) { _command = command; _state = ObdCommandJobState.NEW; } public Long getId() { return _id; } public void setId(Long id) { _id = id; } public ObdCommand getCommand() { return _command; } /** * @return job current state. */ public ObdCommandJobState getState() { return _state; } /** * Sets a new job state. * * @param the new job state. */ public void setState(ObdCommandJobState state) { _state = state; } /** * The state of the command. */ public enum ObdCommandJobState { NEW, RUNNING, FINISHED, EXECUTION_ERROR, QUEUE_ERROR } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/io/ObdCommandJob.java
Java
asf20
1,275
/* * TODO put header */ package eu.lighthouselabs.obd.reader.io; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.IBinder; import android.util.Log; import eu.lighthouselabs.obd.reader.IPostListener; import eu.lighthouselabs.obd.reader.IPostMonitor; /** * Service connection for ObdGatewayService. */ public class ObdGatewayServiceConnection implements ServiceConnection { private static final String TAG = "ObdGatewayServiceConnection"; private IPostMonitor _service = null; private IPostListener _listener = null; public void onServiceConnected(ComponentName name, IBinder binder) { _service = (IPostMonitor) binder; _service.setListener(_listener); } public void onServiceDisconnected(ComponentName name) { _service = null; Log.d(TAG, "Service is disconnected."); } /** * @return true if service is running, false otherwise. */ public boolean isRunning() { if (_service == null) { return false; } return _service.isRunning(); } /** * Queue JobObdCommand. * * @param the * job */ public void addJobToQueue(ObdCommandJob job) { if (null != _service) _service.addJobToQueue(job); } /** * Sets a callback in the service. * * @param listener */ public void setServiceListener(IPostListener listener) { _listener = listener; } }
09055199d-
obd-reader/src/eu/lighthouselabs/obd/reader/io/ObdGatewayServiceConnection.java
Java
asf20
1,363
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
1084solid-exp
mock_server/playfoursquare.py
Python
asf20
2,253
/** * 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; }
1084solid-exp
examples/FoursquaredSettings.java
Java
asf20
444
/** * 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 = ""; }
1084solid-exp
examples/TestCredentials.java
Java
asf20
441
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
1084solid-exp
util/generate.py
Python
asf20
772
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
1084solid-exp
util/oget.py
Python
asf20
3,416
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
1084solid-exp
util/gen_parser.py
Python
asf20
4,392
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
1084solid-exp
util/common.py
Python
asf20
2,820
<html> <head> <style type="text/css"> body { background:#fff; color:#000; font:normal 12px Tahoma, Arial, Helvetica, Serif; margin:0px; padding:0px; } h4 { float:left; height:15px; margin:0px 0 0; padding:20px 0 0 10px; font:bold 15px Arial, Helvetica, Serif; } h4 span { float:left; padding:0 5px; margin-top:-10px; } ul { clear:both;margin:0 0 15px; padding:0 0 0 20px; } ul li { margin:0;padding:0; list-style-type:square; margin-bottom:5px; margin-left:20px; font:13px Arial, Helvetica, Serif; } </style> </head> <body> <h4><span>What's new in v2010-10-05?</span></h4> <ul> <li>Badge description now being shown with badge-unlock in post-checkin dialog.</li> <li>Post-checkin scores were not being displayed. Scores were still being recorded for users on the foursquare servers, just not being shown in the results dialog.</li> <li>Venue shortcut-creation bug fixed.</li> <li>URLs now being linked in tip/to-do details screen.</li> </ul> <h4><span>What's new in v2010-09-30</span></h4> <ul> <li>Redesign for most activity screens.</li> <li>Tips and To-do screens added as top-level tabs.</li> <li>Friend information added to venue pages.</li> <li>Can access friend requests from Me tab.</li> <li>Can now refresh Me tab.</li> <li>Switched from xml to json for API calls.</li> </ul> <h4><span>What's new in v2010-08-31</span></h4> <ul> <li>Option for install to SD card (Android 2.2 and above required).</li> <li>Added profile settings information to Preferences page. This is a convenience to let users see what email address and name they're using with their Foursquare account.</li> <li>SSL support.</li> </ul> <h4><span>What's new in v2010-08-05</span></h4> <ul> <li>Click your user photo in the 'Me' tab to set a new photo for yourself.</li> <li>Added an option in preferences to use a Foursquare image viewer for viewing user photos. Un-check "Image Viewing" to use it instead of your phone's native image viewer (default).</li> </ul> <h4><span>What's new in v2010-07-13</span></h4> <ul> <li>Bug fix for new category icons (from 2010-07-12 version) which could cause a force-close on the Places tab.</li> </ul> <h4><span>What's new in v2010-07-12</span></h4> <ul> <li>Friend requests screen now has an input filter at top, should make it easier to locate specific friend requests by name.</li> <li>Places list items now have a 'special' icon when the venue is offering a special. Also now showing a person icon when the venue is trending.</li> <li>High res category icons being used now.</li> <li>Added last n system logs messages to feedback emails to help diagnose application errors.</li> </ul> <h4><span>What's new in v2010-06-28</span></h4> <ul> <li>Showing recent nearby friend checkins on a map. You can find this on the Friends tab, Menu -> More -> Map.</li> <li>Add Friends screen now has an option to find Facebook friends that are also using Foursquare. NOTE: There's a render bug in Android for the Facebook login page which makes the username and password fields misalign when the virtual keypad is displayed, this should be fixed in Android Froyo.</li> </ul> <h4><span>What's new in v2010-06-16</span></h4> <ul> <li>The venue activity has a new menu option called 'Edit Venue' which gives you the option to propose venue edits. These include marking a venue as closed, duplicate, or mislocated. The last option allows you to update all venue information such as address, name, etc.</li> <li>Menu for Friends tab updated to have a 'more' item, which gives the option to sort friend checkins by time or distance.</li> <li>Add friends and find friends items added to 'more' item on Friends tab menu. <li>Refresh menu item moved to first position in Places tab to be consistent with Friends tab.</li> <li>Fixed bug introduced in v2010-06-07 which was formatting the times of checkins incorrectly in the Friends tab.</li> </ul> <h4><span>What's new in v2010-06-07</span></h4> <ul> <li>Now showing the 'add friend' option on user details screens, if not already friends. Should make it easier to build your network. </li> <li>Checkin pings support. A service will wake every N minutes (user-configurable) to check for new checkins from friends. </li> <li>New item on user details pages named 'pings', allows you to turn pings on/off per user. Only applicable if you have enabled ping notifications for yourself. </li> <li>Fix a widget bug that would cause "Application Not Responding" errors.</li> <li>Fixed bug for new users on 1.5. The empty friends screen would crash on some android 1.5 devices.</li> </ul> <h4><span>What's new in v2010-05-11</span></h4> <ul> <li>Friend invites page now has an option to generate a list of contacts not on foursquare for sending email invites to join. This should make it easier to get friends playing along. </li> <li>For new users, the Friends tab will now show a sad face and two buttons 'add friends' & 'friend requests'. This should make it a little easier for new users to start adding friends. </li> <li>Updated default message for venue pages when there are no recent checkins. This was done to make it clear that the venue page is only showing recent checkins, not a total checkin history. </li> <li>Sorting nearby venues by popularity and distance instead of just distance, <a href="http://blog.foursquare.com/post/589698188/weve-just-made-the-places-screen-smarter">read here</a> for more info.</li> <li>Updated to SDK level 6. </li> </ul> <h4><span>v2010-04-23</span></h4> <ul> <li>Default zoom level for venue map is closer to street level.</li> <li>Added a new option through preferences which allows user to clear their current geo location before each venue search. This may help users having issues with geolocation.</li> <li>Updated application icon and menu icons for v6 and newer platforms.</li> <li>Showing reverse geolocation footer on Places tab.</li> </ul> <h4><span>v2010-04-09</span></h4> <ul> <li>New check-in button on venue page.</li> <li>Added a native sign up screen from the login page.</li> <li>Added a 'special' button to the venue page if the venue has a special available.</li> <li>Menu added for Me page, makes it easier to get to the Friend Requests page.</li> <li>Made quick-check-in off by default instead of on. Users can change this in preferences page.</li> <li>Fixed timestamp bug which would place some Droid users in the year 1910.</li> </ul> <h4><span>v2010-03-29</span></h4> <ul> <li>Update for timestamp formatting.</li> </ul> <h4><span>v2010-03-28</span></h4> <ul> <li>Updated checkin screen.</li> </ul> <h4><span>v2010-03-26</span></h4> <ul> <li>Added user photos to venue tips list.</li> <li>Clicking a tip from a venue page displays a new list of options (listing your to-do/completed tips will be added in a future version).</li> <li>Clicking on a nearby special shows venue details for that venue on post-checkin screen.</li> <li>Clicking on mayor photo in post-checkin screen shows user details.</li> <li>Updated distance sorting of venue searches.</li> </ul> <h4><span>v2010-03-23</span></h4> <ul> <li>This "What's New" page.</li> <li>View a user's mayorships through the user details page.</li> <li>History times are now formatted.</li> <li>Choose startup tab (Friends or Places) through the preferences page.</li> <li>Friends checkin tab is sorted by distance and checkin times.</li> <li>Added category icons for user history list.</li> </ul> <h4><span>v2010-03-12</span></h4> <ul> <li>New UI design.</li> <li>See user's mayorhip and badge count.</li> <li>See your own foursquare history.</li> <li>See friends of friends.</li> <li>See contact info of friends.</li> </ul> <h4><span>v2010-03-05</span></h4> <ul> <li>Global Search.</li> <li>Add Friends from Preferences page.</li> <li>Handle friend requests from Preferences page.</li> <li>Click on a user's photo in user details page to see full-size image.</li> </ul> </body> </html>
1084solid-exp
main/assets/changelog-en.html
HTML
asf20
9,096
/** * 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(); } } }
1084solid-exp
main/src/com/facebook/android/FacebookWebViewActivity.java
Java
asf20
14,675
/* * 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; } }
1084solid-exp
main/src/com/facebook/android/FacebookError.java
Java
asf20
1,304
/* * 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; } } }
1084solid-exp
main/src/com/facebook/android/Facebook.java
Java
asf20
10,363
/* * 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(); } }
1084solid-exp
main/src/com/facebook/android/FacebookUtil.java
Java
asf20
7,679
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/FriendsMapActivity.java
Java
asf20
10,764
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/FetchImageForViewIntent.java
Java
asf20
16,224
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/NearbyVenuesMapActivity.java
Java
asf20
8,273
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/AddVenueActivity.java
Java
asf20
30,780
/** * 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) { } } }
1084solid-exp
main/src/com/joelapenna/foursquared/TodosActivity.java
Java
asf20
21,177
/** * 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); } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/UserMayorshipsActivity.java
Java
asf20
10,408
/** * 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); } } } }; }
1084solid-exp
main/src/com/joelapenna/foursquared/VenueActivity.java
Java
asf20
35,457
/** * 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) { } } }
1084solid-exp
main/src/com/joelapenna/foursquared/TipsActivity.java
Java
asf20
19,171
/** * 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(); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/LoginActivity.java
Java
asf20
8,813
/** * 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; } }; }
1084solid-exp
main/src/com/joelapenna/foursquared/SearchVenuesActivity.java
Java
asf20
16,934
/** * 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()); } }; }
1084solid-exp
main/src/com/joelapenna/foursquared/UserDetailsActivity.java
Java
asf20
45,842
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/CategoryPickerDialog.java
Java
asf20
7,738
/** * 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); } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/AddTodoActivity.java
Java
asf20
8,752
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/providers/VenueQuerySuggestionsProvider.java
Java
asf20
566
/** * 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(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/providers/GlobalSearchProvider.java
Java
asf20
8,688
/** * 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; } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/Foursquared.java
Java
asf20
16,225
/** * 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; } } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/VenueTipsActivity.java
Java
asf20
9,133
/** * 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) { } } }
1084solid-exp
main/src/com/joelapenna/foursquared/UserDetailsTipsActivity.java
Java
asf20
20,048
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/PreferenceActivity.java
Java
asf20
8,363
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/SearchVenuesMapActivity.java
Java
asf20
8,920
/** * 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(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/TabsUtil4.java
Java
asf20
841
/** * 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(); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/RemoteResourceFetcher.java
Java
asf20
6,456
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/TipUtils.java
Java
asf20
2,077
/** * 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(); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/AddressBookUtils.java
Java
asf20
902
// 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> * &nbsp; Method encode(String) renamed to encodeString(String).<br> * &nbsp; Method decode(String) renamed to decodeString(String).<br> * &nbsp; New method encode(byte[],int) added.<br> * &nbsp; 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
1084solid-exp
main/src/com/joelapenna/foursquared/util/Base64Coder.java
Java
asf20
6,665
/** * 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."); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/BaseDiskCache.java
Java
asf20
7,683
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/GeoUtils.java
Java
asf20
1,993
/** * 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(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/VenueUtils.java
Java
asf20
5,574
/** * 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); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/RemoteResourceManager.java
Java
asf20
3,347
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/TabsUtil.java
Java
asf20
2,428
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/ExifUtils.java
Java
asf20
1,279
/** * 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() { } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/NullDiskCache.java
Java
asf20
1,637
/** * 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 }; } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/CheckinTimestampSort.java
Java
asf20
2,310
/** * 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); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/NotificationsUtil.java
Java
asf20
2,476
/** * 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()); } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/StringFormatters.java
Java
asf20
8,145
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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/AddressBookEmailBuilder.java
Java
asf20
5,397
/** * 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(); }
1084solid-exp
main/src/com/joelapenna/foursquared/util/DiskCache.java
Java
asf20
539
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/Comparators.java
Java
asf20
6,515
/** * 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() { } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/JavaLoggingHandler.java
Java
asf20
1,135
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/ImageUtils.java
Java
asf20
3,265
/** * 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); // } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/TabsUtil3.java
Java
asf20
860
/** * 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(); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/FeedbackUtils.java
Java
asf20
2,801
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/MenuUtils.java
Java
asf20
894
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/AddressBookUtils3and4.java
Java
asf20
3,066
/** * 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(); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/UiUtil.java
Java
asf20
2,738
/** * 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; } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/AddressBookUtils5.java
Java
asf20
2,701
/** * 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); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/DumpcatcherHelper.java
Java
asf20
4,040
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/util/UserUtils.java
Java
asf20
5,931
/** * 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); } } } } }; }
1084solid-exp
main/src/com/joelapenna/foursquared/CheckinResultDialog.java
Java
asf20
14,998
/** * 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); } }); } }
1084solid-exp
main/src/com/joelapenna/foursquared/AddFriendsActivity.java
Java
asf20
3,791
/** * 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); } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/ShoutExecuteActivity.java
Java
asf20
9,696
/** * 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); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/WebViewActivity.java
Java
asf20
2,497
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/WebViewDialog.java
Java
asf20
2,290
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/TipActivity.java
Java
asf20
16,987
/** * 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; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/UserDetailsPingsActivity.java
Java
asf20
9,363
/** * 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); } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/UserDetailsFriendsActivity.java
Java
asf20
9,270
/** * 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); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/NearbyVenuesActivity.java
Java
asf20
20,287
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)); } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/location/BestLocationListener.java
Java
asf20
7,669
/** * 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); } }
1084solid-exp
main/src/com/joelapenna/foursquared/location/LocationUtils.java
Java
asf20
1,081
/** * 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); } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/AddTipActivity.java
Java
asf20
7,839
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.UserUtils; import com.joelapenna.foursquared.widget.FriendActionableListAdapter; import com.joelapenna.foursquared.widget.SegmentedButton; import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import java.util.ArrayList; import java.util.List; /** * Shows the logged-in user's followers and friends. If the user has no followers, then * they should just be shown UserDetailsFriendsActivity directly. * * @date September 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class UserDetailsFriendsFollowersActivity extends LoadableListActivityWithViewAndHeader { static final String TAG = "UserDetailsFriendsFollowersActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME + ".UserDetailsFriendsFollowersActivity.EXTRA_USER_NAME"; private StateHolder mStateHolder; private FriendActionableListAdapter mListAdapter; private ScrollView mLayoutEmpty; private static final int MENU_REFRESH = 0; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); } else { if (getIntent().hasExtra(EXTRA_USER_NAME)) { mStateHolder = new StateHolder(getIntent().getStringExtra(EXTRA_USER_NAME)); mStateHolder.setFollowersOnly(true); } else { Log.e(TAG, TAG + " requires user name in intent extras."); finish(); return; } } ensureUi(); // Friend tips is shown first by default so auto-fetch it if necessary. if (!mStateHolder.getRanOnceFollowers()) { mStateHolder.startTask(this, true); } } @Override public void onPause() { super.onPause(); if (isFinishing()) { mStateHolder.cancelTasks(); mListAdapter.removeObserver(); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { LayoutInflater inflater = LayoutInflater.from(this); mLayoutEmpty = (ScrollView)inflater.inflate(R.layout.user_details_friends_activity_empty, null); mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); mListAdapter = new FriendActionableListAdapter( this, mButtonRowClickHandler, ((Foursquared) getApplication()).getRemoteResourceManager()); if (mStateHolder.getFollowersOnly()) { mListAdapter.setGroup(mStateHolder.getFollowers()); if (mStateHolder.getFollowers().size() == 0) { if (mStateHolder.getRanOnceFollowers()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } else { mListAdapter.setGroup(mStateHolder.getFriends()); if (mStateHolder.getFriends().size() == 0) { if (mStateHolder.getRanOnceFriends()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); } } } SegmentedButton buttons = getHeaderButton(); buttons.clearButtons(); buttons.addButtons( getString(R.string.user_details_friends_followers_activity_followers), getString(R.string.user_details_friends_followers_activity_friends)); if (mStateHolder.mFollowersOnly) { buttons.setPushedButtonIndex(0); } else { buttons.setPushedButtonIndex(1); } buttons.setOnClickListener(new OnClickListenerSegmentedButton() { @Override public void onClick(int index) { if (index == 0) { mStateHolder.setFollowersOnly(true); mListAdapter.setGroup(mStateHolder.getFollowers()); if (mStateHolder.getFollowers().size() < 1) { if (mStateHolder.getRanOnceFollowers()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTask(UserDetailsFriendsFollowersActivity.this, true); } } } else { mStateHolder.setFollowersOnly(false); mListAdapter.setGroup(mStateHolder.getFriends()); if (mStateHolder.getFriends().size() < 1) { if (mStateHolder.getRanOnceFriends()) { setEmptyView(mLayoutEmpty); } else { setLoadingView(); mStateHolder.startTask(UserDetailsFriendsFollowersActivity.this, false); } } } mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } }); ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setSmoothScrollbarEnabled(false); listView.setItemsCanFocus(false); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { User user = (User) parent.getAdapter().getItem(position); Intent intent = new Intent(UserDetailsFriendsFollowersActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user); startActivity(intent); } }); if (mStateHolder.getIsRunningTaskFollowers() || mStateHolder.getIsRunningTaskFriends()) { setProgressBarIndeterminateVisibility(true); } else { setProgressBarIndeterminateVisibility(false); } setTitle(getString(R.string.user_details_friends_followers_activity_title, mStateHolder.getUsername())); } private FriendActionableListAdapter.ButtonRowClickHandler mButtonRowClickHandler = new FriendActionableListAdapter.ButtonRowClickHandler() { @Override public void onBtnClickBtn1(User user) { if (mStateHolder.getFollowersOnly()) { updateFollowerStatus(user, true); } } @Override public void onBtnClickBtn2(User user) { if (mStateHolder.getFollowersOnly()) { updateFollowerStatus(user, false); } } }; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: mStateHolder.startTask(this, mStateHolder.getFollowersOnly()); return true; } return super.onOptionsItemSelected(item); } /* * Leaving this out for now as it may be very costly for users with very large * friend networks. private void prepareResultIntent() { Group<User> followers = mStateHolder.getFollowers(); Group<User> friends = mStateHolder.getFollowers(); User[] followersArr = (User[])followers.toArray(new User[followers.size()]); User[] friendsArr = (User[])friends.toArray(new User[friends.size()]); Intent intent = new Intent(); intent.putExtra(EXTRA_FOLLOWERS_RETURNED, followersArr); intent.putExtra(EXTRA_FRIENDS_RETURNED, friendsArr); setResult(CODE, intent); } */ private void updateFollowerStatus(User user, boolean approve) { mStateHolder.startTaskUpdateFollower(this, user, approve); if (mStateHolder.getFollowersOnly()) { mListAdapter.notifyDataSetChanged(); if (mStateHolder.getFollowers().size() == 0) { setEmptyView(mLayoutEmpty); } } } private void onStartTaskUsers() { if (mListAdapter != null) { if (mStateHolder.getFollowersOnly()) { mStateHolder.setIsRunningTaskFollowers(true); mListAdapter.setGroup(mStateHolder.getFollowers()); } else { mStateHolder.setIsRunningTaskFriends(true); mListAdapter.setGroup(mStateHolder.getFriends()); } mListAdapter.notifyDataSetChanged(); } setProgressBarIndeterminateVisibility(true); setLoadingView(); } private void onStartUpdateFollower() { setProgressBarIndeterminateVisibility(true); } private void onTaskUsersComplete(Group<User> group, boolean friendsOnly, Exception ex) { SegmentedButton buttons = getHeaderButton(); boolean update = false; if (group != null) { if (friendsOnly) { mStateHolder.setFollowers(group); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getFollowers()); update = true; } } else { mStateHolder.setFriends(group); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getFriends()); update = true; } } } else { if (friendsOnly) { mStateHolder.setFollowers(new Group<User>()); if (buttons.getSelectedButtonIndex() == 0) { mListAdapter.setGroup(mStateHolder.getFollowers()); update = true; } } else { mStateHolder.setFriends(new Group<User>()); if (buttons.getSelectedButtonIndex() == 1) { mListAdapter.setGroup(mStateHolder.getFriends()); update = true; } } NotificationsUtil.ToastReasonForFailure(this, ex); } if (friendsOnly) { mStateHolder.setIsRunningTaskFollowers(false); mStateHolder.setRanOnceFollowers(true); if (mStateHolder.getFollowers().size() == 0 && buttons.getSelectedButtonIndex() == 0) { setEmptyView(mLayoutEmpty); } } else { mStateHolder.setIsRunningTaskFriends(false); mStateHolder.setRanOnceFriends(true); if (mStateHolder.getFriends().size() == 0 && buttons.getSelectedButtonIndex() == 1) { setEmptyView(mLayoutEmpty); } } if (update) { mListAdapter.notifyDataSetChanged(); getListView().setSelection(0); } if (!mStateHolder.areAnyTasksRunning()) { setProgressBarIndeterminateVisibility(false); } } private void onTaskUpdateFollowerComplete(TaskUpdateFollower task, User user, boolean approve, Exception ex) { if (user != null) { if (UserUtils.isFriend(user)) { if (mStateHolder.addFriend(user)) { mListAdapter.notifyDataSetChanged(); } } } mStateHolder.removeTaskUpdateFollower(task); if (!mStateHolder.areAnyTasksRunning()) { setProgressBarIndeterminateVisibility(false); } } private static class TaskUsers extends AsyncTask<Void, Void, Group<User>> { private UserDetailsFriendsFollowersActivity mActivity; private boolean mFollowersOnly; private Exception mReason; public TaskUsers(UserDetailsFriendsFollowersActivity activity, boolean followersOnly) { mActivity = activity; mFollowersOnly = followersOnly; } @Override protected void onPreExecute() { mActivity.onStartTaskUsers(); } @Override protected Group<User> doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); Location loc = foursquared.getLastKnownLocation(); if (mFollowersOnly) { return foursquare.friendRequests(); } else { return foursquare.friends(null, LocationUtils.createFoursquareLocation(loc)); } } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(Group<User> users) { if (mActivity != null) { mActivity.onTaskUsersComplete(users, mFollowersOnly, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskUsersComplete(null, mFollowersOnly, mReason); } } public void setActivity(UserDetailsFriendsFollowersActivity activity) { mActivity = activity; } } private static class TaskUpdateFollower extends AsyncTask<Void, Void, User> { private UserDetailsFriendsFollowersActivity mActivity; private String mUserId; private boolean mApprove; private Exception mReason; private boolean mDone; public TaskUpdateFollower(UserDetailsFriendsFollowersActivity activity, String userId, boolean approve) { mActivity = activity; mUserId = userId; mApprove = approve; mDone = false; } @Override protected void onPreExecute() { mActivity.onStartUpdateFollower(); } @Override protected User doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); if (mApprove) { return foursquare.friendApprove(mUserId); } else { return foursquare.friendDeny(mUserId); } } catch (Exception e) { mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (mActivity != null) { mActivity.onTaskUpdateFollowerComplete(this, user, mApprove, mReason); } mDone = true; } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskUpdateFollowerComplete(this, null, mApprove, mReason); } mDone = true; } public void setActivity(UserDetailsFriendsFollowersActivity activity) { mActivity = activity; } public boolean getIsDone() { return mDone; } } private static class StateHolder { private String mUsername; private Group<User> mFollowers; private Group<User> mFriends; private TaskUsers mTaskFollowers; private TaskUsers mTaskFriends; private boolean mIsRunningTaskFollowers; private boolean mIsRunningTaskFriends; private boolean mFollowersOnly; private boolean mRanOnceFollowers; private boolean mRanOnceFriends; private List<TaskUpdateFollower> mTasksUpdateFollowers; public StateHolder(String username) { mUsername = username; mIsRunningTaskFollowers = false; mIsRunningTaskFriends = false; mRanOnceFriends = false; mRanOnceFollowers = false; mFollowers = new Group<User>(); mFriends = new Group<User>(); mFollowersOnly = true; mTasksUpdateFollowers = new ArrayList<TaskUpdateFollower>(); } public String getUsername() { return mUsername; } public Group<User> getFollowers() { return mFollowers; } public void setFollowers(Group<User> followers) { mFollowers = followers; } public Group<User> getFriends() { return mFriends; } public void setFriends(Group<User> friends) { mFriends = friends; } public void startTask(UserDetailsFriendsFollowersActivity activity, boolean followersOnly) { if (followersOnly) { if (mIsRunningTaskFollowers) { return; } mIsRunningTaskFollowers = true; mTaskFollowers = new TaskUsers(activity, followersOnly); mTaskFollowers.execute(); } else { if (mIsRunningTaskFriends) { return; } mIsRunningTaskFriends = true; mTaskFriends = new TaskUsers(activity, followersOnly); mTaskFriends.execute(); } } public void startTaskUpdateFollower(UserDetailsFriendsFollowersActivity activity, User user, boolean approve) { for (User it : mFollowers) { if (it.getId().equals(user.getId())) { mFollowers.remove(it); break; } } TaskUpdateFollower task = new TaskUpdateFollower(activity, user.getId(), approve); task.execute(); mTasksUpdateFollowers.add(task); } public void setActivity(UserDetailsFriendsFollowersActivity activity) { if (mTaskFollowers != null) { mTaskFollowers.setActivity(activity); } if (mTaskFriends != null) { mTaskFriends.setActivity(activity); } for (TaskUpdateFollower it : mTasksUpdateFollowers) { it.setActivity(activity); } } public boolean getIsRunningTaskFollowers() { return mIsRunningTaskFollowers; } public void setIsRunningTaskFollowers(boolean isRunning) { mIsRunningTaskFollowers = isRunning; } public boolean getIsRunningTaskFriends() { return mIsRunningTaskFriends; } public void setIsRunningTaskFriends(boolean isRunning) { mIsRunningTaskFriends = isRunning; } public void cancelTasks() { if (mTaskFollowers != null) { mTaskFollowers.setActivity(null); mTaskFollowers.cancel(true); } if (mTaskFriends != null) { mTaskFriends.setActivity(null); mTaskFriends.cancel(true); } for (TaskUpdateFollower it : mTasksUpdateFollowers) { it.setActivity(null); it.cancel(true); } } public boolean getFollowersOnly() { return mFollowersOnly; } public void setFollowersOnly(boolean followersOnly) { mFollowersOnly = followersOnly; } public boolean getRanOnceFollowers() { return mRanOnceFollowers; } public void setRanOnceFollowers(boolean ranOnce) { mRanOnceFollowers = ranOnce; } public boolean getRanOnceFriends() { return mRanOnceFriends; } public void setRanOnceFriends(boolean ranOnce) { mRanOnceFriends = ranOnce; } public boolean areAnyTasksRunning() { return mIsRunningTaskFollowers || mIsRunningTaskFriends || mTasksUpdateFollowers.size() > 0; } public boolean addFriend(User user) { for (User it : mFriends) { if (it.getId().equals(user.getId())) { return false; } } mFriends.add(user); return true; } public void removeTaskUpdateFollower(TaskUpdateFollower task) { mTasksUpdateFollowers.remove(task); // Try to cleanup anyone we missed, this could happen for a brief period // during rotation. for (int i = mTasksUpdateFollowers.size()-1; i > -1; i--) { if (mTasksUpdateFollowers.get(i).getIsDone()) { mTasksUpdateFollowers.remove(i); } } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/UserDetailsFriendsFollowersActivity.java
Java
asf20
23,526
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Venue; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay; import com.joelapenna.foursquared.maps.VenueItemizedOverlay; import com.joelapenna.foursquared.util.UiUtil; import android.os.Bundle; import android.util.Log; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class VenueMapActivity extends MapActivity { public static final String TAG = "VenueMapActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME + ".VenueMapActivity.INTENT_EXTRA_VENUE"; private MapView mMapView; private MapController mMapController; private VenueItemizedOverlay mOverlay = null; private MyLocationOverlay mMyLocationOverlay = null; private StateHolder mStateHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.venue_map_activity); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { mStateHolder = new StateHolder(); if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) { mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE)); } else { Log.e(TAG, "VenueMapActivity requires a venue parcel its intent extras."); finish(); return; } } ensureUi(); } private void ensureUi() { /* Button mapsButton = (Button) findViewById(R.id.mapsButton); mapsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse( // "geo:0,0?q=" + mStateHolder.getVenue().getName() + " near " + mStateHolder.getVenue().getCity())); startActivity(intent); } }); if (FoursquaredSettings.SHOW_VENUE_MAP_BUTTON_MORE == false) { mapsButton.setVisibility(View.GONE); } */ setTitle(getString(R.string.venue_map_activity_title, mStateHolder.getVenue().getName())); mMapView = (MapView) findViewById(R.id.mapView); mMapView.setBuiltInZoomControls(true); mMapController = mMapView.getController(); mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView); mMapView.getOverlays().add(mMyLocationOverlay); mOverlay = new VenueItemizedOverlay(this.getResources().getDrawable( R.drawable.map_marker_blue)); if (VenueUtils.hasValidLocation(mStateHolder.getVenue())) { Group<Venue> venueGroup = new Group<Venue>(); venueGroup.setType("Current Venue"); venueGroup.add(mStateHolder.getVenue()); mOverlay.setGroup(venueGroup); mMapView.getOverlays().add(mOverlay); } updateMap(); } @Override public void onResume() { super.onResume(); mMyLocationOverlay.enableMyLocation(); if (UiUtil.sdkVersion() > 3) { mMyLocationOverlay.enableCompass(); } } @Override public void onPause() { super.onPause(); mMyLocationOverlay.disableMyLocation(); mMyLocationOverlay.disableCompass(); } @Override protected boolean isRouteDisplayed() { return false; } private void updateMap() { if (mOverlay != null && mOverlay.size() > 0) { GeoPoint center = mOverlay.getCenter(); mMapController.animateTo(center); mMapController.setZoom(17); } } private static class StateHolder { private Venue mVenue; public StateHolder() { } public Venue getVenue() { return mVenue; } public void setVenue(Venue venue) { mVenue = venue; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/VenueMapActivity.java
Java
asf20
4,672
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import android.app.Activity; import android.app.SearchManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.UriMatcher; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import java.net.URLDecoder; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class BrowsableActivity extends Activity { private static final String TAG = "BrowsableActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int URI_PATH_CHECKIN = 1; private static final int URI_PATH_CHECKINS = 2; private static final int URI_PATH_SEARCH = 3; private static final int URI_PATH_SHOUT = 4; private static final int URI_PATH_USER = 5; private static final int URI_PATH_VENUE = 6; public static String PARAM_SHOUT_TEXT = "shout"; public static String PARAM_SEARCH_QUERY = "q"; public static String PARAM_SEARCH_IMMEDIATE= "immediate"; public static String PARAM_USER_ID= "uid"; private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { sUriMatcher.addURI("m.foursquare.com", "checkin", URI_PATH_CHECKIN); sUriMatcher.addURI("m.foursquare.com", "checkins", URI_PATH_CHECKINS); sUriMatcher.addURI("m.foursquare.com", "search", URI_PATH_SEARCH); sUriMatcher.addURI("m.foursquare.com", "shout", URI_PATH_SHOUT); sUriMatcher.addURI("m.foursquare.com", "user", URI_PATH_USER); sUriMatcher.addURI("m.foursquare.com", "venue/#", URI_PATH_VENUE); } private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Uri uri = getIntent().getData(); if (DEBUG) Log.d(TAG, "Intent Data: " + uri); Intent intent; switch (sUriMatcher.match(uri)) { case URI_PATH_CHECKIN: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_CHECKIN"); intent = new Intent(this, VenueActivity.class); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, uri.getQueryParameter("vid")); startActivity(intent); break; case URI_PATH_CHECKINS: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_CHECKINS"); intent = new Intent(this, FriendsActivity.class); startActivity(intent); break; case URI_PATH_SEARCH: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_SEARCH"); intent = new Intent(this, SearchVenuesActivity.class); if (!TextUtils.isEmpty(uri.getQueryParameter(PARAM_SEARCH_QUERY))) { intent.putExtra(SearchManager.QUERY, URLDecoder.decode(uri.getQueryParameter(PARAM_SEARCH_QUERY))); if (uri.getQueryParameter(PARAM_SEARCH_IMMEDIATE) != null && uri.getQueryParameter(PARAM_SEARCH_IMMEDIATE).equals("1")) { intent.setAction(Intent.ACTION_SEARCH); // interpret action as search immediately. } else { intent.setAction(Intent.ACTION_VIEW); // interpret as prepopulate search field only. } } startActivity(intent); break; case URI_PATH_SHOUT: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_SHOUT"); intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_SHOUT, true); if (!TextUtils.isEmpty(uri.getQueryParameter(PARAM_SHOUT_TEXT))) { intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_TEXT_PREPOPULATE, URLDecoder.decode(uri.getQueryParameter(PARAM_SHOUT_TEXT))); } startActivity(intent); break; case URI_PATH_USER: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_USER"); intent = new Intent(this, UserDetailsActivity.class); if (!TextUtils.isEmpty(uri.getQueryParameter(PARAM_USER_ID))) { intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, uri.getQueryParameter(PARAM_USER_ID)); } startActivity(intent); break; case URI_PATH_VENUE: if (DEBUG) Log.d(TAG, "Matched: URI_PATH_VENUE"); intent = new Intent(this, VenueActivity.class); intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, uri.getLastPathSegment()); startActivity(intent); break; default: if (DEBUG) Log.d(TAG, "Matched: None"); } finish(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/BrowsableActivity.java
Java
asf20
5,421
/** * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 CommonsWare, LLC */ package com.joelapenna.foursquared.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * This is based off the chapter 13 sample in Advanced Android Development, by Mark Murphy. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class OnBootReceiver extends BroadcastReceiver { public static final String TAG = "OnBootReceiver"; @Override public void onReceive(Context context, Intent intent) { // If the user has notifications on, set an alarm every N minutes, where N is their // requested refresh rate. PingsService.setupPings(context); } }
1084solid-exp
main/src/com/joelapenna/foursquared/app/OnBootReceiver.java
Java
asf20
787
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquared.R; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.LinearLayout; /** * This is pretty much a direct copy of LoadableListActivity. It just gives the caller * a chance to set their own view for the empty state. This is used by FriendsActivity * to show a button like 'Find some friends!' when the list is empty (in the case that * they are a new user and have no friends initially). * * By default, loadable_list_activity_with_view is used as the intial empty view with * a progress bar and textview description. The owner can then call setEmptyView() * with their own view to show if there are no results. * * @date April 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class LoadableListActivityWithView extends ListActivity { private LinearLayout mLayoutHeader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.loadable_list_activity_with_view); mLayoutHeader = (LinearLayout)findViewById(R.id.header); getListView().setDividerHeight(0); } public void setEmptyView(View view) { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); parent.getChildAt(0).setVisibility(View.GONE); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.addView(view); } public void setLoadingView() { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.getChildAt(0).setVisibility(View.VISIBLE); } public int getNoSearchResultsStringId() { return R.string.no_search_results; } public LinearLayout getHeaderLayout() { return mLayoutHeader; } }
1084solid-exp
main/src/com/joelapenna/foursquared/app/LoadableListActivityWithView.java
Java
asf20
2,169
/** * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 CommonsWare, LLC */ package com.joelapenna.foursquared.app; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.os.PowerManager; /** * This is based off the chapter 13 sample in Advanced Android Development, by Mark Murphy. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public abstract class WakefulIntentService extends IntentService { public static final String TAG = "WakefulIntentService"; public static final String LOCK_NAME_STATIC = "com.joelapenna.foursquared.app.WakefulintentService.Static"; private static PowerManager.WakeLock lockStatic = null; abstract void doWakefulWork(Intent intent); public static void acquireStaticLock(Context context) { getLock(context).acquire(); } private synchronized static PowerManager.WakeLock getLock(Context context) { if (lockStatic == null) { PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE); lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME_STATIC); lockStatic.setReferenceCounted(true); } return(lockStatic); } public WakefulIntentService(String name) { super(name); } @Override final protected void onHandleIntent(Intent intent) { doWakefulWork(intent); getLock(this).release(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/app/WakefulIntentService.java
Java
asf20
1,553
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.appwidget.FriendsAppWidgetProvider; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.Comparators; import android.app.IntentService; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import java.util.Collections; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FoursquaredService extends IntentService { private static final String TAG = "FoursquaredService"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public FoursquaredService() { super("FoursquaredService"); } /** * Handles various intents, appwidget state changes for starters. * * {@inheritDoc} */ @Override public void onHandleIntent(Intent intent) { if (DEBUG) Log.d(TAG, "onHandleIntent: " + intent.toString()); if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(intent.getAction())) { updateWidgets(); } } private void updateWidgets() { if (DEBUG) Log.d(TAG, "updateWidgets"); Group<Checkin> checkins = null; Foursquared foursquared = ((Foursquared) getApplication()); if (foursquared.isReady()) { if (DEBUG) Log.d(TAG, "User settings are ready, starting normal widget update."); try { checkins = foursquared.getFoursquare().checkins( LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation())); } catch (Exception e) { if (DEBUG) Log.d(TAG, "Exception: Skipping widget update.", e); return; } Collections.sort(checkins, Comparators.getCheckinRecencyComparator()); // Request the user photos for the checkins... At the moment, this // is async. It is likely this means that the first update of the widget will never // show user photos as the photos will still be downloading when the getInputStream // call is made in SpecialDealsAppWidgetProvider. for (int i = 0; i < checkins.size(); i++) { Uri photoUri = Uri.parse((checkins.get(i)).getUser().getPhoto()); if (!foursquared.getRemoteResourceManager().exists(photoUri)) { foursquared.getRemoteResourceManager().request(photoUri); } } } AppWidgetManager am = AppWidgetManager.getInstance(this); int[] appWidgetIds = am.getAppWidgetIds(new ComponentName(this, FriendsAppWidgetProvider.class)); for (int i = 0; i < appWidgetIds.length; i++) { FriendsAppWidgetProvider.updateAppWidget((Context) this, foursquared .getRemoteResourceManager(), am, appWidgetIds[i], checkins); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/app/FoursquaredService.java
Java
asf20
3,255
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FriendsActivity; import com.joelapenna.foursquared.MainActivity; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.StringFormatters; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.widget.RemoteViews; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This service will run every N minutes (specified by the user in settings). An alarm * handles running the service. * * When the service runs, we call /checkins. From the list of checkins, we cut down the * list of relevant checkins as follows: * <ul> * <li>Not one of our own checkins.</li> * <li>We haven't turned pings off for the user. This can be toggled on/off in the * UserDetailsActivity activity, per user.</li> * <li>The checkin is younger than the last time we ran this service.</li> * </ul> * * Note that the server might override the pings attribute to 'off' for certain checkins, * usually if the checkin is far away from our current location. * * Pings will not be cleared from the notification bar until a subsequent run can * generate at least one new ping. A new batch of pings will clear all * previous pings so as to not clutter the notification bar. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsService extends WakefulIntentService { public static final String TAG = "PingsService"; private static final boolean DEBUG = false; public static final int NOTIFICATION_ID_CHECKINS = 15; public PingsService() { super("PingsService"); } @Override public void onCreate() { super.onCreate(); } @Override protected void doWakefulWork(Intent intent) { Log.i(TAG, "Foursquare pings service running..."); // The user must have logged in once previously for this to work, // and not leave the app in a logged-out state. Foursquared foursquared = (Foursquared) getApplication(); Foursquare foursquare = foursquared.getFoursquare(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (!foursquared.isReady()) { Log.i(TAG, "User not logged in, cannot proceed."); return; } // Before running, make sure the user still wants pings on. // For example, the user could have turned pings on from // this device, but then turned it off on a second device. This // service would continue running then, continuing to notify the // user. if (!checkUserStillWantsPings(foursquared.getUserId(), foursquare)) { // Turn off locally. Log.i(TAG, "Pings have been turned off for user, cancelling service."); prefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit(); cancelPings(this); return; } // Get the users current location and then request nearby checkins. Group<Checkin> checkins = null; Location location = getLastGeolocation(); if (location != null) { try { checkins = foursquare.checkins( LocationUtils.createFoursquareLocation(location)); } catch (Exception ex) { Log.e(TAG, "Error getting checkins in pings service.", ex); } } else { Log.e(TAG, "Could not find location in pings service, cannot proceed."); } if (checkins != null) { Log.i(TAG, "Checking " + checkins.size() + " checkins for pings."); // Don't accept any checkins that are older than the last time we ran. long lastRunTime = prefs.getLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()); Date dateLast = new Date(lastRunTime); Log.i(TAG, "Last service run time: " + dateLast.toLocaleString() + " (" + lastRunTime + ")."); // Now build the list of 'new' checkins. List<Checkin> newCheckins = new ArrayList<Checkin>(); for (Checkin it : checkins) { if (DEBUG) Log.d(TAG, "Checking checkin of " + it.getUser().getFirstname()); // Ignore ourselves. The server should handle this by setting the pings flag off but.. if (it.getUser() != null && it.getUser().getId().equals(foursquared.getUserId())) { if (DEBUG) Log.d(TAG, " Ignoring checkin of ourselves."); continue; } // Check that our user wanted to see pings from this user. if (!it.getPing()) { if (DEBUG) Log.d(TAG, " Pings are off for this user."); continue; } // If it's an 'off the grid' checkin, ignore. if (it.getVenue() == null && it.getShout() == null) { if (DEBUG) Log.d(TAG, " Checkin is off the grid, ignoring."); continue; } // Check against date times. try { Date dateCheckin = StringFormatters.DATE_FORMAT.parse(it.getCreated()); if (DEBUG) { Log.d(TAG, " Comaring date times for checkin."); Log.d(TAG, " Last run time: " + dateLast.toLocaleString()); Log.d(TAG, " Checkin time: " + dateCheckin.toLocaleString()); } if (dateCheckin.after(dateLast)) { if (DEBUG) Log.d(TAG, " Checkin is younger than our last run time, passes all tests!!"); newCheckins.add(it); } else { if (DEBUG) Log.d(TAG, " Checkin is older than last run time."); } } catch (ParseException ex) { if (DEBUG) Log.e(TAG, " Error parsing checkin timestamp: " + it.getCreated(), ex); } } Log.i(TAG, "Found " + newCheckins.size() + " new checkins."); notifyUser(newCheckins); } else { // Checkins were null, so don't record this as the last run time in order to try // fetching checkins we may have missed on the next run. // Thanks to logan.johnson@gmail.com for the fix. Log.i(TAG, "Checkins were null, won't update last run timestamp."); return; } // Record this as the last time we ran. prefs.edit().putLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()).commit(); } private Location getLastGeolocation() { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); List<String> providers = manager.getAllProviders(); Location bestLocation = null; for (String it : providers) { Location location = manager.getLastKnownLocation(it); if (location != null) { if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { bestLocation = location; } } } return bestLocation; } private void notifyUser(List<Checkin> newCheckins) { // If we have no new checkins to show, nothing to do. We would also be leaving the // previous batch of pings alive (if any) which is ok. if (newCheckins.size() < 1) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // Clear all previous pings notifications before showing new ones. NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); mgr.cancelAll(); // We'll only ever show a single entry, so we collapse data depending on how many // new checkins we received on this refresh. RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.pings_list_item); if (newCheckins.size() == 1) { // A single checkin, show full checkin preview. Checkin checkin = newCheckins.get(0); String checkinMsgLine1 = StringFormatters.getCheckinMessageLine1(checkin, true); String checkinMsgLine2 = StringFormatters.getCheckinMessageLine2(checkin); String checkinMsgLine3 = StringFormatters.getCheckinMessageLine3(checkin); contentView.setTextViewText(R.id.text1, checkinMsgLine1); if (!TextUtils.isEmpty(checkinMsgLine2)) { contentView.setTextViewText(R.id.text2, checkinMsgLine2); contentView.setTextViewText(R.id.text3, checkinMsgLine3); } else { contentView.setTextViewText(R.id.text2, checkinMsgLine3); } } else { // More than one new checkin, collapse them. String checkinMsgLine1 = newCheckins.size() + " new Foursquare checkins!"; StringBuilder sbCheckinMsgLine2 = new StringBuilder(1024); for (Checkin it : newCheckins) { sbCheckinMsgLine2.append(StringFormatters.getUserAbbreviatedName(it.getUser())); sbCheckinMsgLine2.append(", "); } if (sbCheckinMsgLine2.length() > 0) { sbCheckinMsgLine2.delete(sbCheckinMsgLine2.length()-2, sbCheckinMsgLine2.length()); } String checkinMsgLine3 = "at " + StringFormatters.DATE_FORMAT_TODAY.format(new Date()); contentView.setTextViewText(R.id.text1, checkinMsgLine1); contentView.setTextViewText(R.id.text2, sbCheckinMsgLine2.toString()); contentView.setTextViewText(R.id.text3, checkinMsgLine3); } PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, FriendsActivity.class), 0); Notification notification = new Notification( R.drawable.notification_icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.flags |= Notification.FLAG_AUTO_CANCEL; if (prefs.getBoolean(Preferences.PREFERENCE_PINGS_VIBRATE, false)) { notification.defaults |= Notification.DEFAULT_VIBRATE; } if (newCheckins.size() > 1) { notification.number = newCheckins.size(); } mgr.notify(NOTIFICATION_ID_CHECKINS, notification); } private boolean checkUserStillWantsPings(String userId, Foursquare foursquare) { try { User user = foursquare.user(userId, false, false, false, null); if (user != null) { return user.getSettings().getPings().equals("on"); } } catch (Exception ex) { // Assume they still want it on. } return true; } public static void setupPings(Context context) { // If the user has pings on, set an alarm every N minutes, where N is their // requested refresh rate. We default to 30 if some problem reading set interval. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean(Preferences.PREFERENCE_PINGS, false)) { int refreshRateInMinutes = getRefreshIntervalInMinutes(prefs); if (DEBUG) { Log.d(TAG, "User has pings on, attempting to setup alarm with interval: " + refreshRateInMinutes + ".."); } // We want to mark this as the last run time so we don't get any notifications // before the service is started. prefs.edit().putLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()).commit(); // Schedule the alarm. AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + (refreshRateInMinutes * 60 * 1000), refreshRateInMinutes * 60 * 1000, makePendingIntentAlarm(context)); } } public static void cancelPings(Context context) { AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.cancel(makePendingIntentAlarm(context)); } private static PendingIntent makePendingIntentAlarm(Context context) { return PendingIntent.getBroadcast(context, 0, new Intent(context, PingsOnAlarmReceiver.class), 0); } public static void clearAllNotifications(Context context) { NotificationManager mgr = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); mgr.cancelAll(); } public static void generatePingsTest(Context context) { Intent intent = new Intent(context, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); NotificationManager mgr = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.pings_list_item); contentView.setTextViewText(R.id.text1, "Ping title line"); contentView.setTextViewText(R.id.text2, "Ping message line 2"); contentView.setTextViewText(R.id.text3, "Ping message line 3"); Notification notification = new Notification( R.drawable.notification_icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.defaults |= Notification.DEFAULT_VIBRATE; mgr.notify(-1, notification); } private static int getRefreshIntervalInMinutes(SharedPreferences prefs) { int refreshRateInMinutes = 30; try { refreshRateInMinutes = Integer.parseInt(prefs.getString( Preferences.PREFERENCE_PINGS_INTERVAL, String.valueOf(refreshRateInMinutes))); } catch (NumberFormatException ex) { Log.e(TAG, "Error parsing pings interval time, defaulting to: " + refreshRateInMinutes); } return refreshRateInMinutes; } }
1084solid-exp
main/src/com/joelapenna/foursquared/app/PingsService.java
Java
asf20
15,922
/** * Copyright 2010 Mark Wyszomierski * Portions Copyright (c) 2008-2010 CommonsWare, LLC */ package com.joelapenna.foursquared.app; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * This is based off the chapter 13 sample in Advanced Android Development, by Mark Murphy. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsOnAlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { WakefulIntentService.acquireStaticLock(context); context.startService(new Intent(context, PingsService.class)); } }
1084solid-exp
main/src/com/joelapenna/foursquared/app/PingsOnAlarmReceiver.java
Java
asf20
702
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquared.R; import android.app.ListActivity; import android.os.Bundle; import android.view.ViewGroup; import android.view.Window; import android.widget.ProgressBar; import android.widget.TextView; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class LoadableListActivity extends ListActivity { private int mNoSearchResultsString = getNoSearchResultsStringId(); private ProgressBar mEmptyProgress; private TextView mEmptyText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.loadable_list_activity); mEmptyProgress = (ProgressBar)findViewById(R.id.emptyProgress); mEmptyText = (TextView)findViewById(R.id.emptyText); setLoadingView(); getListView().setDividerHeight(0); } public void setEmptyView() { mEmptyProgress.setVisibility(ViewGroup.GONE); mEmptyText.setText(mNoSearchResultsString); } public void setLoadingView() { mEmptyProgress.setVisibility(ViewGroup.VISIBLE); mEmptyText.setText("");//R.string.loading); } public void setLoadingView(String loadingText) { setLoadingView(); mEmptyText.setText(loadingText); } public int getNoSearchResultsStringId() { return R.string.no_search_results; } }
1084solid-exp
main/src/com/joelapenna/foursquared/app/LoadableListActivity.java
Java
asf20
1,541
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.app; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.widget.SegmentedButton; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.LinearLayout; /** * This is pretty much a direct copy of LoadableListActivity. It just gives the caller * a chance to set their own view for the empty state. This is used by FriendsActivity * to show a button like 'Find some friends!' when the list is empty (in the case that * they are a new user and have no friends initially). * * By default, loadable_list_activity_with_view is used as the intial empty view with * a progress bar and textview description. The owner can then call setEmptyView() * with their own view to show if there are no results. * * @date April 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class LoadableListActivityWithViewAndHeader extends ListActivity { private LinearLayout mLayoutHeader; private SegmentedButton mHeaderButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.loadable_list_activity_with_view_and_header); mLayoutHeader = (LinearLayout)findViewById(R.id.header); mHeaderButton = (SegmentedButton)findViewById(R.id.segmented); getListView().setDividerHeight(0); } public void setEmptyView(View view) { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); parent.getChildAt(0).setVisibility(View.GONE); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.addView(view); } public void setLoadingView() { LinearLayout parent = (LinearLayout)findViewById(R.id.loadableListHolder); if (parent.getChildCount() > 1) { parent.removeViewAt(1); } parent.getChildAt(0).setVisibility(View.VISIBLE); } public int getNoSearchResultsStringId() { return R.string.no_search_results; } public LinearLayout getHeaderLayout() { return mLayoutHeader; } public SegmentedButton getHeaderButton() { return mHeaderButton; } }
1084solid-exp
main/src/com/joelapenna/foursquared/app/LoadableListActivityWithViewAndHeader.java
Java
asf20
2,449
package com.joelapenna.foursquared; import com.joelapenna.foursquared.providers.GlobalSearchProvider; import android.app.Activity; import android.app.SearchManager; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; /** * Activity that gets intents from the Quick Search Box and starts the correct * Activity depending on the type of the data. * * @author Tauno Talimaa (tauntz@gmail.com) */ public class GlobalSearchActivity extends Activity { private static final String TAG = GlobalSearchProvider.class.getSimpleName(); private static final boolean DEBUG = FoursquaredSettings.DEBUG; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); handleIntent(intent); } private void handleIntent(Intent intent) { String dataString = intent.getDataString(); if (!TextUtils.isEmpty(dataString)) { Uri uri = Uri.parse(intent.getDataString()); String directory = uri.getPathSegments().get(0); if (directory.equals(GlobalSearchProvider.VENUE_DIRECTORY)) { if (DEBUG) { Log.d(TAG, "Viewing venue details for venue id:" + uri.getLastPathSegment()); } Intent i = new Intent(this, VenueActivity.class); i.setAction(Intent.ACTION_VIEW); i.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, uri.getLastPathSegment()); startActivity(i); finish(); } else if (directory.equals(GlobalSearchProvider.FRIEND_DIRECTORY)) { if (DEBUG) { Log.d(TAG, "Viewing friend details for friend id:" + uri.getLastPathSegment()); // TODO: Implement } } } else { // For now just launch search activity and assume a venue search. Intent intentSearch = new Intent(this, SearchVenuesActivity.class); intentSearch.setAction(Intent.ACTION_SEARCH); if (intent.hasExtra(SearchManager.QUERY)) { intentSearch.putExtra(SearchManager.QUERY, intent.getStringExtra(SearchManager.QUERY)); } startActivity(intentSearch); finish(); } } }
1084solid-exp
main/src/com/joelapenna/foursquared/GlobalSearchActivity.java
Java
asf20
2,568
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.util.CheckinTimestampSort; import com.joelapenna.foursquared.util.Comparators; import com.joelapenna.foursquared.util.MenuUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.UiUtil; import com.joelapenna.foursquared.widget.CheckinListAdapter; import com.joelapenna.foursquared.widget.SegmentedButton; import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import java.io.IOException; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.Map; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) * @author Mark Wyszomierski (markww@gmail.com) * -Added dummy location observer, new menu icon logic, * links to new user activity (3/10/2010). * -Sorting checkins by distance/time. (3/18/2010). * -Added option to sort by server response, or by distance. (6/10/2010). * -Reformatted/refactored. (9/22/2010). */ public class FriendsActivity extends LoadableListActivityWithViewAndHeader { static final String TAG = "FriendsActivity"; static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final int CITY_RADIUS_IN_METERS = 20 * 1000; // 20km private static final long SLEEP_TIME_IF_NO_LOCATION = 3000L; private static final int MENU_GROUP_SEARCH = 0; private static final int MENU_REFRESH = 1; private static final int MENU_SHOUT = 2; private static final int MENU_MORE = 3; private static final int MENU_MORE_MAP = 20; private static final int MENU_MORE_LEADERBOARD = 21; private static final int SORT_METHOD_RECENT = 0; private static final int SORT_METHOD_NEARBY = 1; private StateHolder mStateHolder; private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver(); private LinkedHashMap<Integer, String> mMenuMoreSubitems; private SeparatedListAdapter mListAdapter; private ViewGroup mLayoutEmpty; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); if (getLastNonConfigurationInstance() != null) { mStateHolder = (StateHolder) getLastNonConfigurationInstance(); mStateHolder.setActivity(this); } else { mStateHolder = new StateHolder(); mStateHolder.setSortMethod(SORT_METHOD_RECENT); } ensureUi(); Foursquared foursquared = (Foursquared)getApplication(); if (foursquared.isReady()) { if (!mStateHolder.getRanOnce()) { mStateHolder.startTask(this); } } } @Override public void onResume() { super.onResume(); ((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver); } @Override public void onPause() { super.onPause(); ((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver); if (isFinishing()) { mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); mStateHolder.cancel(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(MENU_GROUP_SEARCH, MENU_REFRESH, Menu.NONE, R.string.refresh) .setIcon(R.drawable.ic_menu_refresh); menu.add(Menu.NONE, MENU_SHOUT, Menu.NONE, R.string.shout_action_label) .setIcon(R.drawable.ic_menu_shout); SubMenu menuMore = menu.addSubMenu(Menu.NONE, MENU_MORE, Menu.NONE, "More"); menuMore.setIcon(android.R.drawable.ic_menu_more); for (Map.Entry<Integer, String> it : mMenuMoreSubitems.entrySet()) { menuMore.add(it.getValue()); } MenuUtils.addPreferencesToMenu(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_REFRESH: mStateHolder.startTask(this); return true; case MENU_SHOUT: Intent intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class); intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_SHOUT, true); startActivity(intent); return true; case MENU_MORE: // Submenu items generate id zero, but we check on item title below. return true; default: if (item.getTitle().equals("Map")) { Checkin[] checkins = (Checkin[])mStateHolder.getCheckins().toArray( new Checkin[mStateHolder.getCheckins().size()]); Intent intentMap = new Intent(FriendsActivity.this, FriendsMapActivity.class); intentMap.putExtra(FriendsMapActivity.EXTRA_CHECKIN_PARCELS, checkins); startActivity(intentMap); return true; } else if (item.getTitle().equals(mMenuMoreSubitems.get(MENU_MORE_LEADERBOARD))) { startActivity(new Intent(FriendsActivity.this, StatsActivity.class)); return true; } break; } return super.onOptionsItemSelected(item); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } @Override public int getNoSearchResultsStringId() { return R.string.no_friend_checkins; } private void ensureUi() { SegmentedButton buttons = getHeaderButton(); buttons.clearButtons(); buttons.addButtons( getString(R.string.friendsactivity_btn_recent), getString(R.string.friendsactivity_btn_nearby)); if (mStateHolder.getSortMethod() == SORT_METHOD_RECENT) { buttons.setPushedButtonIndex(0); } else { buttons.setPushedButtonIndex(1); } buttons.setOnClickListener(new OnClickListenerSegmentedButton() { @Override public void onClick(int index) { if (index == 0) { mStateHolder.setSortMethod(SORT_METHOD_RECENT); } else { mStateHolder.setSortMethod(SORT_METHOD_NEARBY); } ensureUiListView(); } }); mMenuMoreSubitems = new LinkedHashMap<Integer, String>(); mMenuMoreSubitems.put(MENU_MORE_MAP, getResources().getString( R.string.friendsactivity_menu_map)); mMenuMoreSubitems.put(MENU_MORE_LEADERBOARD, getResources().getString( R.string.friendsactivity_menu_leaderboard)); ensureUiListView(); } private void ensureUiListView() { mListAdapter = new SeparatedListAdapter(this); if (mStateHolder.getSortMethod() == SORT_METHOD_RECENT) { sortCheckinsRecent(mStateHolder.getCheckins(), mListAdapter); } else { sortCheckinsDistance(mStateHolder.getCheckins(), mListAdapter); } ListView listView = getListView(); listView.setAdapter(mListAdapter); listView.setDividerHeight(0); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Checkin checkin = (Checkin) parent.getAdapter().getItem(position); if (checkin.getUser() != null) { Intent intent = new Intent(FriendsActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, checkin.getUser()); intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true); startActivity(intent); } } }); // Prepare our no-results view. Something odd is going on with the layout parameters though. // If we don't explicitly set the layout to be fill/fill after inflating, the layout jumps // to a wrap/wrap layout. Furthermore, sdk 3 crashes with the original layout using two // buttons in a horizontal LinearLayout. LayoutInflater inflater = LayoutInflater.from(this); if (UiUtil.sdkVersion() > 3) { mLayoutEmpty = (ScrollView)inflater.inflate( R.layout.friends_activity_empty, null); Button btnAddFriends = (Button)mLayoutEmpty.findViewById( R.id.friendsActivityEmptyBtnAddFriends); btnAddFriends.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FriendsActivity.this, AddFriendsActivity.class); startActivity(intent); } }); Button btnFriendRequests = (Button)mLayoutEmpty.findViewById( R.id.friendsActivityEmptyBtnFriendRequests); btnFriendRequests.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(FriendsActivity.this, FriendRequestsActivity.class); startActivity(intent); } }); } else { // Inflation on 1.5 is causing a lot of issues, dropping full layout. mLayoutEmpty = (ScrollView)inflater.inflate( R.layout.friends_activity_empty_sdk3, null); } mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); if (mListAdapter.getCount() == 0) { setEmptyView(mLayoutEmpty); } if (mStateHolder.getIsRunningTask()) { setProgressBarIndeterminateVisibility(true); if (!mStateHolder.getRanOnce()) { setLoadingView(); } } else { setProgressBarIndeterminateVisibility(false); } } private void sortCheckinsRecent(Group<Checkin> checkins, SeparatedListAdapter listAdapter) { // Sort all by timestamp first. Collections.sort(checkins, Comparators.getCheckinRecencyComparator()); // We'll group in different section adapters based on some time thresholds. Group<Checkin> recent = new Group<Checkin>(); Group<Checkin> today = new Group<Checkin>(); Group<Checkin> yesterday = new Group<Checkin>(); Group<Checkin> older = new Group<Checkin>(); Group<Checkin> other = new Group<Checkin>(); CheckinTimestampSort timestamps = new CheckinTimestampSort(); for (Checkin it : checkins) { // If we can't parse the distance value, it's possible that we // did not have a geolocation for the device at the time the // search was run. In this case just assume this friend is nearby // to sort them in the time buckets. int meters = 0; try { meters = Integer.parseInt(it.getDistance()); } catch (NumberFormatException ex) { if (DEBUG) Log.d(TAG, "Couldn't parse distance for checkin during friend search."); meters = 0; } if (meters > CITY_RADIUS_IN_METERS) { other.add(it); } else { try { Date date = new Date(it.getCreated()); if (date.after(timestamps.getBoundaryRecent())) { recent.add(it); } else if (date.after(timestamps.getBoundaryToday())) { today.add(it); } else if (date.after(timestamps.getBoundaryYesterday())) { yesterday.add(it); } else { older.add(it); } } catch (Exception ex) { older.add(it); } } } if (recent.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(recent); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_recent), adapter); } if (today.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(today); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_today), adapter); } if (yesterday.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(yesterday); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_yesterday), adapter); } if (older.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(older); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_older), adapter); } if (other.size() > 0) { CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); adapter.setGroup(other); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_other_city), adapter); } } private void sortCheckinsDistance(Group<Checkin> checkins, SeparatedListAdapter listAdapter) { Collections.sort(checkins, Comparators.getCheckinDistanceComparator()); Group<Checkin> nearby = new Group<Checkin>(); CheckinListAdapter adapter = new CheckinListAdapter(this, ((Foursquared) getApplication()).getRemoteResourceManager()); for (Checkin it : checkins) { int meters = 0; try { meters = Integer.parseInt(it.getDistance()); } catch (NumberFormatException ex) { if (DEBUG) Log.d(TAG, "Couldn't parse distance for checkin during friend search."); meters = 0; } if (meters < CITY_RADIUS_IN_METERS) { nearby.add(it); } } if (nearby.size() > 0) { adapter.setGroup(nearby); listAdapter.addSection(getResources().getString( R.string.friendsactivity_title_sort_distance), adapter); } } private void onTaskStart() { setProgressBarIndeterminateVisibility(true); setLoadingView(); } private void onTaskComplete(Group<Checkin> checkins, Exception ex) { mStateHolder.setRanOnce(true); mStateHolder.setIsRunningTask(false); setProgressBarIndeterminateVisibility(false); // Clear list for new batch. mListAdapter.removeObserver(); mListAdapter.clear(); mListAdapter = new SeparatedListAdapter(this); // User can sort by default (which is by checkin time), or just by distance. if (checkins != null) { mStateHolder.setCheckins(checkins); if (mStateHolder.getSortMethod() == SORT_METHOD_RECENT) { sortCheckinsRecent(checkins, mListAdapter); } else { sortCheckinsDistance(checkins, mListAdapter); } } else if (ex != null) { mStateHolder.setCheckins(new Group<Checkin>()); NotificationsUtil.ToastReasonForFailure(this, ex); } if (mStateHolder.getCheckins().size() == 0) { setEmptyView(mLayoutEmpty); } getListView().setAdapter(mListAdapter); } private static class TaskCheckins extends AsyncTask<Void, Void, Group<Checkin>> { private Foursquared mFoursquared; private FriendsActivity mActivity; private Exception mException; public TaskCheckins(FriendsActivity activity) { mFoursquared = ((Foursquared) activity.getApplication()); mActivity = activity; } public void setActivity(FriendsActivity activity) { mActivity = activity; } @Override public Group<Checkin> doInBackground(Void... params) { Group<Checkin> checkins = null; try { checkins = checkins(); } catch (Exception ex) { mException = ex; } return checkins; } @Override protected void onPreExecute() { mActivity.onTaskStart(); } @Override public void onPostExecute(Group<Checkin> checkins) { if (mActivity != null) { mActivity.onTaskComplete(checkins, mException); } } private Group<Checkin> checkins() throws FoursquareException, IOException { // If we're the startup tab, it's likely that we won't have a geo location // immediately. For now we can use this ugly method of sleeping for N // seconds to at least let network location get a lock. We're only trying // to discern between same-city, so we can even use LocationManager's // getLastKnownLocation() method because we don't care if we're even a few // miles off. The api endpoint doesn't require location, so still go ahead // even if we can't find a location. Location loc = mFoursquared.getLastKnownLocation(); if (loc == null) { try { Thread.sleep(SLEEP_TIME_IF_NO_LOCATION); } catch (InterruptedException ex) {} loc = mFoursquared.getLastKnownLocation(); } Group<Checkin> checkins = mFoursquared.getFoursquare().checkins(LocationUtils .createFoursquareLocation(loc)); Collections.sort(checkins, Comparators.getCheckinRecencyComparator()); return checkins; } } private static class StateHolder { private Group<Checkin> mCheckins; private int mSortMethod; private boolean mRanOnce; private boolean mIsRunningTask; private TaskCheckins mTaskCheckins; public StateHolder() { mRanOnce = false; mIsRunningTask = false; mCheckins = new Group<Checkin>(); } public int getSortMethod() { return mSortMethod; } public void setSortMethod(int sortMethod) { mSortMethod = sortMethod; } public Group<Checkin> getCheckins() { return mCheckins; } public void setCheckins(Group<Checkin> checkins) { mCheckins = checkins; } public boolean getRanOnce() { return mRanOnce; } public void setRanOnce(boolean ranOnce) { mRanOnce = ranOnce; } public boolean getIsRunningTask() { return mIsRunningTask; } public void setIsRunningTask(boolean isRunning) { mIsRunningTask = isRunning; } public void setActivity(FriendsActivity activity) { if (mIsRunningTask) { mTaskCheckins.setActivity(activity); } } public void startTask(FriendsActivity activity) { if (!mIsRunningTask) { mTaskCheckins = new TaskCheckins(activity); mTaskCheckins.execute(); mIsRunningTask = true; } } public void cancel() { if (mIsRunningTask) { mTaskCheckins.cancel(true); mIsRunningTask = false; } } } /** * This is really just a dummy observer to get the GPS running * since this is the new splash page. After getting a fix, we * might want to stop registering this observer thereafter so * it doesn't annoy the user too much. */ private class SearchLocationObserver implements Observer { @Override public void update(Observable observable, Object data) { } } }
1084solid-exp
main/src/com/joelapenna/foursquared/FriendsActivity.java
Java
asf20
22,692
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Display; import android.view.WindowManager; import android.webkit.WebView; import android.widget.LinearLayout; /** * Shows a listing of what's changed between * * @date March 17, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class ChangelogActivity extends Activity { private static final String CHANGELOG_HTML_FILE = "file:///android_asset/changelog-en.html"; private WebView mWebViewChanges; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.changelog_activity); ensureUi(); } private void ensureUi() { WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); LinearLayout llMain = (LinearLayout)findViewById(R.id.layoutMain); // We'll force the dialog to be a certain percentage height of the screen. mWebViewChanges = new WebView(this); mWebViewChanges.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, (int)Math.floor(display.getHeight() * 0.5))); mWebViewChanges.loadUrl(CHANGELOG_HTML_FILE); llMain.addView(mWebViewChanges); } }
1084solid-exp
main/src/com/joelapenna/foursquared/ChangelogActivity.java
Java
asf20
1,534
/** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquared.appwidget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquare.util.VenueUtils; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.MainActivity; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.UserDetailsActivity; import com.joelapenna.foursquared.app.FoursquaredService; import com.joelapenna.foursquared.util.DumpcatcherHelper; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.text.format.DateUtils; import android.util.Log; import android.view.View; import android.widget.RemoteViews; import java.io.IOException; import java.util.Date; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class FriendsAppWidgetProvider extends AppWidgetProvider { private static final String TAG = "FriendsAppWidgetProvider"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int[][] WIDGET_VIEW_IDS = { { R.id.widgetItem0, R.id.photo0, R.id.user0, R.id.time0, R.id.location0 }, { R.id.widgetItem1, R.id.photo1, R.id.user1, R.id.time1, R.id.location1 }, { R.id.widgetItem2, R.id.photo2, R.id.user2, R.id.time2, R.id.location2 }, { R.id.widgetItem3, R.id.photo3, R.id.user3, R.id.time3, R.id.location3 }, { R.id.widgetItem4, R.id.photo4, R.id.user4, R.id.time4, R.id.location4 } }; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { if (DEBUG) Log.d(TAG, "onUpdate()"); Intent intent = new Intent(context, FoursquaredService.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); context.startService(intent); } public static void updateAppWidget(Context context, RemoteResourceManager rrm, AppWidgetManager appWidgetManager, Integer appWidgetId, Group<Checkin> checkins) { if (DEBUG) Log.d(TAG, "updateAppWidget: " + String.valueOf(appWidgetId)); // Get the layout for the App Widget and attach an on-click listener to the button RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.friends_appwidget); if (DEBUG) Log.d(TAG, "adding header intent: " + String.valueOf(appWidgetId)); Intent baseIntent = new Intent(context, MainActivity.class); views.setOnClickPendingIntent(R.id.widgetHeader, PendingIntent.getActivity(context, 0, baseIntent, 0)); if (DEBUG) Log.d(TAG, "adding footer intent: " + String.valueOf(appWidgetId)); baseIntent = new Intent(context, FoursquaredService.class); baseIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); views.setOnClickPendingIntent(R.id.widgetFooter, PendingIntent.getService(context, 0, baseIntent, 0)); // Now hide all views if checkins is null (a sign of not being logged in), or populate the // checkins. if (checkins == null) { if (DEBUG) Log.d(TAG, "checkins is null, hiding UI."); views.setViewVisibility(R.id.widgetNotLoggedInTextView, View.VISIBLE); for (int i = 0; i < WIDGET_VIEW_IDS.length; i++) { hideCheckinView(views, WIDGET_VIEW_IDS[i]); } } else { if (DEBUG) Log.d(TAG, "Displaying checkins"); views.setViewVisibility(R.id.widgetNotLoggedInTextView, View.GONE); int numCheckins = checkins.size(); for (int i = 0; i < WIDGET_VIEW_IDS.length; i++) { if (i < numCheckins) { updateCheckinView(context, rrm, views, checkins.get(i), WIDGET_VIEW_IDS[i]); } else { hideCheckinView(views, WIDGET_VIEW_IDS[i]); } } } // Lastly, update the refresh timestamp CharSequence timestamp = DateUtils.formatDateTime(context, new Date().getTime(), DateUtils.FORMAT_SHOW_TIME); views.setTextViewText(R.id.widgetFooter, context.getResources().getString( R.string.friends_appwidget_footer_text, timestamp)); // Tell the AppWidgetManager to perform an update on the current App Widget try { appWidgetManager.updateAppWidget(appWidgetId, views); } catch (Exception e) { if (DEBUG) Log.d(TAG, "updateAppWidget crashed: ", e); DumpcatcherHelper.sendException(e); } } private static void updateCheckinView(Context context, RemoteResourceManager rrm, RemoteViews views, Checkin checkin, int[] viewIds) { int viewId = viewIds[0]; int photoViewId = viewIds[1]; int userViewId = viewIds[2]; int timeViewId = viewIds[3]; int locationViewId = viewIds[4]; final User user = checkin.getUser(); final Uri photoUri = Uri.parse(user.getPhoto()); views.setViewVisibility(viewId, View.VISIBLE); Intent baseIntent; baseIntent = new Intent(context, UserDetailsActivity.class); baseIntent.putExtra(UserDetailsActivity.EXTRA_USER_ID, checkin.getUser().getId()); baseIntent.setData(Uri.parse("https://foursquare.com/user/" + checkin.getUser().getId())); views.setOnClickPendingIntent(viewId, PendingIntent.getActivity(context, 0, baseIntent, 0)); try { Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(photoUri)); views.setImageViewBitmap(photoViewId, bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(checkin.getUser().getGender())) { views.setImageViewResource(photoViewId, R.drawable.blank_boy); } else { views.setImageViewResource(photoViewId, R.drawable.blank_girl); } } views.setTextViewText(userViewId, StringFormatters.getUserAbbreviatedName(user)); views.setTextViewText(timeViewId, StringFormatters.getRelativeTimeSpanString(checkin .getCreated())); if (VenueUtils.isValid(checkin.getVenue())) { views.setTextViewText(locationViewId, checkin.getVenue().getName()); } else { views.setTextViewText(locationViewId, ""); } } private static void hideCheckinView(RemoteViews views, int[] viewIds) { views.setViewVisibility(viewIds[0], View.GONE); } }
1084solid-exp
main/src/com/joelapenna/foursquared/appwidget/FriendsAppWidgetProvider.java
Java
asf20
7,071
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.types.Badge; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquared.widget.BadgeWithIconListAdapter; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.DialogInterface.OnDismissListener; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.AdapterView.OnItemClickListener; import java.util.ArrayList; /** * Shows a listing of all the badges the user has earned. Right not it shows only * the earned badges, we can add an additional display flag to also display badges * the user has yet to unlock as well. This will show them what they're missing * which would be fun to see. * * @date March 10, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class BadgesActivity extends Activity { private static final String TAG = "BadgesActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_BADGE_ARRAY_LIST_PARCEL = Foursquared.PACKAGE_NAME + ".BadgesActivity.EXTRA_BADGE_ARRAY_LIST_PARCEL"; public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME + ".BadgesActivity.EXTRA_USER_NAME"; private static final int DIALOG_ID_INFO = 1; private GridView mBadgesGrid; private BadgeWithIconListAdapter mListAdapter; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.badges_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; } else { if (getIntent().hasExtra(EXTRA_BADGE_ARRAY_LIST_PARCEL) && getIntent().hasExtra(EXTRA_USER_NAME)) { mStateHolder = new StateHolder(getIntent().getStringExtra(EXTRA_USER_NAME)); // Can't jump from ArrayList to Group, argh. ArrayList<Badge> badges = getIntent().getExtras().getParcelableArrayList( EXTRA_BADGE_ARRAY_LIST_PARCEL); Group<Badge> group = new Group<Badge>(); for (Badge it : badges) { group.add(it); } mStateHolder.setBadges(group); } else { Log.e(TAG, "BadgesActivity requires a badge ArrayList pareclable in its intent extras."); finish(); return; } } ensureUi(); } @Override public void onPause() { super.onPause(); if (isFinishing()) { mListAdapter.removeObserver(); unregisterReceiver(mLoggedOutReceiver); } } @Override public Object onRetainNonConfigurationInstance() { return mStateHolder; } private void ensureUi() { mBadgesGrid = (GridView)findViewById(R.id.badgesGrid); mListAdapter = new BadgeWithIconListAdapter(this, ((Foursquared)getApplication()).getRemoteResourceManager()); mListAdapter.setGroup(mStateHolder.getBadges()); mBadgesGrid.setAdapter(mListAdapter); mBadgesGrid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) { Badge badge = (Badge)mListAdapter.getItem(position); showDialogInfo(badge.getName(), badge.getDescription(), badge.getIcon()); } }); setTitle(getString(R.string.badges_activity_title, mStateHolder.getUsername())); } private void showDialogInfo(String title, String message, String badgeIconUrl) { mStateHolder.setDlgInfoTitle(title); mStateHolder.setDlgInfoMessage(message); mStateHolder.setDlgInfoBadgeIconUrl(badgeIconUrl); showDialog(DIALOG_ID_INFO); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ID_INFO: AlertDialog dlgInfo = new AlertDialog.Builder(this) .setTitle(mStateHolder.getDlgInfoTitle()) .setIcon(0) .setMessage(mStateHolder.getDlgInfoMessage()).create(); dlgInfo.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(DIALOG_ID_INFO); } }); try { Uri icon = Uri.parse(mStateHolder.getDlgInfoBadgeIconUrl()); dlgInfo.setIcon(new BitmapDrawable(((Foursquared) getApplication()) .getRemoteResourceManager().getInputStream(icon))); } catch (Exception e) { Log.e(TAG, "Error loading badge dialog!", e); dlgInfo.setIcon(R.drawable.default_on); } return dlgInfo; } return null; } private static class StateHolder { private String mUsername; private Group<Badge> mBadges; private String mDlgInfoTitle; private String mDlgInfoMessage; private String mDlgInfoBadgeIconUrl; public StateHolder(String username) { mUsername = username; mBadges = new Group<Badge>(); } public String getUsername() { return mUsername; } public Group<Badge> getBadges() { return mBadges; } public void setBadges(Group<Badge> badges) { mBadges = badges; } public String getDlgInfoTitle() { return mDlgInfoTitle; } public void setDlgInfoTitle(String text) { mDlgInfoTitle = text; } public String getDlgInfoMessage() { return mDlgInfoMessage; } public void setDlgInfoMessage(String text) { mDlgInfoMessage = text; } public String getDlgInfoBadgeIconUrl() { return mDlgInfoBadgeIconUrl; } public void setDlgInfoBadgeIconUrl(String url) { mDlgInfoBadgeIconUrl = url; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/BadgesActivity.java
Java
asf20
7,265
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquared.preferences.Preferences; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; /** * Used to show a prompt to the user before the app runs. Some new marketplace vendors have * been asking this so they can prompt the user and tell them that the app uses internet * connections, which is not unlimited usage under many plans. This really should be handled * by the install screen which shows other permissions used. * * To enable this activity, just set it as the LAUNCHER in the manifest file. If the tag is * not added in the manifest file, this activity is never used. * * You can modify these text items in strings.xml to modify the appearance of the activity: * <ul> * <li>prelaunch_text</li> * <li>prelaunch_button</li> * <li>prelaunch_checkbox_dont_show_again</li> * </ul> * * @date May 15, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PrelaunchActivity extends Activity { public static final String TAG = "PrelaunchActivity"; public static final boolean DEBUG = FoursquaredSettings.DEBUG; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); setContentView(R.layout.prelaunch_activity); // If user doesn't want to be reminded anymore, just go to main activity. if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean( Preferences.PREFERENCE_SHOW_PRELAUNCH_ACTIVITY, false) == false) { startMainActivity(); } else { ensureUi(); } } private void ensureUi() { Button buttonOk = (Button) findViewById(R.id.btnOk); buttonOk.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { goToMain(false); } }); } private void goToMain(boolean dontRemind) { // Don't show this startup screen anymore. CheckBox checkboxDontShowAgain = (CheckBox)findViewById(R.id.checkboxDontShowAgain); if (checkboxDontShowAgain.isChecked()) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); prefs.edit().putBoolean(Preferences.PREFERENCE_SHOW_PRELAUNCH_ACTIVITY, false).commit(); } startMainActivity(); } private void startMainActivity() { Intent intent = new Intent(this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); finish(); } }
1084solid-exp
main/src/com/joelapenna/foursquared/PrelaunchActivity.java
Java
asf20
3,029
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.facebook.android.Facebook; import com.facebook.android.FacebookUtil; import com.facebook.android.FacebookWebViewActivity; import com.facebook.android.Facebook.PreparedUrl; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.FriendInvitesResult; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.util.AddressBookEmailBuilder; import com.joelapenna.foursquared.util.AddressBookUtils; import com.joelapenna.foursquared.util.NotificationsUtil; import com.joelapenna.foursquared.util.AddressBookEmailBuilder.ContactSimple; import com.joelapenna.foursquared.widget.FriendSearchAddFriendAdapter; import com.joelapenna.foursquared.widget.FriendSearchInviteNonFoursquareUserAdapter; import com.joelapenna.foursquared.widget.SeparatedListAdapter; import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.DialogInterface.OnDismissListener; import android.os.AsyncTask; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.TextView.OnEditorActionListener; import java.util.ArrayList; import java.util.List; /** * Lets the user search for friends via first+last name, phone number, or * twitter names. Once a list of matching users is found, the user can click on * elements in the list to send a friend request to them. When the request is * successfully sent, that user is removed from the list. You can add the * INPUT_TYPE key to the intent while launching the activity to control what * type of friend search the activity will perform. Pass in one of the following * values: * <ul> * <li>INPUT_TYPE_NAME_OR_PHONE</li> * <li>INPUT_TYPE_TWITTERNAME</li> * <li>INPUT_TYPE_ADDRESSBOOK</li> * <li>INPUT_TYPE_ADDRESSBOOK_INVITE</li> * </ul> * * @date February 11, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class AddFriendsByUserInputActivity extends Activity { private static final String TAG = "AddFriendsByUserInputActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private static final int DIALOG_ID_CONFIRM_INVITE_ALL = 1; public static final String INPUT_TYPE = "com.joelapenna.foursquared.AddFriendsByUserInputActivity.INPUT_TYPE"; public static final int INPUT_TYPE_NAME_OR_PHONE = 0; public static final int INPUT_TYPE_TWITTERNAME = 1; public static final int INPUT_TYPE_ADDRESSBOOK = 2; public static final int INPUT_TYPE_ADDRESSBOOK_INVITE = 3; public static final int INPUT_TYPE_FACEBOOK = 4; private static final int ACTIVITY_RESULT_FACEBOOK_WEBVIEW_ACTIVITY = 5; private TextView mTextViewInstructions; private TextView mTextViewAdditionalInstructions; private EditText mEditInput; private Button mBtnSearch; private ListView mListView; private ProgressDialog mDlgProgress; private int mInputType; private SeparatedListAdapter mListAdapter; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.d(TAG, "onCreate()"); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.add_friends_by_user_input_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); mTextViewInstructions = (TextView) findViewById(R.id.addFriendInstructionsTextView); mTextViewAdditionalInstructions = (TextView) findViewById(R.id.addFriendInstructionsAdditionalTextView); mEditInput = (EditText) findViewById(R.id.addFriendInputEditText); mBtnSearch = (Button) findViewById(R.id.addFriendSearchButton); mListView = (ListView) findViewById(R.id.addFriendResultsListView); mListAdapter = new SeparatedListAdapter(this); mListView.setAdapter(mListAdapter); mListView.setItemsCanFocus(true); mListView.setDividerHeight(0); mBtnSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startSearch(mEditInput.getText().toString()); } }); mEditInput.addTextChangedListener(mNamesFieldWatcher); mEditInput.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_NULL) { startSearch(mEditInput.getText().toString()); } return false; } }); mBtnSearch.setEnabled(false); mInputType = getIntent().getIntExtra(INPUT_TYPE, INPUT_TYPE_NAME_OR_PHONE); switch (mInputType) { case INPUT_TYPE_TWITTERNAME: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_twitter_instructions)); mEditInput.setHint(getResources().getString(R.string.add_friends_by_twitter_hint)); mEditInput.setInputType(InputType.TYPE_CLASS_TEXT); break; case INPUT_TYPE_ADDRESSBOOK: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_addressbook_instructions)); mTextViewAdditionalInstructions.setText(getResources().getString( R.string.add_friends_by_addressbook_additional_instructions)); mEditInput.setVisibility(View.GONE); mBtnSearch.setVisibility(View.GONE); break; case INPUT_TYPE_ADDRESSBOOK_INVITE: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_addressbook_instructions)); mTextViewAdditionalInstructions.setText(getResources().getString( R.string.add_friends_by_addressbook_additional_instructions)); mEditInput.setVisibility(View.GONE); mBtnSearch.setVisibility(View.GONE); break; case INPUT_TYPE_FACEBOOK: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_facebook_instructions)); mTextViewAdditionalInstructions.setText(getResources().getString( R.string.add_friends_by_facebook_additional_instructions)); mEditInput.setVisibility(View.GONE); mBtnSearch.setVisibility(View.GONE); break; default: mTextViewInstructions.setText(getResources().getString( R.string.add_friends_by_name_or_phone_instructions)); mEditInput.setHint(getResources().getString(R.string.add_friends_by_name_or_phone_hint)); mEditInput.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); break; } Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTaskFindFriends(this); mStateHolder.setActivityForTaskFriendRequest(this); mStateHolder.setActivityForTaskSendInvite(this); // If we have run before, restore matches divider. if (mStateHolder.getRanOnce()) { populateListFromStateHolder(); } } else { mStateHolder = new StateHolder(); // If we are scanning the address book, or a facebook search, we should // kick off immediately. switch (mInputType) { case INPUT_TYPE_ADDRESSBOOK: case INPUT_TYPE_ADDRESSBOOK_INVITE: startSearch(""); break; case INPUT_TYPE_FACEBOOK: startFacebookWebViewActivity(); break; } } } @Override public void onResume() { super.onResume(); if (mStateHolder.getIsRunningTaskFindFriends()) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_find)); } else if (mStateHolder.getIsRunningTaskSendFriendRequest()) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources() .getString(R.string.add_friends_progress_bar_message_send_request)); } else if (mStateHolder.getIsRunningTaskSendInvite()) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources() .getString(R.string.add_friends_progress_bar_message_send_invite)); } } @Override public void onPause() { super.onPause(); stopProgressBar(); if (isFinishing()) { mListAdapter.removeObserver(); } } @Override public void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTaskFindFriends(null); mStateHolder.setActivityForTaskFriendRequest(null); mStateHolder.setActivityForTaskSendInvite(null); return mStateHolder; } private void userAdd(User user) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_send_request)); mStateHolder.startTaskSendFriendRequest(AddFriendsByUserInputActivity.this, user.getId()); } private void userInfo(User user) { Intent intent = new Intent(AddFriendsByUserInputActivity.this, UserDetailsActivity.class); intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, user); startActivity(intent); } private void userInvite(ContactSimple contact) { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_send_invite)); mStateHolder.startTaskSendInvite(AddFriendsByUserInputActivity.this, contact.mEmail, false); } private void inviteAll() { startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_send_invite)); mStateHolder.startTaskSendInvite( AddFriendsByUserInputActivity.this, mStateHolder.getUsersNotOnFoursquareAsCommaSepString(), true); } private void startSearch(String input) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mEditInput.getWindowToken(), 0); mEditInput.setEnabled(false); mBtnSearch.setEnabled(false); startProgressBar(getResources().getString(R.string.add_friends_activity_label), getResources().getString(R.string.add_friends_progress_bar_message_find)); mStateHolder.startTaskFindFriends(AddFriendsByUserInputActivity.this, input); } private void startFacebookWebViewActivity() { Intent intent = new Intent(this, FacebookWebViewActivity.class); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_ACTION, Facebook.LOGIN); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_APP_ID, getResources().getString(R.string.facebook_api_key)); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_PERMISSIONS, new String[] {}); //{"publish_stream", "read_stream", "offline_access"}); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_DEBUG, false); intent.putExtra(FacebookWebViewActivity.INTENT_EXTRA_KEY_CLEAR_COOKIES, true); startActivityForResult(intent, ACTIVITY_RESULT_FACEBOOK_WEBVIEW_ACTIVITY); } private void startProgressBar(String title, String message) { if (mDlgProgress == null) { mDlgProgress = ProgressDialog.show(this, title, message); } mDlgProgress.show(); } private void stopProgressBar() { if (mDlgProgress != null) { mDlgProgress.dismiss(); mDlgProgress = null; } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ID_CONFIRM_INVITE_ALL: AlertDialog dlgInfo = new AlertDialog.Builder(this) .setTitle(getResources().getString(R.string.add_friends_contacts_title_invite_all)) .setIcon(0) .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { inviteAll(); } }) .setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .setMessage(getResources().getString(R.string.add_friends_contacts_message_invite_all, String.valueOf(mStateHolder.getUsersNotOnFoursquare().size()))) .create(); dlgInfo.setOnDismissListener(new OnDismissListener() { public void onDismiss(DialogInterface dialog) { removeDialog(DIALOG_ID_CONFIRM_INVITE_ALL); } }); return dlgInfo; } return null; } /** * Listen for FacebookWebViewActivity finishing, inspect success/failure and returned * request parameters. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ACTIVITY_RESULT_FACEBOOK_WEBVIEW_ACTIVITY) { // If RESULT_OK, means the request was attempted, but we still have to check the return status. if (resultCode == RESULT_OK) { // Check return status. if (data.getBooleanExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_RESULT_STATUS, false)) { // If ok, the result bundle will contain all data from the webview. Bundle bundle = data.getBundleExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_RESULT_BUNDLE); // We can switch on the action here, the activity echoes it back to us for convenience. String suppliedAction = data.getStringExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_SUPPLIED_ACTION); if (suppliedAction.equals(Facebook.LOGIN)) { // We can now start a task to fetch foursquare friends using their facebook id. mStateHolder.startTaskFindFriends( AddFriendsByUserInputActivity.this, bundle.getString(Facebook.TOKEN)); } } else { // Error running the operation, report to user perhaps. String error = data.getStringExtra(FacebookWebViewActivity.INTENT_RESULT_KEY_ERROR); Log.e(TAG, error); Toast.makeText(this, error, Toast.LENGTH_LONG).show(); finish(); } } else { // If the user cancelled enterting their facebook credentials, exit here too. finish(); } } } private void populateListFromStateHolder() { mListAdapter.removeObserver(); mListAdapter = new SeparatedListAdapter(this); if (mStateHolder.getUsersOnFoursquare().size() + mStateHolder.getUsersNotOnFoursquare().size() > 0) { if (mStateHolder.getUsersOnFoursquare().size() > 0) { FriendSearchAddFriendAdapter adapter = new FriendSearchAddFriendAdapter( this, mButtonRowClickHandler, ((Foursquared)getApplication()).getRemoteResourceManager()); adapter.setGroup(mStateHolder.getUsersOnFoursquare()); mListAdapter.addSection( getResources().getString(R.string.add_friends_contacts_found_on_foursqare), adapter); } if (mStateHolder.getUsersNotOnFoursquare().size() > 0) { FriendSearchInviteNonFoursquareUserAdapter adapter = new FriendSearchInviteNonFoursquareUserAdapter( this, mAdapterListenerInvites); adapter.setContacts(mStateHolder.getUsersNotOnFoursquare()); mListAdapter.addSection( getResources().getString(R.string.add_friends_contacts_not_found_on_foursqare), adapter); } } else { Toast.makeText(this, getResources().getString(R.string.add_friends_no_matches), Toast.LENGTH_SHORT).show(); } mListView.setAdapter(mListAdapter); } private void onFindFriendsTaskComplete(FindFriendsResult result, Exception ex) { if (result != null) { mStateHolder.setUsersOnFoursquare(result.getUsersOnFoursquare()); mStateHolder.setUsersNotOnFoursquare(result.getUsersNotOnFoursquare()); if (result.getUsersOnFoursquare().size() + result.getUsersNotOnFoursquare().size() < 1) { Toast.makeText(this, getResources().getString(R.string.add_friends_no_matches), Toast.LENGTH_SHORT).show(); } } else { NotificationsUtil.ToastReasonForFailure(AddFriendsByUserInputActivity.this, ex); } populateListFromStateHolder(); mEditInput.setEnabled(true); mBtnSearch.setEnabled(true); mStateHolder.setIsRunningTaskFindFriends(false); stopProgressBar(); } private void onSendFriendRequestTaskComplete(User friendRequestRecipient, Exception ex) { if (friendRequestRecipient != null) { // We do a linear search to find the row to remove, ouch. int position = 0; for (User it : mStateHolder.getUsersOnFoursquare()) { if (it.getId().equals(friendRequestRecipient.getId())) { mStateHolder.getUsersOnFoursquare().remove(position); break; } position++; } mListAdapter.notifyDataSetChanged(); Toast.makeText(AddFriendsByUserInputActivity.this, getResources().getString(R.string.add_friends_request_sent_ok), Toast.LENGTH_SHORT).show(); } else { NotificationsUtil.ToastReasonForFailure(AddFriendsByUserInputActivity.this, ex); } mEditInput.setEnabled(true); mBtnSearch.setEnabled(true); mStateHolder.setIsRunningTaskSendFriendRequest(false); stopProgressBar(); } private void onSendInviteTaskComplete(String email, boolean isAllEmails, Exception ex) { if (email != null) { if (isAllEmails) { mStateHolder.getUsersNotOnFoursquare().clear(); Toast.makeText(AddFriendsByUserInputActivity.this, getResources().getString(R.string.add_friends_invites_sent_ok), Toast.LENGTH_SHORT).show(); } else { // We do a linear search to find the row to remove, ouch. int position = 0; for (ContactSimple it : mStateHolder.getUsersNotOnFoursquare()) { if (it.mEmail.equals(email)) { mStateHolder.getUsersNotOnFoursquare().remove(position); break; } position++; } Toast.makeText(AddFriendsByUserInputActivity.this, getResources().getString(R.string.add_friends_invite_sent_ok), Toast.LENGTH_SHORT).show(); } mListAdapter.notifyDataSetChanged(); } else { NotificationsUtil.ToastReasonForFailure(AddFriendsByUserInputActivity.this, ex); } mEditInput.setEnabled(true); mBtnSearch.setEnabled(true); mStateHolder.setIsRunningTaskSendInvite(false); stopProgressBar(); } private static class FindFriendsTask extends AsyncTask<String, Void, FindFriendsResult> { private AddFriendsByUserInputActivity mActivity; private Exception mReason; public FindFriendsTask(AddFriendsByUserInputActivity activity) { mActivity = activity; } public void setActivity(AddFriendsByUserInputActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(mActivity.getResources().getString( R.string.add_friends_activity_label), mActivity.getResources().getString( R.string.add_friends_progress_bar_message_find)); } @Override protected FindFriendsResult doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); FindFriendsResult result = new FindFriendsResult(); switch (mActivity.mInputType) { case INPUT_TYPE_TWITTERNAME: result.setUsersOnFoursquare(foursquare.findFriendsByTwitter(params[0])); break; case INPUT_TYPE_ADDRESSBOOK: scanAddressBook(result, foursquare, foursquared, false); break; case INPUT_TYPE_ADDRESSBOOK_INVITE: scanAddressBook(result, foursquare, foursquared, true); break; case INPUT_TYPE_FACEBOOK: // For facebook, we need to first get all friend uids, then use that with the foursquare api. String facebookFriendIds = getFacebookFriendIds(params[0]); if (!TextUtils.isEmpty(facebookFriendIds)) { result.setUsersOnFoursquare(foursquare.findFriendsByFacebook(facebookFriendIds)); } else { result.setUsersOnFoursquare(new Group<User>()); } break; default: // Combine searches for name/phone, results returned in one list. Group<User> users = new Group<User>(); users.addAll(foursquare.findFriendsByPhone(params[0])); users.addAll(foursquare.findFriendsByName(params[0])); result.setUsersOnFoursquare(users); break; } return result; } catch (Exception e) { if (DEBUG) Log.d(TAG, "FindFriendsTask: Exception doing add friends by name", e); mReason = e; } return null; } private String getFacebookFriendIds(String facebookToken) { Facebook facebook = new Facebook(); facebook.setAccessToken(facebookToken); String friendsAsJson = ""; try { PreparedUrl purl = facebook.requestUrl("me/friends"); friendsAsJson = FacebookUtil.openUrl(purl.getUrl(), purl.getHttpMethod(), purl.getParameters()); } catch (Exception ex) { Log.e(TAG, "Error getting facebook friends as json.", ex); return friendsAsJson; } // {"data":[{"name":"Friends Name","id":"12345"}]} StringBuilder sb = new StringBuilder(2048); try { JSONObject json = new JSONObject(friendsAsJson); JSONArray friends = json.getJSONArray("data"); for (int i = 0, m = friends.length(); i < m; i++) { JSONObject friend = friends.getJSONObject(i); sb.append(friend.get("id")); sb.append(","); } if (sb.length() > 0 && sb.charAt(sb.length()-1) == ',') { sb.deleteCharAt(sb.length()-1); } } catch (Exception ex) { Log.e(TAG, "Error deserializing facebook friends json object.", ex); } return sb.toString(); } private void scanAddressBook(FindFriendsResult result, Foursquare foursquare, Foursquared foursquared, boolean invites) throws Exception { AddressBookUtils addr = AddressBookUtils.addressBookUtils(); AddressBookEmailBuilder bld = addr.getAllContactsEmailAddressesInfo(mActivity); String phones = addr.getAllContactsPhoneNumbers(mActivity); String emails = bld.getEmailsCommaSeparated(); if (!TextUtils.isEmpty(phones) || !TextUtils.isEmpty(emails)) { FriendInvitesResult xml = foursquare.findFriendsByPhoneOrEmail(phones, emails); result.setUsersOnFoursquare(xml.getContactsOnFoursquare()); if (invites) { // Get a contact name for each email address we can send an invite to. List<ContactSimple> contactsNotOnFoursquare = new ArrayList<ContactSimple>(); for (String it : xml.getContactEmailsNotOnFoursquare()) { ContactSimple contact = new ContactSimple(); contact.mEmail = it; contact.mName = bld.getNameForEmail(it); contactsNotOnFoursquare.add(contact); } result.setUsersNotOnFoursquare(contactsNotOnFoursquare); } } } @Override protected void onPostExecute(FindFriendsResult result) { if (DEBUG) Log.d(TAG, "FindFriendsTask: onPostExecute()"); if (mActivity != null) { mActivity.onFindFriendsTaskComplete(result, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onFindFriendsTaskComplete( null, new Exception("Friend search cancelled.")); } } } private static class SendFriendRequestTask extends AsyncTask<String, Void, User> { private AddFriendsByUserInputActivity mActivity; private Exception mReason; public SendFriendRequestTask(AddFriendsByUserInputActivity activity) { mActivity = activity; } public void setActivity(AddFriendsByUserInputActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(mActivity.getResources().getString( R.string.add_friends_activity_label), mActivity.getResources().getString( R.string.add_friends_progress_bar_message_send_request)); } @Override protected User doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); User user = foursquare.friendSendrequest(params[0]); return user; } catch (Exception e) { if (DEBUG) Log.d(TAG, "SendFriendRequestTask: Exception doing send friend request.", e); mReason = e; } return null; } @Override protected void onPostExecute(User user) { if (DEBUG) Log.d(TAG, "SendFriendRequestTask: onPostExecute()"); if (mActivity != null) { mActivity.onSendFriendRequestTaskComplete(user, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onSendFriendRequestTaskComplete(null, new Exception( "Friend invitation cancelled.")); } } } private static class SendInviteTask extends AsyncTask<String, Void, String> { private AddFriendsByUserInputActivity mActivity; private boolean mIsAllEmails; private Exception mReason; public SendInviteTask(AddFriendsByUserInputActivity activity, boolean isAllEmails) { mActivity = activity; mIsAllEmails = isAllEmails; } public void setActivity(AddFriendsByUserInputActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.startProgressBar(mActivity.getResources().getString( R.string.add_friends_activity_label), mActivity.getResources().getString( R.string.add_friends_progress_bar_message_send_invite)); } @Override protected String doInBackground(String... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); foursquare.inviteByEmail(params[0]); return params[0]; } catch (Exception e) { Log.e(TAG, "SendInviteTask: Exception sending invite.", e); mReason = e; } return null; } @Override protected void onPostExecute(String email) { if (DEBUG) Log.d(TAG, "SendInviteTask: onPostExecute()"); if (mActivity != null) { mActivity.onSendInviteTaskComplete(email, mIsAllEmails, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onSendInviteTaskComplete(null, mIsAllEmails, new Exception("Invite send cancelled.")); } } } private static class StateHolder { FindFriendsTask mTaskFindFriends; SendFriendRequestTask mTaskSendFriendRequest; SendInviteTask mTaskSendInvite; Group<User> mUsersOnFoursquare; List<ContactSimple> mUsersNotOnFoursquare; boolean mIsRunningTaskFindFriends; boolean mIsRunningTaskSendFriendRequest; boolean mIsRunningTaskSendInvite; boolean mRanOnce; public StateHolder() { mUsersOnFoursquare = new Group<User>(); mUsersNotOnFoursquare = new ArrayList<ContactSimple>(); mIsRunningTaskFindFriends = false; mIsRunningTaskSendFriendRequest = false; mIsRunningTaskSendInvite = false; mRanOnce = false; } public Group<User> getUsersOnFoursquare() { return mUsersOnFoursquare; } public void setUsersOnFoursquare(Group<User> usersOnFoursquare) { mUsersOnFoursquare = usersOnFoursquare; mRanOnce = true; } public List<ContactSimple> getUsersNotOnFoursquare() { return mUsersNotOnFoursquare; } public void setUsersNotOnFoursquare(List<ContactSimple> usersNotOnFoursquare) { mUsersNotOnFoursquare = usersNotOnFoursquare; } public void startTaskFindFriends(AddFriendsByUserInputActivity activity, String input) { mIsRunningTaskFindFriends = true; mTaskFindFriends = new FindFriendsTask(activity); mTaskFindFriends.execute(input); } public void startTaskSendFriendRequest(AddFriendsByUserInputActivity activity, String userId) { mIsRunningTaskSendFriendRequest = true; mTaskSendFriendRequest = new SendFriendRequestTask(activity); mTaskSendFriendRequest.execute(userId); } public void startTaskSendInvite(AddFriendsByUserInputActivity activity, String email, boolean isAllEmails) { mIsRunningTaskSendInvite = true; mTaskSendInvite = new SendInviteTask(activity, isAllEmails); mTaskSendInvite.execute(email); } public void setActivityForTaskFindFriends(AddFriendsByUserInputActivity activity) { if (mTaskFindFriends != null) { mTaskFindFriends.setActivity(activity); } } public void setActivityForTaskFriendRequest(AddFriendsByUserInputActivity activity) { if (mTaskSendFriendRequest != null) { mTaskSendFriendRequest.setActivity(activity); } } public void setActivityForTaskSendInvite(AddFriendsByUserInputActivity activity) { if (mTaskSendInvite != null) { mTaskSendInvite.setActivity(activity); } } public void setIsRunningTaskFindFriends(boolean isRunning) { mIsRunningTaskFindFriends = isRunning; } public void setIsRunningTaskSendFriendRequest(boolean isRunning) { mIsRunningTaskSendFriendRequest = isRunning; } public void setIsRunningTaskSendInvite(boolean isRunning) { mIsRunningTaskSendInvite = isRunning; } public boolean getIsRunningTaskFindFriends() { return mIsRunningTaskFindFriends; } public boolean getIsRunningTaskSendFriendRequest() { return mIsRunningTaskSendFriendRequest; } public boolean getIsRunningTaskSendInvite() { return mIsRunningTaskSendInvite; } public boolean getRanOnce() { return mRanOnce; } public String getUsersNotOnFoursquareAsCommaSepString() { StringBuilder sb = new StringBuilder(2048); for (ContactSimple it : mUsersNotOnFoursquare) { if (sb.length() > 0) { sb.append(","); } sb.append(it.mEmail); } return sb.toString(); } } private TextWatcher mNamesFieldWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable s) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { mBtnSearch.setEnabled(!TextUtils.isEmpty(s)); } }; /** * This handler will be called when the user clicks on buttons in one of the * listview's rows. */ private FriendSearchAddFriendAdapter.ButtonRowClickHandler mButtonRowClickHandler = new FriendSearchAddFriendAdapter.ButtonRowClickHandler() { @Override public void onBtnClickAdd(User user) { userAdd(user); } @Override public void onInfoAreaClick(User user) { userInfo(user); } }; private FriendSearchInviteNonFoursquareUserAdapter.AdapterListener mAdapterListenerInvites = new FriendSearchInviteNonFoursquareUserAdapter.AdapterListener() { @Override public void onBtnClickInvite(ContactSimple contact) { userInvite(contact); } @Override public void onInfoAreaClick(ContactSimple contact) { // We could popup an intent for this contact so they can see // who we're talking about? } @Override public void onInviteAll() { showDialog(DIALOG_ID_CONFIRM_INVITE_ALL); } }; private static class FindFriendsResult { private Group<User> mUsersOnFoursquare; private List<ContactSimple> mUsersNotOnFoursquare; public FindFriendsResult() { mUsersOnFoursquare = new Group<User>(); mUsersNotOnFoursquare = new ArrayList<ContactSimple>(); } public Group<User> getUsersOnFoursquare() { return mUsersOnFoursquare; } public void setUsersOnFoursquare(Group<User> users) { if (users != null) { mUsersOnFoursquare = users; } } public List<ContactSimple> getUsersNotOnFoursquare() { return mUsersNotOnFoursquare; } public void setUsersNotOnFoursquare(List<ContactSimple> usersNotOnFoursquare) { if (usersNotOnFoursquare != null) { mUsersNotOnFoursquare = usersNotOnFoursquare; } } } }
1084solid-exp
main/src/com/joelapenna/foursquared/AddFriendsByUserInputActivity.java
Java
asf20
39,555
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.http.AbstractHttpApi; import com.joelapenna.foursquared.util.NotificationsUtil; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.protocol.ClientContext; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.webkit.WebView; import java.io.IOException; /** * Displays a special in a webview. Ideally we could use WebView.setHttpAuthUsernamePassword(), * but it is unfortunately not working. Instead we download the html content manually, then * feed it to our webview. Not ideal and we should update this in the future. * * @date April 4, 2010. * @author Mark Wyszomierski (markww@gmail.com), foursquare. * */ public class SpecialWebViewActivity extends Activity { private static final String TAG = "WebViewActivity"; public static final String EXTRA_CREDENTIALS_USERNAME = Foursquared.PACKAGE_NAME + ".SpecialWebViewActivity.EXTRA_CREDENTIALS_USERNAME"; public static final String EXTRA_CREDENTIALS_PASSWORD = Foursquared.PACKAGE_NAME + ".SpecialWebViewActivity.EXTRA_CREDENTIALS_PASSWORD"; public static final String EXTRA_SPECIAL_ID = Foursquared.PACKAGE_NAME + ".SpecialWebViewActivity.EXTRA_SPECIAL_ID"; private WebView mWebView; private StateHolder mStateHolder; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.special_webview_activity); mWebView = (WebView)findViewById(R.id.webView); mWebView.getSettings().setJavaScriptEnabled(true); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivityForTask(this); if (mStateHolder.getIsRunningTask() == false) { mWebView.loadDataWithBaseURL("--", mStateHolder.getHtml(), "text/html", "utf-8", ""); } } else { mStateHolder = new StateHolder(); if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EXTRA_CREDENTIALS_USERNAME) && getIntent().getExtras().containsKey(EXTRA_CREDENTIALS_PASSWORD) && getIntent().getExtras().containsKey(EXTRA_SPECIAL_ID)) { String username = getIntent().getExtras().getString(EXTRA_CREDENTIALS_USERNAME); String password = getIntent().getExtras().getString(EXTRA_CREDENTIALS_PASSWORD); String specialid = getIntent().getExtras().getString(EXTRA_SPECIAL_ID); mStateHolder.startTask(this, username, password, specialid); } else { Log.e(TAG, TAG + " intent missing required extras parameters."); finish(); } } } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivityForTask(null); return mStateHolder; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } private void onTaskComplete(String html, Exception ex) { mStateHolder.setIsRunningTask(false); if (html != null) { mStateHolder.setHtml(html); mWebView.loadDataWithBaseURL("--", mStateHolder.getHtml(), "text/html", "utf-8", ""); } else { NotificationsUtil.ToastReasonForFailure(this, ex); } } private static class SpecialTask extends AsyncTask<String, Void, String> { private SpecialWebViewActivity mActivity; private Exception mReason; public SpecialTask(SpecialWebViewActivity activity) { mActivity = activity; } public void setActivity(SpecialWebViewActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { } @Override protected String doInBackground(String... params) { String html = null; try { String username = params[0]; String password = params[1]; String specialid = params[2]; StringBuilder sbUrl = new StringBuilder(128); sbUrl.append("https://api.foursquare.com/iphone/special?sid="); sbUrl.append(specialid); AuthScope authScope = new AuthScope("api.foursquare.com", 80); DefaultHttpClient httpClient = AbstractHttpApi.createHttpClient(); httpClient.getCredentialsProvider().setCredentials(authScope, new UsernamePasswordCredentials(username, password)); httpClient.addRequestInterceptor(preemptiveAuth, 0); HttpGet httpGet = new HttpGet(sbUrl.toString()); try { HttpResponse response = httpClient.execute(httpGet); String responseText = EntityUtils.toString(response.getEntity()); html = responseText.replace("('/img", "('http://www.foursquare.com/img"); } catch (Exception e) { mReason = e; } } catch (Exception e) { mReason = e; } return html; } @Override protected void onPostExecute(String html) { if (mActivity != null) { mActivity.onTaskComplete(html, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskComplete(null, new Exception("Special task cancelled.")); } } private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { @Override public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider)context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; } private static class StateHolder { private String mHtml; private boolean mIsRunningTask; private SpecialTask mTask; public StateHolder() { mIsRunningTask = false; } public void setHtml(String html) { mHtml = html; } public String getHtml() { return mHtml; } public void startTask(SpecialWebViewActivity activity, String username, String password, String specialid) { mIsRunningTask = true; mTask = new SpecialTask(activity); mTask.execute(username, password, specialid); } public void setActivityForTask(SpecialWebViewActivity activity) { if (mTask != null) { mTask.setActivity(activity); } } public void setIsRunningTask(boolean isRunningTipTask) { mIsRunningTask = isRunningTipTask; } public boolean getIsRunningTask() { return mIsRunningTask; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/SpecialWebViewActivity.java
Java
asf20
9,274
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.UserUtils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @date September 25, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class FriendActionableListAdapter extends BaseGroupAdapter<User> implements ObservableAdapter { private LayoutInflater mInflater; private int mLayoutToInflate; private ButtonRowClickHandler mClickListener; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private int mLoadedPhotoIndex; public FriendActionableListAdapter(Context context, ButtonRowClickHandler clickListener, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.friend_actionable_list_item; mClickListener = clickListener; mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mLoadedPhotoIndex = 0; mRrm.addObserver(mResourcesObserver); } public FriendActionableListAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } public void removeObserver() { mHandler.removeCallbacks(mRunnableLoadPhotos); mHandler.removeCallbacks(mUpdatePhotos); mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); holder = new ViewHolder(); holder.photo = (ImageView) convertView.findViewById(R.id.photo); holder.name = (TextView) convertView.findViewById(R.id.name); holder.btn1 = (Button) convertView.findViewById(R.id.btn1); holder.btn2 = (Button) convertView.findViewById(R.id.btn2); convertView.setTag(holder); holder.btn1.setOnClickListener(mOnClickListenerBtn1); holder.btn2.setOnClickListener(mOnClickListenerBtn2); } else { holder = (ViewHolder) convertView.getTag(); } User user = (User) getItem(position); final Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } } holder.name.setText(user.getFirstname() + " " + (user.getLastname() != null ? user.getLastname() : "")); if (UserUtils.isFollower(user)) { holder.btn1.setVisibility(View.VISIBLE); holder.btn2.setVisibility(View.VISIBLE); holder.btn1.setTag(user); holder.btn2.setTag(user); } else { // Eventually we may have items for this case, like 'delete friend'. holder.btn1.setVisibility(View.GONE); holder.btn2.setVisibility(View.GONE); } return convertView; } private OnClickListener mOnClickListenerBtn1 = new OnClickListener() { @Override public void onClick(View v) { if (mClickListener != null) { User user = (User) v.getTag(); mClickListener.onBtnClickBtn1(user); } } }; private OnClickListener mOnClickListenerBtn2 = new OnClickListener() { @Override public void onClick(View v) { if (mClickListener != null) { User user = (User) v.getTag(); mClickListener.onBtnClickBtn2(user); } } }; public void removeItem(int position) throws IndexOutOfBoundsException { group.remove(position); notifyDataSetInvalidated(); } @Override public void setGroup(Group<User> g) { super.setGroup(g); mLoadedPhotoIndex = 0; mHandler.postDelayed(mRunnableLoadPhotos, 10L); } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(mUpdatePhotos); } } private Runnable mUpdatePhotos = new Runnable() { @Override public void run() { notifyDataSetChanged(); } }; private Runnable mRunnableLoadPhotos = new Runnable() { @Override public void run() { if (mLoadedPhotoIndex < getCount()) { User user = (User)getItem(mLoadedPhotoIndex++); Uri photoUri = Uri.parse(user.getPhoto()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } mHandler.postDelayed(mRunnableLoadPhotos, 200L); } } }; static class ViewHolder { ImageView photo; TextView name; Button btn1; Button btn2; } public interface ButtonRowClickHandler { public void onBtnClickBtn1(User user); public void onBtnClickBtn2(User user); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/FriendActionableListAdapter.java
Java
asf20
6,288
package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import java.io.File; import java.io.IOException; import java.util.Observable; import java.util.Observer; public class CategoryPickerAdapter extends BaseAdapter implements ObservableAdapter { private static final String TAG = "CheckinListAdapter"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private LayoutInflater mInflater; private int mLayoutToInflate; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); private Category mCategory; public CategoryPickerAdapter(Context context, RemoteResourceManager rrm, Category category) { super(); mCategory = category; mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.category_picker_list_item; mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); for (Category it : mCategory.getChildCategories()) { Uri photoUri = Uri.parse(it.getIconUrl()); File file = mRrm.getFile(photoUri); if (file != null) { if (System.currentTimeMillis() - file.lastModified() > FoursquaredSettings.CATEGORY_ICON_EXPIRATION) { mRrm.invalidate(photoUri); file = null; } } if (file == null) { mRrm.request(photoUri); } } } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.icon = (ImageView) convertView.findViewById(R.id.categoryPickerIcon); holder.name = (TextView) convertView.findViewById(R.id.categoryPickerName); holder.disclosure = (ImageView) convertView.findViewById(R.id.categoryPickerIconDisclosure); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } Category category = (Category) getItem(position); final Uri photoUri = Uri.parse(category.getIconUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.icon.setImageBitmap(bitmap); } catch (IOException e) { if (DEBUG) Log.e(TAG, "Error loading category icon.", e); } if (category.getChildCategories() != null && category.getChildCategories().size() > 0) { holder.disclosure.setVisibility(View.VISIBLE); } else { holder.disclosure.setVisibility(View.GONE); } holder.name.setText(category.getNodeName()); return convertView; } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } private static class ViewHolder { ImageView icon; TextView name; ImageView disclosure; } @Override public int getCount() { return mCategory.getChildCategories().size(); } @Override public Object getItem(int position) { return mCategory.getChildCategories().get(position); } @Override public long getItemId(int position) { return position; } @Override public boolean hasStableIds() { return true; } public static class CategoryFlat { private Category mCategory; private int mDepth; public CategoryFlat(Category category, int depth) { mCategory = category; mDepth = depth; } public Category getCategory() { return mCategory; } public int getDepth() { return mDepth; } } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/CategoryPickerAdapter.java
Java
asf20
5,457
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import java.io.IOException; import java.util.Observable; import java.util.Observer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; /** * @date February 14, 2010 * @author Mark Wyszomierski (markww@gmail.com), foursquare. */ public class FriendSearchAddFriendAdapter extends BaseGroupAdapter<User> implements ObservableAdapter { private static final String TAG = ""; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private LayoutInflater mInflater; private int mLayoutToInflate; private ButtonRowClickHandler mClickListener; private RemoteResourceManager mRrm; private RemoteResourceManagerObserver mResourcesObserver; private Handler mHandler = new Handler(); public FriendSearchAddFriendAdapter(Context context, ButtonRowClickHandler clickListener, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = R.layout.add_friends_list_item; mClickListener = clickListener; mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } public FriendSearchAddFriendAdapter(Context context, int layoutResource) { super(context); mInflater = LayoutInflater.from(context); mLayoutToInflate = layoutResource; } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(mLayoutToInflate, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.clickable = (LinearLayout) convertView .findViewById(R.id.addFriendListItemClickableArea); holder.photo = (ImageView) convertView.findViewById(R.id.addFriendListItemPhoto); holder.name = (TextView) convertView.findViewById(R.id.addFriendListItemName); holder.add = (Button) convertView.findViewById(R.id.addFriendListItemAddButton); convertView.setTag(holder); holder.clickable.setOnClickListener(mOnClickListenerInfo); holder.add.setOnClickListener(mOnClickListenerAdd); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } User user = (User) getItem(position); final Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } } holder.clickable.setTag(new Integer(position)); holder.name.setText(user.getFirstname() + " " + (user.getLastname() != null ? user.getLastname() : "")); holder.add.setTag(new Integer(position)); return convertView; } private OnClickListener mOnClickListenerAdd = new OnClickListener() { @Override public void onClick(View v) { Integer position = (Integer) v.getTag(); mClickListener.onBtnClickAdd((User) getItem(position)); } }; private OnClickListener mOnClickListenerInfo = new OnClickListener() { @Override public void onClick(View v) { if (mClickListener != null) { Integer position = (Integer) v.getTag(); mClickListener.onInfoAreaClick((User) getItem(position)); } } }; public void removeItem(int position) throws IndexOutOfBoundsException { group.remove(position); notifyDataSetInvalidated(); } @Override public void setGroup(Group<User> g) { super.setGroup(g); for (int i = 0; i < g.size(); i++) { Uri photoUri = Uri.parse(g.get(i).getPhoto()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Fetcher got: " + data); mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } static class ViewHolder { LinearLayout clickable; ImageView photo; TextView name; Button add; } public interface ButtonRowClickHandler { public void onBtnClickAdd(User user); public void onInfoAreaClick(User user); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/FriendSearchAddFriendAdapter.java
Java
asf20
6,293
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Venue; import android.content.Context; /** * @author Joe LaPenna (joe@joelapenna.com) */ abstract public class BaseVenueAdapter extends BaseGroupAdapter<Venue> { public BaseVenueAdapter(Context context) { super(context); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/BaseVenueAdapter.java
Java
asf20
368
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.types.Category; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import com.joelapenna.foursquared.util.StringFormatters; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @date March 9, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class HistoryListAdapter extends BaseCheckinAdapter implements ObservableAdapter { private LayoutInflater mInflater; private RemoteResourceManager mRrm; private Handler mHandler; private RemoteResourceManagerObserver mResourcesObserver; public HistoryListAdapter(Context context, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mHandler = new Handler(); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.history_list_item, null); holder = new ViewHolder(); holder.icon = (ImageView) convertView.findViewById(R.id.icon); holder.firstLine = (TextView) convertView.findViewById(R.id.firstLine); holder.shoutTextView = (TextView) convertView.findViewById(R.id.shoutTextView); holder.timeTextView = (TextView) convertView.findViewById(R.id.timeTextView); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } Checkin checkin = (Checkin) getItem(position); if (checkin.getVenue() != null) { holder.firstLine.setText(checkin.getVenue().getName()); holder.firstLine.setVisibility(View.VISIBLE); Category category = checkin.getVenue().getCategory(); if (category != null) { Uri photoUri = Uri.parse(category.getIconUrl()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.icon.setImageBitmap(bitmap); } catch (IOException e) { holder.icon.setImageResource(R.drawable.category_none); } } else { holder.icon.setImageResource(R.drawable.category_none); } } else { // This is going to be a shout then. holder.icon.setImageResource(R.drawable.ic_menu_shout); holder.firstLine.setVisibility(View.GONE); } if (TextUtils.isEmpty(checkin.getShout()) == false) { holder.shoutTextView.setText(checkin.getShout()); holder.shoutTextView.setVisibility(View.VISIBLE); } else { holder.shoutTextView.setVisibility(View.GONE); } holder.timeTextView.setText( StringFormatters.getRelativeTimeSpanString(checkin.getCreated())); return convertView; } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } private static class ViewHolder { ImageView icon; TextView firstLine; TextView shoutTextView; TextView timeTextView; } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/HistoryListAdapter.java
Java
asf20
4,375
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquared.R; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; import android.widget.TextView; /** * @date June 24, 2010 * @author Mark Wyszomierski (mark@gmail.com) */ public class MapCalloutView extends LinearLayout { private TextView mTextViewTitle; private TextView mTextViewMessage; public MapCalloutView(Context context) { super(context); } public MapCalloutView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void onFinishInflate() { super.onFinishInflate(); ((Activity)getContext()).getLayoutInflater().inflate(R.layout.map_callout_view, this); mTextViewTitle = (TextView)findViewById(R.id.title); mTextViewMessage = (TextView)findViewById(R.id.message); } public void setTitle(String title) { mTextViewTitle.setText(title); } public void setMessage(String message) { mTextViewMessage.setText(message); } }
1084solid-exp
main/src/com/joelapenna/foursquared/widget/MapCalloutView.java
Java
asf20
1,179