code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.control;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* In order to get ECU Trouble Codes, one must first send a DtcNumberObdCommand
* and by so, determining the number of error codes available by means of
* getTotalAvailableCodes().
*
* If none are available (totalCodes < 1), don't instantiate this command.
*/
public class TroubleCodesObdCommand extends ObdCommand {
protected final static char[] dtcLetters = { 'P', 'C', 'B', 'U' };
private StringBuffer codes = null;
private int howManyTroubleCodes = 0;
/**
* Default ctor.
*/
public TroubleCodesObdCommand(int howManyTroubleCodes) {
super("03");
codes = new StringBuffer();
this.howManyTroubleCodes = howManyTroubleCodes;
}
/**
* Copy ctor.
*
* @param other
*/
public TroubleCodesObdCommand(TroubleCodesObdCommand other) {
super(other);
codes = new StringBuffer();
}
// TODO clean
// int count = numCmd.getCodeCount();
// int dtcNum = (count + 2) / 3;
// for (int i = 0; i < dtcNum; i++) {
// sendCommand(cmd);
// String res = getResult();
// for (int j = 0; j < 3; j++) {
// String byte1 = res.substring(3 + j * 6, 5 + j * 6);
// String byte2 = res.substring(6 + j * 6, 8 + j * 6);
// int b1 = Integer.parseInt(byte1, 16);
// int b2 = Integer.parseInt(byte2, 16);
// int val = (b1 << 8) + b2;
// if (val == 0) {
// break;
// }
// String code = "P";
// if ((val & 0xC000) > 14) {
// code = "C";
// }
// code += Integer.toString((val & 0x3000) >> 12);
// code += Integer.toString((val & 0x0fff));
// codes.append(code);
// codes.append("\n");
// }
/**
* @return the formatted result of this command in string representation.
*/
public String formatResult() {
String res = getResult();
if (!"NODATA".equals(res)) {
/*
* Ignore first byte [43] of the response and then read each two
* bytes.
*/
int begin = 2; // start at 2nd byte
int end = 6; // end at 4th byte
for (int i = 0; i < howManyTroubleCodes * 2; i++) {
// read and jump 2 bytes
byte b1 = Byte.parseByte(res.substring(begin, end));
begin += 2;
end += 2;
// read and jump 2 bytes
byte b2 = Byte.parseByte(res.substring(begin, end));
begin += 2;
end += 2;
int tempValue = b1 << 8 | b2;
}
}
String[] ress = res.split("\r");
for (String r : ress) {
String k = r.replace("\r", "");
codes.append(k);
codes.append("\n");
}
return codes.toString();
}
@Override
public String getFormattedResult() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getName() {
return AvailableCommandNames.TROUBLE_CODES.getValue();
}
}
| Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.control;
import eu.lighthouselabs.obd.commands.PercentageObdCommand;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* TODO put description
*
* Timing Advance
*/
public class TimingAdvanceObdCommand extends PercentageObdCommand {
public TimingAdvanceObdCommand() {
super("01 0E");
}
public TimingAdvanceObdCommand(TimingAdvanceObdCommand other) {
super(other);
}
@Override
public String getName() {
return AvailableCommandNames.TIMING_ADVANCE.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.control;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* This command will for now read MIL (check engine light) state and number of
* diagnostic trouble codes currently flagged in the ECU.
*
* Perhaps in the future we'll extend this to read the 3rd, 4th and 5th bytes of
* the response in order to store information about the availability and
* completeness of certain on-board tests.
*/
public class DtcNumberObdCommand extends ObdCommand {
private int codeCount = 0;
private boolean milOn = false;
/**
* Default ctor.
*/
public DtcNumberObdCommand() {
super("01 01");
}
/**
* Copy ctor.
*
* @param other
*/
public DtcNumberObdCommand(DtcNumberObdCommand other) {
super(other);
}
/**
*
*/
public String getFormattedResult() {
String res = getResult();
if (!"NODATA".equals(res)) {
// ignore first two bytes [hh hh] of the response
int mil = buffer.get(2);
if ((mil & 0x80) == 128)
milOn = true;
codeCount = mil & 0x7F;
}
res = milOn ? "MIL is ON" : "MIL is OFF";
return new StringBuilder().append(res).append(codeCount)
.append(" codes").toString();
}
/**
* @return the number of trouble codes currently flaggd in the ECU.
*/
public int getTotalAvailableCodes() {
return codeCount;
}
/**
*
* @return the state of the check engine light state.
*/
public boolean getMilOn() {
return milOn;
}
@Override
public String getName() {
return AvailableCommandNames.DTC_NUMBER.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.protocol;
import eu.lighthouselabs.obd.commands.ObdCommand;
/**
* This command will turn-off echo.
*/
public class EchoOffObdCommand extends ObdCommand {
/**
* @param command
*/
public EchoOffObdCommand() {
super("AT E0");
}
/**
* @param other
*/
public EchoOffObdCommand(ObdCommand other) {
super(other);
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult()
*/
@Override
public String getFormattedResult() {
return getResult();
}
@Override
public String getName() {
return "Echo Off";
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.protocol;
import java.io.IOException;
import java.io.InputStream;
import eu.lighthouselabs.obd.commands.ObdCommand;
/**
* This method will reset the OBD connection.
*/
public class ObdResetCommand extends ObdCommand {
/**
* @param command
*/
public ObdResetCommand() {
super("AT Z");
}
/**
* @param other
*/
public ObdResetCommand(ObdResetCommand other) {
super(other);
}
/**
* Reset command returns an empty string, so we must override the following
* two methods.
* @throws IOException
*/
@Override
public void readResult(InputStream in) throws IOException {
// do nothing
return;
}
@Override
public String getResult() {
return "";
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult()
*/
@Override
public String getFormattedResult() {
return getResult();
}
@Override
public String getName() {
return "Reset OBD";
}
} | Java |
/*
* TODO put description
*/
package eu.lighthouselabs.obd.commands.protocol;
import eu.lighthouselabs.obd.commands.ObdCommand;
/**
* This will set the value of time in milliseconds (ms) that the OBD interface
* will wait for a response from the ECU. If exceeds, the response is "NO DATA".
*/
public class TimeoutObdCommand extends ObdCommand {
/**
* @param a
* value between 0 and 255 that multiplied by 4 results in the
* desired timeout in milliseconds (ms).
*/
public TimeoutObdCommand(int timeout) {
super("AT ST " + Integer.toHexString(0xFF & timeout));
}
/**
* @param other
*/
public TimeoutObdCommand(ObdCommand other) {
super(other);
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult()
*/
@Override
public String getFormattedResult() {
return getResult();
}
@Override
public String getName() {
return "Timeout";
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.protocol;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.enums.ObdProtocols;
/**
* Select the protocol to use.
*/
public class SelectProtocolObdCommand extends ObdCommand {
private final ObdProtocols _protocol;
/**
* @param command
*/
public SelectProtocolObdCommand(ObdProtocols protocol) {
super("AT SP " + protocol.getValue());
_protocol = protocol;
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult()
*/
@Override
public String getFormattedResult() {
return getResult();
}
@Override
public String getName() {
return "Select Protocol " + _protocol.name();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.protocol;
import eu.lighthouselabs.obd.commands.ObdCommand;
/**
* Turns off line-feed.
*/
public class LineFeedOffObdCommand extends ObdCommand {
/**
* @param command
*/
public LineFeedOffObdCommand() {
super("AT L0");
}
/**
* @param other
*/
public LineFeedOffObdCommand(ObdCommand other) {
super(other);
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult()
*/
@Override
public String getFormattedResult() {
return getResult();
}
@Override
public String getName() {
return "Line Feed Off";
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.temperature;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* Engine Coolant Temperature.
*/
public class EngineCoolantTemperatureObdCommand extends TemperatureObdCommand {
/**
*
*/
public EngineCoolantTemperatureObdCommand() {
super("01 05");
}
/**
* @param other
*/
public EngineCoolantTemperatureObdCommand(TemperatureObdCommand other) {
super(other);
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.commands.ObdCommand#getName()
*/
@Override
public String getName() {
return AvailableCommandNames.ENGINE_COOLANT_TEMP.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.temperature;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* TODO
*
* put description
*/
public class AirIntakeTemperatureObdCommand extends TemperatureObdCommand {
public AirIntakeTemperatureObdCommand() {
super("01 0F");
}
public AirIntakeTemperatureObdCommand(AirIntakeTemperatureObdCommand other) {
super(other);
}
@Override
public String getName() {
return AvailableCommandNames.AIR_INTAKE_TEMP.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.temperature;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.commands.SystemOfUnits;
/**
* TODO
*
* put description
*/
public abstract class TemperatureObdCommand extends ObdCommand implements SystemOfUnits {
private float temperature = 0.0f;
/**
* Default ctor.
*
* @param cmd
*/
public TemperatureObdCommand(String cmd) {
super(cmd);
}
/**
* Copy ctor.
*
* @param other
*/
public TemperatureObdCommand(TemperatureObdCommand other) {
super(other);
}
/**
* TODO
*
* put description of why we subtract 40
*
* @param temp
* @return
*/
protected final float prepareTempValue(float temp) {
return temp - 40;
}
/**
* Get values from 'buff', since we can't rely on char/string for calculations.
*
* @return Temperature in Celsius or Fahrenheit.
*/
@Override
public String getFormattedResult() {
String res = getResult();
if (!"NODATA".equals(res)) {
// ignore first two bytes [hh hh] of the response
temperature = prepareTempValue(buffer.get(2));
// convert?
if (useImperialUnits)
res = String.format("%.1f%s", getImperialUnit(), "F");
else
res = String.format("%.0f%s", temperature, "C");
}
return res;
}
/**
* @return the temperature in Celsius.
*/
public float getTemperature() {
return temperature;
}
/**
* @return the temperature in Fahrenheit.
*/
public float getImperialUnit() {
return temperature * 1.8f + 32;
}
/**
* @return the temperature in Kelvin.
*/
public float getKelvin() {
return temperature + 273.15f;
}
/**
* @return the OBD command name.
*/
public abstract String getName();
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.temperature;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* Ambient Air Temperature.
*/
public class AmbientAirTemperatureObdCommand extends TemperatureObdCommand {
/**
* @param cmd
*/
public AmbientAirTemperatureObdCommand() {
super("01 46");
}
/**
* @param other
*/
public AmbientAirTemperatureObdCommand(TemperatureObdCommand other) {
super(other);
}
@Override
public String getName() {
return AvailableCommandNames.AMBIENT_AIR_TEMP.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.utils;
/**
* Misc utilities
*/
public final class ObdUtils {
/**
* @param an integer value
* @return the equivalent FuelType name.
*/
public final static String getFuelTypeName(int value) {
String name = null;
switch (value) {
case 1:
name = "Gasoline";
break;
case 2:
name = "Methanol";
break;
case 3:
name = "Ethanol";
break;
case 4:
name = "Diesel";
break;
case 5:
name = "GPL/LGP";
break;
case 6:
name = "Natural Gas (CNG)";
break;
case 7:
name = "Propane";
break;
case 8:
name = "Electric";
break;
case 9:
name = "Biodiesel + Gasoline";
break;
case 10:
name = "Biodiesel + Methanol";
break;
case 11:
name = "Biodiesel + Ethanol";
break;
case 12:
name = "Biodiesel + GPL/LPG";
break;
case 13:
name = "Biodiesel + Natural Gas";
break;
case 14:
name = "Biodiesel + Propane";
break;
case 15:
name = "Biodiesel + Electric";
break;
case 16:
name = "Biodiesel + Gasoline/Electric";
break;
case 17:
name = "Hybrid Gasoline";
break;
case 18:
name = "Hybrid Ethanol";
break;
case 19:
name = "Hybrid Diesel";
break;
case 20:
name = "Hybrid Electric";
break;
case 21:
name = "Hybrid Mixed";
break;
case 22:
name = "Hybrid Regenerative";
break;
default:
name = "NODATA";
}
return name;
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.fuel;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* Get fuel level in percentage
*/
public class FuelLevelObdCommand extends ObdCommand {
private float fuelLevel = 0f;
/**
* @param command
*/
public FuelLevelObdCommand() {
super("01 2F");
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult()
*/
@Override
public String getFormattedResult() {
if (!"NODATA".equals(getResult())) {
// ignore first two bytes [hh hh] of the response
fuelLevel = 100.0f * buffer.get(2) / 255.0f;
}
return String.format("%.1f%s", fuelLevel, "%");
}
@Override
public String getName() {
return AvailableCommandNames.FUEL_LEVEL.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.fuel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.commands.SpeedObdCommand;
import eu.lighthouselabs.obd.commands.control.CommandEquivRatioObdCommand;
import eu.lighthouselabs.obd.commands.engine.EngineRPMObdCommand;
import eu.lighthouselabs.obd.commands.pressure.IntakeManifoldPressureObdCommand;
import eu.lighthouselabs.obd.commands.temperature.AirIntakeTemperatureObdCommand;
/**
* TODO put description
*/
public class FuelEconomyWithoutMAFObdCommand extends ObdCommand {
public static final double AIR_FUEL_RATIO = 14.64;
public static final double FUEL_DENSITY_GRAMS_PER_LITER = 720.0;
public FuelEconomyWithoutMAFObdCommand() {
super("");
}
/**
* As it's a fake command, neither do we need to send request or read
* response.
*/
@Override
public void run(InputStream in, OutputStream out) throws IOException,
InterruptedException {
// prepare variables
EngineRPMObdCommand rpmCmd = new EngineRPMObdCommand();
rpmCmd.run(in, out);
rpmCmd.getFormattedResult();
AirIntakeTemperatureObdCommand airTempCmd = new AirIntakeTemperatureObdCommand();
airTempCmd.run(in, out);
airTempCmd.getFormattedResult();
SpeedObdCommand speedCmd = new SpeedObdCommand();
speedCmd.run(in, out);
speedCmd.getFormattedResult();
CommandEquivRatioObdCommand equivCmd = new CommandEquivRatioObdCommand();
equivCmd.run(in, out);
equivCmd.getFormattedResult();
IntakeManifoldPressureObdCommand pressCmd = new IntakeManifoldPressureObdCommand();
pressCmd.run(in, out);
pressCmd.getFormattedResult();
double imap = rpmCmd.getRPM() * pressCmd.getMetricUnit() / airTempCmd.getKelvin();
// double maf = (imap / 120) * (speedCmd.getMetricSpeed()/100)*()
}
@Override
public String getFormattedResult() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
}
| Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.fuel;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
import eu.lighthouselabs.obd.enums.FuelType;
/**
* TODO put description
*/
public class FuelEconomyWithMAFObdCommand {
private int speed = 1;
private double maf = 1;
private float ltft = 1;
private double ratio = 1;
private FuelType fuelType;
private boolean useImperial = false;
double mpg = -1;
double litersPer100Km = -1;
/**
* @param command
*/
public FuelEconomyWithMAFObdCommand(FuelType fuelType, int speed,
double maf, float ltft, boolean useImperial) {
this.fuelType = fuelType;
this.speed = speed;
this.maf = maf;
this.ltft = ltft;
this.useImperial = useImperial;
mpg = (14.7 * 6.17 * 454 * speed * 0.621371) / (3600 * maf);
// mpg = 710.7 * speed / maf * (1 + ltft / 100);
// mpg = (14.7 * ratio * 6.17 * 454.0 * speed * 0.621371) / (3600.0 * maf);
// mpg = (14.7 * (1 + ltft / 100) * 6.17 * 454.0 * speed * 0.621371) / (3600.0 * maf);
// litersPer100Km = mpg / 2.2352;
litersPer100Km = 235.2 / mpg;
// float fuelDensity = 0.71f;
// if (fuelType.equals(FuelType.DIESEL))
// fuelDensity = 0.832f;
// litersPer100Km = (maf / 14.7 / fuelDensity * 3600) * (1 + ltft / 100)
// / speed;
}
/**
* As it's a fake command, neither do we need to send request or read
* response.
*/
public double getMPG() {
return mpg;
}
/**
* @return the fuel consumption in l/100km
*/
public double getLitersPer100Km() {
return litersPer100Km;
}
public String getFormattedResult() {
String res = "NODATA";
res = String.format("%.2f%s", litersPer100Km, "l/100km");
if (useImperial)
res = String.format("%.1f%s", mpg, "mpg");
return res;
}
public String getName() {
return AvailableCommandNames.FUEL_ECONOMY_WITH_MAF.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.fuel;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.commands.SpeedObdCommand;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* TODO put description
*/
public class FuelEconomyObdCommand extends ObdCommand {
protected float kml = -1.0f;
private float speed = -1.0f;
/**
* Default ctor.
*/
public FuelEconomyObdCommand() {
super("");
}
/**
* As it's a fake command, neither do we need to send request or read
* response.
*/
@Override
public void run(InputStream in, OutputStream out) throws IOException,
InterruptedException {
// get consumption liters per hour
FuelConsumptionObdCommand fuelConsumptionCommand = new FuelConsumptionObdCommand();
fuelConsumptionCommand.run(in, out);
fuelConsumptionCommand.getFormattedResult();
float fuelConsumption = fuelConsumptionCommand.getLitersPerHour();
// get metric speed
SpeedObdCommand speedCommand = new SpeedObdCommand();
speedCommand.run(in, out);
speedCommand.getFormattedResult();
speed = speedCommand.getMetricSpeed();
// get l/100km
kml = (100 / speed) * fuelConsumption;
}
/**
*
* @return
*/
@Override
public String getFormattedResult() {
if (useImperialUnits) {
// convert to mpg
return String.format("%.1f %s", getMilesPerUKGallon(), "mpg");
}
return String.format("%.1f %s", kml, "l/100km");
}
public float getLitersPer100Km() {
return kml;
}
public float getMilesPerUSGallon() {
return 235.2f / kml;
}
public float getMilesPerUKGallon() {
return 282.5f / kml;
}
@Override
public String getName() {
return AvailableCommandNames.FUEL_ECONOMY.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.fuel;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.enums.FuelTrim;
/**
* Get Fuel Trim.
*
*/
public class FuelTrimObdCommand extends ObdCommand {
private float fuelTrimValue = 0.0f;
private final FuelTrim bank;
/**
* Default ctor.
*
* Will read the bank from parameters and construct the command accordingly.
* Please, see FuelTrim enum for more details.
*/
public FuelTrimObdCommand(FuelTrim bank) {
super(bank.getObdCommand());
this.bank = bank;
}
/**
* @param value
* @return
*/
private float prepareTempValue(int value) {
Double perc = (value - 128) * (100.0 / 128);
return Float.parseFloat(perc.toString());
}
@Override
public String getFormattedResult() {
if (!"NODATA".equals(getResult())) {
// ignore first two bytes [hh hh] of the response
fuelTrimValue = prepareTempValue(buffer.get(2));
}
return String.format("%.2f%s", fuelTrimValue, "%");
}
/**
* @return the readed Fuel Trim percentage value.
*/
public final float getValue() {
return fuelTrimValue;
}
/**
* @return the name of the bank in string representation.
*/
public final String getBank() {
return bank.getBank();
}
@Override
public String getName() {
return bank.getBank();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.fuel;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* TODO put description
*/
public class FuelConsumptionObdCommand extends ObdCommand {
private float fuelRate = -1.0f;
public FuelConsumptionObdCommand() {
super("01 5E");
}
public FuelConsumptionObdCommand(ObdCommand other) {
super(other);
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.commands.ObdCommand#getFormattedResult()
*/
@Override
public String getFormattedResult() {
if (!"NODATA".equals(getResult())) {
// ignore first two bytes [hh hh] of the response
int a = buffer.get(2);
int b = buffer.get(3);
fuelRate = (a * 256 + b) * 0.05f;
}
String res = String.format("%.1f%s", fuelRate, "");
return res;
}
public float getLitersPerHour() {
return fuelRate;
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.commands.ObdCommand#getName()
*/
@Override
public String getName() {
return AvailableCommandNames.FUEL_CONSUMPTION.getValue();
}
}
| Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.fuel;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.commands.utils.ObdUtils;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* This command is intended to determine the vehicle fuel type.
*/
public class FindFuelTypeObdCommand extends ObdCommand {
private int fuelType = 0;
/**
* Default ctor.
*/
public FindFuelTypeObdCommand() {
super("10 51");
}
/**
* Copy ctor
*
* @param other
*/
public FindFuelTypeObdCommand(ObdCommand other) {
super(other);
}
/*
* (non-Javadoc)
*
* @see eu.lighthouselabs.obd.command.ObdCommand#getFormattedResult()
*/
@Override
public String getFormattedResult() {
String res = getResult();
if (!"NODATA".equals(res)) {
// ignore first two bytes [hh hh] of the response
fuelType = buffer.get(2);
res = getFuelTypeName();
}
return res;
}
/**
* @return Fuel type name.
*/
public final String getFuelTypeName() {
return ObdUtils.getFuelTypeName(fuelType);
}
@Override
public String getName() {
return AvailableCommandNames.FUEL_TYPE.getValue();
}
} | Java |
package eu.lighthouselabs.obd.commands.pressure;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
public class FuelPressureObdCommand extends PressureObdCommand {
public FuelPressureObdCommand() {
super("010A");
}
public FuelPressureObdCommand(FuelPressureObdCommand other) {
super(other);
}
/**
* TODO
*
* put description of why we multiply by 3
*
* @param temp
* @return
*/
@Override
protected final int preparePressureValue() {
return tempValue * 3;
}
@Override
public String getName() {
return AvailableCommandNames.FUEL_PRESSURE.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.pressure;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* Intake Manifold Pressure
*/
public class IntakeManifoldPressureObdCommand extends PressureObdCommand {
/**
* Default ctor.
*/
public IntakeManifoldPressureObdCommand() {
super("01 0B");
}
/**
* Copy ctor.
*
* @param other
*/
public IntakeManifoldPressureObdCommand(
IntakeManifoldPressureObdCommand other) {
super(other);
}
@Override
public String getName() {
return AvailableCommandNames.INTAKE_MANIFOLD_PRESSURE.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands.pressure;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.commands.SystemOfUnits;
/**
* TODO put description
*/
public abstract class PressureObdCommand extends ObdCommand implements
SystemOfUnits {
protected int tempValue = 0;
protected int pressure = 0;
/**
* Default ctor
*
* @param cmd
*/
public PressureObdCommand(String cmd) {
super(cmd);
}
/**
* Copy ctor.
*
* @param cmd
*/
public PressureObdCommand(PressureObdCommand other) {
super(other);
}
/**
* Some PressureObdCommand subclasses will need to implement this method in
* order to determine the final kPa value.
*
* *NEED* to read tempValue
*
* @return
*/
protected int preparePressureValue() {
return tempValue;
}
/**
*
*/
@Override
public String getFormattedResult() {
String res = getResult();
if (!"NODATA".equals(res)) {
// ignore first two bytes [hh hh] of the response
tempValue = buffer.get(2);
pressure = preparePressureValue(); // this will need tempValue
res = String.format("%d%s", pressure, "kPa");
if (useImperialUnits) {
res = String.format("%.1f%s", getImperialUnit(), "psi");
}
}
return res;
}
/**
* @return the pressure in kPa
*/
public int getMetricUnit() {
return pressure;
}
/**
* @return the pressure in psi
*/
public float getImperialUnit() {
Double d = pressure * 0.145037738;
return Float.valueOf(d.toString());
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands;
/**
* This interface will define methods for converting to/from imperial units and
* from/to metric units.
*/
public interface SystemOfUnits {
float getImperialUnit();
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
/**
* TODO put description
*/
public abstract class ObdCommand {
protected ArrayList<Integer> buffer = null;
protected String cmd = null;
protected boolean useImperialUnits = false;
protected String rawData = null;
/**
* Default ctor to use
*
* @param command
* the command to send
*/
public ObdCommand(String command) {
this.cmd = command;
this.buffer = new ArrayList<Integer>();
}
/**
* Prevent empty instantiation
*/
private ObdCommand() {
}
/**
* Copy ctor.
*
* @param other
* the ObdCommand to copy.
*/
public ObdCommand(ObdCommand other) {
this(other.cmd);
}
/**
* Sends the OBD-II request and deals with the response.
*
* This method CAN be overriden in fake commands.
*/
public void run(InputStream in, OutputStream out) throws IOException,
InterruptedException {
sendCommand(out);
readResult(in);
}
/**
* Sends the OBD-II request.
*
* This method may be overriden in subclasses, such as ObMultiCommand or
* TroubleCodesObdCommand.
*
* @param cmd
* The command to send.
*/
protected void sendCommand(OutputStream out) throws IOException,
InterruptedException {
// add the carriage return char
cmd += "\r";
// write to OutputStream, or in this case a BluetoothSocket
out.write(cmd.getBytes());
out.flush();
/*
* HACK GOLDEN HAMMER ahead!!
*
* TODO clean
*
* Due to the time that some systems may take to respond, let's give it
* 500ms.
*/
Thread.sleep(200);
}
/**
* Resends this command.
*
*
*/
protected void resendCommand(OutputStream out) throws IOException,
InterruptedException {
out.write("\r".getBytes());
out.flush();
/*
* HACK GOLDEN HAMMER ahead!!
*
* TODO clean this
*
* Due to the time that some systems may take to respond, let's give it
* 500ms.
*/
// Thread.sleep(250);
}
/**
* Reads the OBD-II response.
*
* This method may be overriden in subclasses, such as ObdMultiCommand.
*/
protected void readResult(InputStream in) throws IOException {
byte b = 0;
StringBuilder res = new StringBuilder();
// read until '>' arrives
while ((char) (b = (byte) in.read()) != '>')
if ((char) b != ' ')
res.append((char) b);
/*
* Imagine the following response 41 0c 00 0d.
*
* ELM sends strings!! So, ELM puts spaces between each "byte". And pay
* attention to the fact that I've put the word byte in quotes, because
* 41 is actually TWO bytes (two chars) in the socket. So, we must do
* some more processing..
*/
//
rawData = res.toString().trim();
// clear buffer
buffer.clear();
// read string each two chars
int begin = 0;
int end = 2;
while (end <= rawData.length()) {
String temp = "0x" + rawData.substring(begin, end);
buffer.add(Integer.decode(temp));
begin = end;
end += 2;
}
}
/**
* @return the raw command response in string representation.
*/
public String getResult() {
if (rawData.contains("SEARCHING") || rawData.contains("DATA")) {
rawData = "NODATA";
}
return rawData;
}
/**
* @return a formatted command response in string representation.
*/
public abstract String getFormattedResult();
/******************************************************************
* Getters & Setters
*/
/**
* @return a list of integers
*/
public ArrayList<Integer> getBuffer() {
return buffer;
}
/**
* Returns this command in string representation.
*
* @return the command
*/
public String getCommand() {
return cmd;
}
/**
* @return true if imperial units are used, or false otherwise
*/
public boolean useImperialUnits() {
return useImperialUnits;
}
/**
* Set to 'true' if you want to use imperial units, false otherwise. By
* default this value is set to 'false'.
*
* @param isImperial
*/
public void useImperialUnits(boolean isImperial) {
this.useImperialUnits = isImperial;
}
/**
* @return the OBD command name.
*/
public abstract String getName();
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
/**
* TODO put description
*/
public class ObdMultiCommand {
private ArrayList<ObdCommand> commands;
/**
* Default ctor.
*/
public ObdMultiCommand() {
this.commands = new ArrayList<ObdCommand>();
}
/**
* Add ObdCommand to list of ObdCommands.
*
* @param command
*/
public void add(ObdCommand command) {
this.commands.add(command);
}
/**
* Removes ObdCommand from the list of ObdCommands.
* @param command
*/
public void remove(ObdCommand command) {
this.commands.remove(command);
}
/**
* Iterate all commands and call:
* - sendCommand()
* - readResult()
*/
public void sendCommands(InputStream in, OutputStream out) throws IOException,
InterruptedException {
for (ObdCommand command : commands) {
/*
* Send command and read response.
*/
command.run(in, out);
}
}
/**
*
* @return
*/
public String getFormattedResult() {
StringBuilder res = new StringBuilder();
for (ObdCommand command : commands) {
res.append(command.getFormattedResult()).append(",");
}
return res.toString();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.commands;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
/**
* TODO put description
*
* Current speed.
*/
public class SpeedObdCommand extends ObdCommand implements SystemOfUnits {
private int metricSpeed = 0;
/**
* Default ctor.
*/
public SpeedObdCommand() {
super("01 0D");
}
/**
* Copy ctor.
*
* @param other
*/
public SpeedObdCommand(SpeedObdCommand other) {
super(other);
}
/**
*
*/
public String getFormattedResult() {
String res = getResult();
if (!"NODATA".equals(res)) {
//Ignore first two bytes [hh hh] of the response.
metricSpeed = buffer.get(2);
res = String.format("%d%s", metricSpeed, "km/h");
if (useImperialUnits)
res = String.format("%.2f%s", getImperialUnit(),
"mph");
}
return res;
}
/**
* @return the speed in metric units.
*/
public int getMetricSpeed() {
return metricSpeed;
}
/**
* @return the speed in imperial units.
*/
public float getImperialSpeed() {
return getImperialUnit();
}
/**
* Convert from km/h to mph
*/
public float getImperialUnit() {
Double tempValue = metricSpeed * 0.621371192;
return Float.valueOf(tempValue.toString());
}
@Override
public String getName() {
return AvailableCommandNames.SPEED.getValue();
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.enums;
/**
* TODO put description
*/
public enum AvailableCommandNames {
AIR_INTAKE_TEMP("Air Intake Temperature"),
AMBIENT_AIR_TEMP("Ambient Air Temperature"),
ENGINE_COOLANT_TEMP("Engine Coolant Temperature"),
BAROMETRIC_PRESSURE("Barometric Pressure"),
FUEL_PRESSURE("Fuel Pressure"),
INTAKE_MANIFOLD_PRESSURE("Intake Manifold Pressure"),
ENGINE_LOAD("Engine Load"),
ENGINE_RUNTIME("Engine Runtime"),
ENGINE_RPM("Engine RPM"),
SPEED("Vehicle Speed"),
MAF("Mass Air Flow"),
THROTTLE_POS("Throttle Position"),
TROUBLE_CODES("Trouble Codes"),
FUEL_LEVEL("Fuel Level"),
FUEL_TYPE("Fuel Type"),
FUEL_CONSUMPTION("Fuel Consumption"),
FUEL_ECONOMY("Fuel Economy"),
FUEL_ECONOMY_WITH_MAF("Fuel Economy 2"),
FUEL_ECONOMY_WITHOUT_MAF("Fuel Economy 3"),
TIMING_ADVANCE("Timing Advance"),
DTC_NUMBER("Diagnostic Trouble Codes"),
EQUIV_RATIO("Command Equivalence Ratio");
private final String value;
/**
*
* @param value
*/
private AvailableCommandNames(String value) {
this.value = value;
}
/**
*
* @return
*/
public final String getValue() {
return value;
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.enums;
/**
* All OBD protocols.
*/
public enum ObdProtocols {
/**
* Auto select protocol and save.
*/
AUTO('0'),
/**
* 41.6 kbaud
*/
SAE_J1850_PWM('1'),
/**
* 10.4 kbaud
*/
SAE_J1850_VPW('2'),
/**
* 5 baud init
*/
ISO_9141_2('3'),
/**
* 5 baud init
*/
ISO_14230_4_KWP('4'),
/**
* Fast init
*/
ISO_14230_4_KWP_FAST('5'),
/**
* 11 bit ID, 500 kbaud
*/
ISO_15765_4_CAN('6'),
/**
* 29 bit ID, 500 kbaud
*/
ISO_15765_4_CAN_B('7'),
/**
* 11 bit ID, 250 kbaud
*/
ISO_15765_4_CAN_C('8'),
/**
* 29 bit ID, 250 kbaud
*/
ISO_15765_4_CAN_D('9'),
/**
* 29 bit ID, 250 kbaud (user adjustable)
*/
SAE_J1939_CAN('A'),
/**
* 11 bit ID (user adjustable), 125 kbaud (user adjustable)
*/
USER1_CAN('B'),
/**
* 11 bit ID (user adjustable), 50 kbaud (user adjustable)
*/
USER2_CAN('C');
private final char value;
ObdProtocols(char value) {
this.value = value;
}
public char getValue() {
return value;
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.enums;
/**
* Select one of the Fuel Trim percentage banks to access.
*/
public enum FuelTrim {
SHORT_TERM_BANK_1(0x06),
LONG_TERM_BANK_1(0x07),
SHORT_TERM_BANK_2(0x08),
LONG_TERM_BANK_2(0x09);
private final int value;
/**
*
* @param value
*/
private FuelTrim(int value) {
this.value = value;
}
/**
*
* @return
*/
public final int getValue() {
return value;
}
/**
*
* @return
*/
public final String getObdCommand() {
return new String("01 " + value);
}
public final String getBank() {
String res = "NODATA";
switch (value) {
case 0x06:
res = "Short Term Fuel Trim Bank 1";
break;
case 0x07:
res = "Long Term Fuel Trim Bank 1";
break;
case 0x08:
res = "Short Term Fuel Trim Bank 2";
break;
case 0x09:
res = "Long Term Fuel Trim Bank 2";
break;
default:
break;
}
return res;
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.enums;
import eu.lighthouselabs.obd.commands.utils.ObdUtils;
/**
* MODE 1 PID 0x51 will return one of the following values to identify the fuel
* type of the vehicle.
*/
public enum FuelType {
GASOLINE(0x01),
METHANOL(0x02),
ETHANOL(0x03),
DIESEL(0x04),
LPG(0x05),
CNG(0x06),
PROPANE(0x07),
ELECTRIC(0x08),
BIFUEL_GASOLINE(0x09),
BIFUEL_METHANOL(0x0A),
BIFUEL_ETHANOL(0x0B),
BIFUEL_LPG(0x0C),
BIFUEL_CNG(0x0D),
BIFUEL_PROPANE(0x0E),
BIFUEL_ELECTRIC(0x0F),
BIFUEL_GASOLINE_ELECTRIC(0x10),
HYBRID_GASOLINE(0x11),
HYBRID_ETHANOL(0x12),
HYBRID_DIESEL(0x13),
HYBRID_ELECTRIC(0x14),
HYBRID_MIXED(0x15),
HYBRID_REGENERATIVE(0x16);
private final int value;
/**
*
* @param value
*/
private FuelType(int value) {
this.value = value;
}
/**
*
* @return
*/
public final int getValue() {
return value;
}
/**
*
* @return
*/
public final String getName() {
return ObdUtils.getFuelTypeName(value);
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.reader.config;
import java.util.ArrayList;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.commands.SpeedObdCommand;
import eu.lighthouselabs.obd.commands.control.CommandEquivRatioObdCommand;
import eu.lighthouselabs.obd.commands.control.DtcNumberObdCommand;
import eu.lighthouselabs.obd.commands.control.TimingAdvanceObdCommand;
import eu.lighthouselabs.obd.commands.control.TroubleCodesObdCommand;
import eu.lighthouselabs.obd.commands.engine.EngineLoadObdCommand;
import eu.lighthouselabs.obd.commands.engine.EngineRPMObdCommand;
import eu.lighthouselabs.obd.commands.engine.EngineRuntimeObdCommand;
import eu.lighthouselabs.obd.commands.engine.MassAirFlowObdCommand;
import eu.lighthouselabs.obd.commands.engine.ThrottlePositionObdCommand;
import eu.lighthouselabs.obd.commands.fuel.FindFuelTypeObdCommand;
import eu.lighthouselabs.obd.commands.fuel.FuelLevelObdCommand;
import eu.lighthouselabs.obd.commands.fuel.FuelTrimObdCommand;
import eu.lighthouselabs.obd.commands.pressure.BarometricPressureObdCommand;
import eu.lighthouselabs.obd.commands.pressure.FuelPressureObdCommand;
import eu.lighthouselabs.obd.commands.pressure.IntakeManifoldPressureObdCommand;
import eu.lighthouselabs.obd.commands.protocol.ObdResetCommand;
import eu.lighthouselabs.obd.commands.temperature.AirIntakeTemperatureObdCommand;
import eu.lighthouselabs.obd.commands.temperature.AmbientAirTemperatureObdCommand;
import eu.lighthouselabs.obd.commands.temperature.EngineCoolantTemperatureObdCommand;
import eu.lighthouselabs.obd.enums.FuelTrim;
/**
* TODO put description
*/
public final class ObdConfig {
public static ArrayList<ObdCommand> getCommands() {
ArrayList<ObdCommand> cmds = new ArrayList<ObdCommand>();
// Protocol
cmds.add(new ObdResetCommand());
// Control
cmds.add(new CommandEquivRatioObdCommand());
cmds.add(new DtcNumberObdCommand());
cmds.add(new TimingAdvanceObdCommand());
cmds.add(new TroubleCodesObdCommand(0));
// Engine
cmds.add(new EngineLoadObdCommand());
cmds.add(new EngineRPMObdCommand());
cmds.add(new EngineRuntimeObdCommand());
cmds.add(new MassAirFlowObdCommand());
// Fuel
// cmds.add(new AverageFuelEconomyObdCommand());
// cmds.add(new FuelEconomyObdCommand());
// cmds.add(new FuelEconomyMAPObdCommand());
// cmds.add(new FuelEconomyCommandedMAPObdCommand());
cmds.add(new FindFuelTypeObdCommand());
cmds.add(new FuelLevelObdCommand());
cmds.add(new FuelTrimObdCommand(FuelTrim.LONG_TERM_BANK_1));
cmds.add(new FuelTrimObdCommand(FuelTrim.LONG_TERM_BANK_2));
cmds.add(new FuelTrimObdCommand(FuelTrim.SHORT_TERM_BANK_1));
cmds.add(new FuelTrimObdCommand(FuelTrim.SHORT_TERM_BANK_2));
// Pressure
cmds.add(new BarometricPressureObdCommand());
cmds.add(new FuelPressureObdCommand());
cmds.add(new IntakeManifoldPressureObdCommand());
// Temperature
cmds.add(new AirIntakeTemperatureObdCommand());
cmds.add(new AmbientAirTemperatureObdCommand());
cmds.add(new EngineCoolantTemperatureObdCommand());
// Misc
cmds.add(new SpeedObdCommand());
cmds.add(new ThrottlePositionObdCommand());
return cmds;
}
} | Java |
package eu.lighthouselabs.obd.reader.network;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class DataUploader {
public String uploadRecord(String urlStr, Map<String,String> data) throws IOException, URISyntaxException {
String encData = getEncodedData(data);
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 30000);
HttpClient client = new DefaultHttpClient(params);
HttpPost request = new HttpPost();
request.setURI(new URI(urlStr));
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setEntity(new StringEntity(encData));
ResponseHandler<String> resHandle = new BasicResponseHandler();
String response = client.execute(request,resHandle);
return response;
}
public String getEncodedData(Map<String,String> data) throws UnsupportedEncodingException {
StringBuffer buff = new StringBuffer();
Iterator<String> keys = data.keySet().iterator();
while (keys.hasNext()) {
String k = keys.next();
buff.append(URLEncoder.encode(k,"UTF-8"));
buff.append("=");
buff.append(URLEncoder.encode(data.get(k),"UTF-8"));
buff.append("&");
}
return buff.toString();
}
}
| Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.reader;
import eu.lighthouselabs.obd.reader.io.ObdCommandJob;
/**
* TODO put description
*/
public interface IPostMonitor {
void setListener(IPostListener callback);
boolean isRunning();
void executeQueue();
void addJobToQueue(ObdCommandJob job);
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.reader;
import eu.lighthouselabs.obd.reader.io.ObdCommandJob;
/**
* TODO put description
*/
public interface IPostListener {
void stateUpdate(ObdCommandJob job);
} | Java |
package eu.lighthouselabs.obd.reader.drawable;
import eu.lighthouselabs.obd.reader.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
public class CoolantGaugeView extends GradientGaugeView {
public final static int min_temp = 35;
public final static int max_temp = 138;
public final static int TEXT_SIZE = 18;
public final static int range = max_temp - min_temp;
private int temp = min_temp;
public CoolantGaugeView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
paint = new Paint();
paint.setTextSize(TEXT_SIZE);
Typeface bold = Typeface.defaultFromStyle(Typeface.BOLD);
paint.setTypeface(bold);
paint.setStrokeWidth(3);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
}
public void setTemp(int temp) {
this.temp = temp;
if (this.temp < min_temp) {
this.temp = min_temp + 2;
}
if (this.temp > max_temp) {
this.temp = max_temp;
}
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
Resources res = context.getResources();
Drawable container = (Drawable) res.getDrawable(R.drawable.coolant_gauge);
int width = getWidth();
int left = getLeft();
int top = getTop();
paint.setColor(Color.BLUE);
canvas.drawText("C",left,top+TEXT_SIZE,paint);
paint.setColor(Color.RED);
canvas.drawText("H", left+width-TEXT_SIZE, top+TEXT_SIZE, paint);
drawGradient(canvas, container, TEXT_SIZE+5, temp-min_temp,range);
}
}
| Java |
package eu.lighthouselabs.obd.reader.drawable;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public abstract class GradientGaugeView extends View {
protected Context context = null;
protected Paint paint = null;
public GradientGaugeView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
paint = new Paint();
}
@Override
protected abstract void onDraw(Canvas canvas);
protected void drawGradient(Canvas canvas, Drawable container, int offset, double value, double range) {
int width = getWidth();
int height = getHeight();
int left = getLeft();
int top = getTop();
Log.i("width",String.format("%d %d",width,left));
container.setBounds(left,top+offset,left+width,top+height+offset);
container.draw(canvas);
ShapeDrawable cover = new ShapeDrawable(new RectShape());
double perc = value / range;
int coverLeft = (int)(width * perc);
cover.setBounds(left+coverLeft, top+offset, left+width, top+height+offset);
cover.draw(canvas);
}
}
| Java |
package eu.lighthouselabs.obd.reader.drawable;
import eu.lighthouselabs.obd.reader.R;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
public class AccelGaugeView extends GradientGaugeView {
public final static int TEXT_SIZE = 15;
public final static int range = 20;
private double accel = 2;
public AccelGaugeView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
paint = new Paint();
paint.setTextSize(TEXT_SIZE);
Typeface bold = Typeface.defaultFromStyle(Typeface.BOLD);
paint.setTypeface(bold);
paint.setStrokeWidth(3);
paint.setStyle(Paint.Style.FILL);
}
public void setAccel(double accel) {
this.accel = accel;
}
@Override
protected void onDraw(Canvas canvas) {
Resources res = context.getResources();
Drawable container = (Drawable) res.getDrawable(R.drawable.accel_gauge);
int width = getWidth();
int left = getLeft();
int top = getTop();
paint.setColor(Color.GREEN);
canvas.drawText("Soft",left,top+TEXT_SIZE,paint);
paint.setColor(Color.RED);
canvas.drawText("Hard", left+width-TEXT_SIZE*3, top+TEXT_SIZE, paint);
drawGradient(canvas, container, TEXT_SIZE+5, accel, range);
}
}
| Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.reader.activity;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import eu.lighthouselabs.obd.commands.SpeedObdCommand;
import eu.lighthouselabs.obd.commands.control.CommandEquivRatioObdCommand;
import eu.lighthouselabs.obd.commands.engine.EngineRPMObdCommand;
import eu.lighthouselabs.obd.commands.engine.MassAirFlowObdCommand;
import eu.lighthouselabs.obd.commands.fuel.FuelEconomyObdCommand;
import eu.lighthouselabs.obd.commands.fuel.FuelEconomyWithMAFObdCommand;
import eu.lighthouselabs.obd.commands.fuel.FuelLevelObdCommand;
import eu.lighthouselabs.obd.commands.fuel.FuelTrimObdCommand;
import eu.lighthouselabs.obd.commands.temperature.AmbientAirTemperatureObdCommand;
import eu.lighthouselabs.obd.enums.AvailableCommandNames;
import eu.lighthouselabs.obd.enums.FuelTrim;
import eu.lighthouselabs.obd.enums.FuelType;
import eu.lighthouselabs.obd.reader.IPostListener;
import eu.lighthouselabs.obd.reader.R;
import eu.lighthouselabs.obd.reader.io.ObdCommandJob;
import eu.lighthouselabs.obd.reader.io.ObdGatewayService;
import eu.lighthouselabs.obd.reader.io.ObdGatewayServiceConnection;
/**
* The main activity.
*/
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
/*
* TODO put description
*/
static final int NO_BLUETOOTH_ID = 0;
static final int BLUETOOTH_DISABLED = 1;
static final int NO_GPS_ID = 2;
static final int START_LIVE_DATA = 3;
static final int STOP_LIVE_DATA = 4;
static final int SETTINGS = 5;
static final int COMMAND_ACTIVITY = 6;
static final int TABLE_ROW_MARGIN = 7;
static final int NO_ORIENTATION_SENSOR = 8;
private Handler mHandler = new Handler();
/**
* Callback for ObdGatewayService to update UI.
*/
private IPostListener mListener = null;
private Intent mServiceIntent = null;
private ObdGatewayServiceConnection mServiceConnection = null;
private SensorManager sensorManager = null;
private Sensor orientSensor = null;
private SharedPreferences prefs = null;
private PowerManager powerManager = null;
private PowerManager.WakeLock wakeLock = null;
private boolean preRequisites = true;
private int speed = 1;
private double maf = 1;
private float ltft = 0;
private double equivRatio = 1;
private final SensorEventListener orientListener = new SensorEventListener() {
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
String dir = "";
if (x >= 337.5 || x < 22.5) {
dir = "N";
} else if (x >= 22.5 && x < 67.5) {
dir = "NE";
} else if (x >= 67.5 && x < 112.5) {
dir = "E";
} else if (x >= 112.5 && x < 157.5) {
dir = "SE";
} else if (x >= 157.5 && x < 202.5) {
dir = "S";
} else if (x >= 202.5 && x < 247.5) {
dir = "SW";
} else if (x >= 247.5 && x < 292.5) {
dir = "W";
} else if (x >= 292.5 && x < 337.5) {
dir = "NW";
}
TextView compass = (TextView) findViewById(R.id.compass_text);
updateTextView(compass, dir);
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
};
public void updateTextView(final TextView view, final String txt) {
new Handler().post(new Runnable() {
public void run() {
view.setText(txt);
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* TODO clean-up this upload thing
*
* ExceptionHandler.register(this,
* "http://www.whidbeycleaning.com/droid/server.php");
*/
setContentView(R.layout.main);
mListener = new IPostListener() {
public void stateUpdate(ObdCommandJob job) {
String cmdName = job.getCommand().getName();
String cmdResult = job.getCommand().getFormattedResult();
Log.d(TAG, FuelTrim.LONG_TERM_BANK_1.getBank() + " equals " + cmdName + "?");
if (AvailableCommandNames.ENGINE_RPM.getValue().equals(cmdName)) {
TextView tvRpm = (TextView) findViewById(R.id.rpm_text);
tvRpm.setText(cmdResult);
} else if (AvailableCommandNames.SPEED.getValue().equals(
cmdName)) {
TextView tvSpeed = (TextView) findViewById(R.id.spd_text);
tvSpeed.setText(cmdResult);
speed = ((SpeedObdCommand) job.getCommand())
.getMetricSpeed();
} else if (AvailableCommandNames.MAF.getValue().equals(cmdName)) {
maf = ((MassAirFlowObdCommand) job.getCommand()).getMAF();
addTableRow(cmdName, cmdResult);
} else if (FuelTrim.LONG_TERM_BANK_1.getBank().equals(cmdName)) {
ltft = ((FuelTrimObdCommand) job.getCommand()).getValue();
} else if (AvailableCommandNames.EQUIV_RATIO.getValue().equals(cmdName)) {
equivRatio = ((CommandEquivRatioObdCommand) job.getCommand()).getRatio();
addTableRow(cmdName, cmdResult);
} else {
addTableRow(cmdName, cmdResult);
}
}
};
/*
* Validate GPS service.
*/
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.getProvider(LocationManager.GPS_PROVIDER) == null) {
/*
* TODO for testing purposes we'll not make GPS a pre-requisite.
*/
// preRequisites = false;
showDialog(NO_GPS_ID);
}
/*
* Validate Bluetooth service.
*/
// Bluetooth device exists?
final BluetoothAdapter mBtAdapter = BluetoothAdapter
.getDefaultAdapter();
if (mBtAdapter == null) {
preRequisites = false;
showDialog(NO_BLUETOOTH_ID);
} else {
// Bluetooth device is enabled?
if (!mBtAdapter.isEnabled()) {
preRequisites = false;
showDialog(BLUETOOTH_DISABLED);
}
}
/*
* Get Orientation sensor.
*/
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
List<Sensor> sens = sensorManager
.getSensorList(Sensor.TYPE_ORIENTATION);
if (sens.size() <= 0) {
showDialog(NO_ORIENTATION_SENSOR);
} else {
orientSensor = sens.get(0);
}
// validate app pre-requisites
if (preRequisites) {
/*
* Prepare service and its connection
*/
mServiceIntent = new Intent(this, ObdGatewayService.class);
mServiceConnection = new ObdGatewayServiceConnection();
mServiceConnection.setServiceListener(mListener);
// bind service
Log.d(TAG, "Binding service..");
bindService(mServiceIntent, mServiceConnection,
Context.BIND_AUTO_CREATE);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
releaseWakeLockIfHeld();
mServiceIntent = null;
mServiceConnection = null;
mListener = null;
mHandler = null;
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "Pausing..");
releaseWakeLockIfHeld();
}
/**
* If lock is held, release. Lock will be held when the service is running.
*/
private void releaseWakeLockIfHeld() {
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
protected void onResume() {
super.onResume();
Log.d(TAG, "Resuming..");
sensorManager.registerListener(orientListener, orientSensor,
SensorManager.SENSOR_DELAY_UI);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
"ObdReader");
}
private void updateConfig() {
Intent configIntent = new Intent(this, ConfigActivity.class);
startActivity(configIntent);
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, START_LIVE_DATA, 0, "Start Live Data");
menu.add(0, COMMAND_ACTIVITY, 0, "Run Command");
menu.add(0, STOP_LIVE_DATA, 0, "Stop");
menu.add(0, SETTINGS, 0, "Settings");
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case START_LIVE_DATA:
startLiveData();
return true;
case STOP_LIVE_DATA:
stopLiveData();
return true;
case SETTINGS:
updateConfig();
return true;
// case COMMAND_ACTIVITY:
// staticCommand();
// return true;
}
return false;
}
// private void staticCommand() {
// Intent commandIntent = new Intent(this, ObdReaderCommandActivity.class);
// startActivity(commandIntent);
// }
private void startLiveData() {
Log.d(TAG, "Starting live data..");
if (!mServiceConnection.isRunning()) {
Log.d(TAG, "Service is not running. Going to start it..");
startService(mServiceIntent);
}
// start command execution
mHandler.post(mQueueCommands);
// screen won't turn off until wakeLock.release()
wakeLock.acquire();
}
private void stopLiveData() {
Log.d(TAG, "Stopping live data..");
if (mServiceConnection.isRunning())
stopService(mServiceIntent);
// remove runnable
mHandler.removeCallbacks(mQueueCommands);
releaseWakeLockIfHeld();
}
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder build = new AlertDialog.Builder(this);
switch (id) {
case NO_BLUETOOTH_ID:
build.setMessage("Sorry, your device doesn't support Bluetooth.");
return build.create();
case BLUETOOTH_DISABLED:
build.setMessage("You have Bluetooth disabled. Please enable it!");
return build.create();
case NO_GPS_ID:
build.setMessage("Sorry, your device doesn't support GPS.");
return build.create();
case NO_ORIENTATION_SENSOR:
build.setMessage("Orientation sensor missing?");
return build.create();
}
return null;
}
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem startItem = menu.findItem(START_LIVE_DATA);
MenuItem stopItem = menu.findItem(STOP_LIVE_DATA);
MenuItem settingsItem = menu.findItem(SETTINGS);
MenuItem commandItem = menu.findItem(COMMAND_ACTIVITY);
// validate if preRequisites are satisfied.
if (preRequisites) {
if (mServiceConnection.isRunning()) {
startItem.setEnabled(false);
stopItem.setEnabled(true);
settingsItem.setEnabled(false);
commandItem.setEnabled(false);
} else {
stopItem.setEnabled(false);
startItem.setEnabled(true);
settingsItem.setEnabled(true);
commandItem.setEnabled(false);
}
} else {
startItem.setEnabled(false);
stopItem.setEnabled(false);
settingsItem.setEnabled(false);
commandItem.setEnabled(false);
}
return true;
}
private void addTableRow(String key, String val) {
TableLayout tl = (TableLayout) findViewById(R.id.data_table);
TableRow tr = new TableRow(this);
MarginLayoutParams params = new ViewGroup.MarginLayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(TABLE_ROW_MARGIN, TABLE_ROW_MARGIN, TABLE_ROW_MARGIN,
TABLE_ROW_MARGIN);
tr.setLayoutParams(params);
tr.setBackgroundColor(Color.BLACK);
TextView name = new TextView(this);
name.setGravity(Gravity.RIGHT);
name.setText(key + ": ");
TextView value = new TextView(this);
value.setGravity(Gravity.LEFT);
value.setText(val);
tr.addView(name);
tr.addView(value);
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
/*
* TODO remove this hack
*
* let's define a limit number of rows
*/
if (tl.getChildCount() > 10)
tl.removeViewAt(0);
}
/**
*
*/
private Runnable mQueueCommands = new Runnable() {
public void run() {
/*
* If values are not default, then we have values to calculate MPG
*/
Log.d(TAG, "SPD:" + speed + ", MAF:" + maf + ", LTFT:" + ltft);
if (speed > 1 && maf > 1 && ltft != 0) {
FuelEconomyWithMAFObdCommand fuelEconCmd = new FuelEconomyWithMAFObdCommand(
FuelType.DIESEL, speed, maf, ltft, false /* TODO */);
TextView tvMpg = (TextView) findViewById(R.id.fuel_econ_text);
String liters100km = String.format("%.2f", fuelEconCmd.getLitersPer100Km());
tvMpg.setText("" + liters100km);
Log.d(TAG, "FUELECON:" + liters100km);
}
if (mServiceConnection.isRunning())
queueCommands();
// run again in 2s
mHandler.postDelayed(mQueueCommands, 2000);
}
};
/**
*
*/
private void queueCommands() {
final ObdCommandJob airTemp = new ObdCommandJob(
new AmbientAirTemperatureObdCommand());
final ObdCommandJob speed = new ObdCommandJob(new SpeedObdCommand());
final ObdCommandJob fuelEcon = new ObdCommandJob(
new FuelEconomyObdCommand());
final ObdCommandJob rpm = new ObdCommandJob(new EngineRPMObdCommand());
final ObdCommandJob maf = new ObdCommandJob(new MassAirFlowObdCommand());
final ObdCommandJob fuelLevel = new ObdCommandJob(
new FuelLevelObdCommand());
final ObdCommandJob ltft1 = new ObdCommandJob(new FuelTrimObdCommand(
FuelTrim.LONG_TERM_BANK_1));
final ObdCommandJob ltft2 = new ObdCommandJob(new FuelTrimObdCommand(
FuelTrim.LONG_TERM_BANK_2));
final ObdCommandJob stft1 = new ObdCommandJob(new FuelTrimObdCommand(
FuelTrim.SHORT_TERM_BANK_1));
final ObdCommandJob stft2 = new ObdCommandJob(new FuelTrimObdCommand(
FuelTrim.SHORT_TERM_BANK_2));
final ObdCommandJob equiv = new ObdCommandJob(new CommandEquivRatioObdCommand());
// mServiceConnection.addJobToQueue(airTemp);
mServiceConnection.addJobToQueue(speed);
// mServiceConnection.addJobToQueue(fuelEcon);
mServiceConnection.addJobToQueue(rpm);
mServiceConnection.addJobToQueue(maf);
mServiceConnection.addJobToQueue(fuelLevel);
// mServiceConnection.addJobToQueue(equiv);
mServiceConnection.addJobToQueue(ltft1);
// mServiceConnection.addJobToQueue(ltft2);
// mServiceConnection.addJobToQueue(stft1);
// mServiceConnection.addJobToQueue(stft2);
}
} | Java |
/*
* TODO put header
*/
package eu.lighthouselabs.obd.reader.activity;
import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.widget.Toast;
import eu.lighthouselabs.obd.commands.ObdCommand;
import eu.lighthouselabs.obd.reader.R;
import eu.lighthouselabs.obd.reader.config.ObdConfig;
/**
* Configuration activity.
*/
public class ConfigActivity extends PreferenceActivity implements
OnPreferenceChangeListener {
public static final String BLUETOOTH_LIST_KEY = "bluetooth_list_preference";
public static final String UPLOAD_URL_KEY = "upload_url_preference";
public static final String UPLOAD_DATA_KEY = "upload_data_preference";
public static final String UPDATE_PERIOD_KEY = "update_period_preference";
public static final String VEHICLE_ID_KEY = "vehicle_id_preference";
public static final String ENGINE_DISPLACEMENT_KEY = "engine_displacement_preference";
public static final String VOLUMETRIC_EFFICIENCY_KEY = "volumetric_efficiency_preference";
public static final String IMPERIAL_UNITS_KEY = "imperial_units_preference";
public static final String COMMANDS_SCREEN_KEY = "obd_commands_screen";
public static final String ENABLE_GPS_KEY = "enable_gps_preference";
public static final String MAX_FUEL_ECON_KEY = "max_fuel_econ_preference";
public static final String CONFIG_READER_KEY = "reader_config_preference";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
* Read preferences resources available at res/xml/preferences.xml
*/
addPreferencesFromResource(R.xml.preferences);
ArrayList<CharSequence> pairedDeviceStrings = new ArrayList<CharSequence>();
ArrayList<CharSequence> vals = new ArrayList<CharSequence>();
ListPreference listBtDevices = (ListPreference) getPreferenceScreen()
.findPreference(BLUETOOTH_LIST_KEY);
String[] prefKeys = new String[] { ENGINE_DISPLACEMENT_KEY,
VOLUMETRIC_EFFICIENCY_KEY, UPDATE_PERIOD_KEY, MAX_FUEL_ECON_KEY };
for (String prefKey : prefKeys) {
EditTextPreference txtPref = (EditTextPreference) getPreferenceScreen()
.findPreference(prefKey);
txtPref.setOnPreferenceChangeListener(this);
}
/*
* Available OBD commands
*
* TODO This should be read from preferences database
*/
ArrayList<ObdCommand> cmds = ObdConfig.getCommands();
PreferenceScreen cmdScr = (PreferenceScreen) getPreferenceScreen()
.findPreference(COMMANDS_SCREEN_KEY);
for (ObdCommand cmd : cmds) {
CheckBoxPreference cpref = new CheckBoxPreference(this);
cpref.setTitle(cmd.getName());
cpref.setKey(cmd.getName());
cpref.setChecked(true);
cmdScr.addPreference(cpref);
}
/*
* Let's use this device Bluetooth adapter to select which paired OBD-II
* compliant device we'll use.
*/
final BluetoothAdapter mBtAdapter = BluetoothAdapter
.getDefaultAdapter();
if (mBtAdapter == null) {
listBtDevices.setEntries(pairedDeviceStrings
.toArray(new CharSequence[0]));
listBtDevices.setEntryValues(vals.toArray(new CharSequence[0]));
// we shouldn't get here, still warn user
Toast.makeText(this, "This device does not support Bluetooth.",
Toast.LENGTH_LONG);
return;
}
/*
* Listen for preferences click.
*
* TODO there are so many repeated validations :-/
*/
final Activity thisActivity = this;
listBtDevices.setEntries(new CharSequence[1]);
listBtDevices.setEntryValues(new CharSequence[1]);
listBtDevices
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// see what I mean in the previous comment?
if (mBtAdapter == null || !mBtAdapter.isEnabled()) {
Toast.makeText(
thisActivity,
"This device does not support Bluetooth or it is disabled.",
Toast.LENGTH_LONG);
return false;
}
return true;
}
});
/*
* Get paired devices and populate preference list.
*/
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDeviceStrings.add(device.getName() + "\n"
+ device.getAddress());
vals.add(device.getAddress());
}
}
listBtDevices.setEntries(pairedDeviceStrings
.toArray(new CharSequence[0]));
listBtDevices.setEntryValues(vals.toArray(new CharSequence[0]));
}
/**
* OnPreferenceChangeListener method that will validate a preferencen new
* value when it's changed.
*
* @param preference
* the changed preference
* @param newValue
* the value to be validated and set if valid
*/
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (UPDATE_PERIOD_KEY.equals(preference.getKey())
|| VOLUMETRIC_EFFICIENCY_KEY.equals(preference.getKey())
|| ENGINE_DISPLACEMENT_KEY.equals(preference.getKey())
|| UPDATE_PERIOD_KEY.equals(preference.getKey())
|| MAX_FUEL_ECON_KEY.equals(preference.getKey())) {
try {
Double.parseDouble(newValue.toString());
return true;
} catch (Exception e) {
Toast.makeText(
this,
"Couldn't parse '" + newValue.toString()
+ "' as a number.", Toast.LENGTH_LONG).show();
}
}
return false;
}
/**
*
* @param prefs
* @return
*/
public static int getUpdatePeriod(SharedPreferences prefs) {
String periodString = prefs.getString(ConfigActivity.UPDATE_PERIOD_KEY,
"4"); // 4 as in seconds
int period = 4000; // by default 4000ms
try {
period = Integer.parseInt(periodString) * 1000;
} catch (Exception e) {
}
if (period <= 0) {
period = 250;
}
return period;
}
/**
*
* @param prefs
* @return
*/
public static double getVolumetricEfficieny(SharedPreferences prefs) {
String veString = prefs.getString(
ConfigActivity.VOLUMETRIC_EFFICIENCY_KEY, ".85");
double ve = 0.85;
try {
ve = Double.parseDouble(veString);
} catch (Exception e) {
}
return ve;
}
/**
*
* @param prefs
* @return
*/
public static double getEngineDisplacement(SharedPreferences prefs) {
String edString = prefs.getString(
ConfigActivity.ENGINE_DISPLACEMENT_KEY, "1.6");
double ed = 1.6;
try {
ed = Double.parseDouble(edString);
} catch (Exception e) {
}
return ed;
}
/**
*
* @param prefs
* @return
*/
public static ArrayList<ObdCommand> getObdCommands(SharedPreferences prefs) {
ArrayList<ObdCommand> cmds = ObdConfig.getCommands();
ArrayList<ObdCommand> ucmds = new ArrayList<ObdCommand>();
for (int i = 0; i < cmds.size(); i++) {
ObdCommand cmd = cmds.get(i);
boolean selected = prefs.getBoolean(cmd.getName(), true);
if (selected) {
ucmds.add(cmd);
}
}
return ucmds;
}
/**
*
* @param prefs
* @return
*/
public static double getMaxFuelEconomy(SharedPreferences prefs) {
String maxStr = prefs.getString(ConfigActivity.MAX_FUEL_ECON_KEY, "70");
double max = 70;
try {
max = Double.parseDouble(maxStr);
} catch (Exception e) {
}
return max;
}
/**
*
* @param prefs
* @return
*/
public static String[] getReaderConfigCommands(SharedPreferences prefs) {
String cmdsStr = prefs.getString(CONFIG_READER_KEY, "atsp0\natz");
String[] cmds = cmdsStr.split("\n");
return cmds;
}
} | Java |
/*
* 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();
}
}
} | Java |
/*
* 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
}
} | Java |
/*
* 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;
}
} | Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquaredSettings {
public static final boolean USE_DEBUG_SERVER = false;
public static final boolean DEBUG = false;
public static final boolean LOCATION_DEBUG = false;
public static final boolean USE_DUMPCATCHER = true;
public static final boolean DUMPCATCHER_TEST = false;
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare;
public class TestCredentials {
public static final String oAuthConsumerKey = "";
public static final String oAuthConsumerSecret = "";
public static final String oAuthToken = "";
public static final String oAuthTokenSecret = "";
public static final String testFoursquarePhone = "";
public static final String testFoursquarePassword = "";
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import com.joelapenna.foursquared.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* This activity can be used to run a facebook url request through a webview.
* The user must supply these intent extras:
* <ul>
* <li>INTENT_EXTRA_ACTION - string, which facebook action to perform, like
* "login", or "stream.publish".</li>
* <li>INTENT_EXTRA_KEY_APP_ID - string, facebook developer key.</li>
* <li>INTENT_EXTRA_KEY_PERMISSIONS - string array, set of facebook permissions
* you want to use.</li>
* </ul>
* or you can supply only INTENT_EXTRA_KEY_CLEAR_COOKIES to just have the
* activity clear its stored cookies (you can also supply it in combination with
* the above flags to clear cookies before trying to run a request too). If
* you've already authenticated the user, you can optionally pass in the token
* and expiration time as intent extras using:
* <ul>
* <li>INTENT_EXTRA_AUTHENTICATED_TOKEN</li>
* <li>INTENT_EXTRA_AUTHENTICATED_EXPIRES</li>
* </ul>
* they will then be used in web requests. You should use
* <code>startActivityForResult</code> to start the activity. When the activity
* finishes, it will return status code RESULT_OK. You can then check the
* returned intent data object for:
* <ul>
* <li>INTENT_RESULT_KEY_RESULT_STATUS - boolean, whether the request succeeded
* or not.</li>
* <li>INTENT_RESULT_KEY_SUPPLIED_ACTION - string, the action you supplied as an
* intent extra echoed back as a convenience.</li>
* <li>INTENT_RESULT_KEY_RESULT_BUNDLE - bundle, present if request succeeded,
* will have all the returned parameters as supplied by the WebView operation.</li>
* <li>INTENT_RESULT_KEY_ERROR - string, present if request failed.</li>
* </ul>
* If the user canceled this activity, the activity result code will be
* RESULT_CANCELED and there will be no intent data returned. You need the
* <code>android.permission.INTERNET</code> permission added to your manifest.
* You need to add this activity definition to your manifest. You can prevent
* this activity from restarting on rotation so the network operations are
* preserved within the WebView like so:
*
* <activity
* android:name="com.facebook.android.FacebookWebViewActivity"
* android:configChanges="orientation|keyboardHidden" />
*
* This class and the rest of the facebook classes within this package are from
* the facebook android library project:
*
* http://github.com/facebook/facebook-android-sdk
*
* The project implementation had several problems with it which made it unusable
* in a production application. It has been rewritten here for use with the
* Foursquare project.
*
* @date June 14, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class FacebookWebViewActivity extends Activity {
private static final String TAG = "FacebookWebViewActivity";
public static final String INTENT_EXTRA_ACTION = "com.facebook.android.FacebookWebViewActivity.action";
public static final String INTENT_EXTRA_KEY_APP_ID = "com.facebook.android.FacebookWebViewActivity.appid";
public static final String INTENT_EXTRA_KEY_PERMISSIONS = "com.facebook.android.FacebookWebViewActivity.permissions";
public static final String INTENT_EXTRA_AUTHENTICATED_TOKEN = "com.facebook.android.FacebookWebViewActivity.authenticated_token";
public static final String INTENT_EXTRA_AUTHENTICATED_EXPIRES = "com.facebook.android.FacebookWebViewActivity.authenticated_expires";
public static final String INTENT_EXTRA_KEY_CLEAR_COOKIES = "com.facebook.android.FacebookWebViewActivity.clear_cookies";
public static final String INTENT_EXTRA_KEY_DEBUG = "com.facebook.android.FacebookWebViewActivity.debug";
public static final String INTENT_RESULT_KEY_RESULT_STATUS = "result_status";
public static final String INTENT_RESULT_KEY_SUPPLIED_ACTION = "supplied_action";
public static final String INTENT_RESULT_KEY_RESULT_BUNDLE = "bundle";
public static final String INTENT_RESULT_KEY_ERROR = "error";
private static final String DISPLAY_STRING = "touch";
private static final int FB_BLUE = 0xFF6D84B4;
private static final int MARGIN = 4;
private static final int PADDING = 2;
private TextView mTitle;
private WebView mWebView;
private ProgressDialog mSpinner;
private String mAction;
private String mAppId;
private String[] mPermissions;
private boolean mDebug;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
CookieSyncManager.createInstance(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
mTitle = new TextView(this);
mTitle.setText("Facebook");
mTitle.setTextColor(Color.WHITE);
mTitle.setTypeface(Typeface.DEFAULT_BOLD);
mTitle.setBackgroundColor(FB_BLUE);
mTitle.setPadding(MARGIN + PADDING, MARGIN, MARGIN, MARGIN);
mTitle.setCompoundDrawablePadding(MARGIN + PADDING);
mTitle.setCompoundDrawablesWithIntrinsicBounds(this.getResources().getDrawable(
R.drawable.facebook_icon), null, null, null);
ll.addView(mTitle);
mWebView = new WebView(this);
mWebView.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mWebView.setWebViewClient(new WebViewClientFacebook());
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.getSettings().setJavaScriptEnabled(true);
ll.addView(mWebView);
mSpinner = new ProgressDialog(this);
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
setContentView(ll, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
Bundle extras = getIntent().getExtras();
if (extras != null) {
if (extras.containsKey(INTENT_EXTRA_KEY_DEBUG)) {
mDebug = extras.getBoolean(INTENT_EXTRA_KEY_DEBUG);
}
if (extras.containsKey(INTENT_EXTRA_ACTION)) {
if (extras.getBoolean(INTENT_EXTRA_KEY_CLEAR_COOKIES, false)) {
clearCookies();
}
if (extras.containsKey(INTENT_EXTRA_KEY_APP_ID)) {
if (extras.containsKey(INTENT_EXTRA_KEY_PERMISSIONS)) {
mAction = extras.getString(INTENT_EXTRA_ACTION);
mAppId = extras.getString(INTENT_EXTRA_KEY_APP_ID);
mPermissions = extras.getStringArray(INTENT_EXTRA_KEY_PERMISSIONS);
// If the user supplied a pre-authenticated info, use it
// here.
Facebook facebook = new Facebook();
if (extras.containsKey(INTENT_EXTRA_AUTHENTICATED_TOKEN) &&
extras.containsKey(INTENT_EXTRA_AUTHENTICATED_EXPIRES)) {
facebook.setAccessToken(extras
.getString(INTENT_EXTRA_AUTHENTICATED_TOKEN));
facebook.setAccessExpires(extras
.getLong(INTENT_EXTRA_AUTHENTICATED_EXPIRES));
if (mDebug) {
Log.d(TAG, "onCreate(): authenticated token being used.");
}
}
// Generate the url based on the action.
String url = facebook.generateUrl(mAction, mAppId, mPermissions);
if (mDebug) {
String permissionsDump = "(null)";
if (mPermissions != null) {
if (mPermissions.length > 0) {
for (int i = 0; i < mPermissions.length; i++) {
permissionsDump += mPermissions[i] + ", ";
}
} else {
permissionsDump = "[empty]";
}
}
Log.d(TAG, "onCreate(): action: " + mAction + ", appid: " + mAppId
+ ", permissions: " + permissionsDump);
Log.d(TAG, "onCreate(): Loading url: " + url);
}
// Start the request finally.
mWebView.loadUrl(url);
} else {
Log.e(TAG, "Missing intent extra: INTENT_EXTRA_KEY_PERMISSIONS, finishing immediately.");
finish();
}
} else {
Log.e(TAG, "Missing intent extra: INTENT_EXTRA_KEY_APP_ID, finishing immediately.");
finish();
}
} else if (extras.getBoolean(INTENT_EXTRA_KEY_CLEAR_COOKIES)) {
clearCookies();
} else {
Log.e(TAG, "Missing intent extra: INTENT_EXTRA_ACTION or INTENT_EXTRA_KEY_CLEAR_COOKIES, finishing immediately.");
finish();
}
} else {
Log.e(TAG, "No intent extras supplied, finishing immediately.");
finish();
}
}
private void clearCookies() {
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
@Override
protected void onResume() {
super.onResume();
CookieSyncManager.getInstance().startSync();
}
@Override
protected void onPause() {
super.onPause();
CookieSyncManager.getInstance().stopSync();
}
private class WebViewClientFacebook extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mDebug) {
Log.d(TAG, "WebViewClientFacebook:shouldOverrideUrlLoading(): " + url);
}
if (url.startsWith(Facebook.REDIRECT_URI)) {
Bundle values = FacebookUtil.parseUrl(url);
String error = values.getString("error_reason");
Intent result = new Intent();
result.putExtra(INTENT_RESULT_KEY_SUPPLIED_ACTION, mAction);
if (error == null) {
CookieSyncManager.getInstance().sync();
result.putExtra(INTENT_RESULT_KEY_RESULT_STATUS, true);
result.putExtra(INTENT_RESULT_KEY_RESULT_BUNDLE, values);
FacebookWebViewActivity.this.setResult(Activity.RESULT_OK, result);
} else {
result.putExtra(INTENT_RESULT_KEY_RESULT_STATUS, false);
result.putExtra(INTENT_RESULT_KEY_SUPPLIED_ACTION, mAction);
result.putExtra(INTENT_RESULT_KEY_ERROR, error);
FacebookWebViewActivity.this.setResult(Activity.RESULT_OK, result);
}
FacebookWebViewActivity.this.finish();
return true;
} else if (url.startsWith(Facebook.CANCEL_URI)) {
FacebookWebViewActivity.this.setResult(Activity.RESULT_CANCELED);
FacebookWebViewActivity.this.finish();
return true;
} else if (url.contains(DISPLAY_STRING)) {
return false;
}
// Launch non-dialog URLs in a full browser.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
if (mDebug) {
Log.e(TAG, "WebViewClientFacebook:onReceivedError(): " + errorCode + ", "
+ description + ", " + failingUrl);
}
Intent result = new Intent();
result.putExtra(INTENT_RESULT_KEY_RESULT_STATUS, false);
result.putExtra(INTENT_RESULT_KEY_SUPPLIED_ACTION, mAction);
result.putExtra(INTENT_RESULT_KEY_ERROR, description + ", " + errorCode + ", "
+ failingUrl);
FacebookWebViewActivity.this.setResult(Activity.RESULT_OK, result);
FacebookWebViewActivity.this.finish();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (mDebug) {
Log.d(TAG, "WebViewClientFacebook:onPageStarted(): " + url);
}
mSpinner.show();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mDebug) {
Log.d(TAG, "WebViewClientFacebook:onPageFinished(): " + url);
}
String title = mWebView.getTitle();
if (title != null && title.length() > 0) {
mTitle.setText(title);
}
mSpinner.dismiss();
}
}
}
| Java |
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
/**
* Encapsulation of a Facebook Error: a Facebook request that could not be
* fulfilled.
*
* @author ssoneff@facebook.com
*/
public class FacebookError extends Throwable {
private static final long serialVersionUID = 1L;
private int mErrorCode = 0;
private String mErrorType;
public FacebookError(String message) {
super(message);
}
public FacebookError(String message, String type, int code) {
super(message);
mErrorType = type;
mErrorCode = code;
}
public int getErrorCode() {
return mErrorCode;
}
public String getErrorType() {
return mErrorType;
}
} | Java |
/*
* Copyright 2010 Mark Wyszomierski
* Portions Copyright (c) 2008-2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import android.os.Bundle;
import android.text.TextUtils;
import java.io.IOException;
import java.net.MalformedURLException;
/**
* Main Facebook object for storing session token and session expiration date
* in memory, as well as generating urls to access different facebook endpoints.
*
* @author Steven Soneff (ssoneff@facebook.com):
* -original author.
* @author Mark Wyszomierski (markww@gmail.com):
* -modified to remove network operation calls, and dialog creation,
* focused on making this class only generate urls for external use
* and storage of a session token and expiration date.
*/
public class Facebook {
/** Strings used in the OAuth flow */
public static final String REDIRECT_URI = "fbconnect://success";
public static final String CANCEL_URI = "fbconnect:cancel";
public static final String TOKEN = "access_token";
public static final String EXPIRES = "expires_in";
/** Login action requires a few extra steps for setup and completion. */
public static final String LOGIN = "login";
/** Facebook server endpoints: may be modified in a subclass for testing */
protected static String OAUTH_ENDPOINT =
"https://graph.facebook.com/oauth/authorize"; // https
protected static String UI_SERVER =
"http://www.facebook.com/connect/uiserver.php"; // http
protected static String GRAPH_BASE_URL =
"https://graph.facebook.com/";
protected static String RESTSERVER_URL =
"https://api.facebook.com/restserver.php";
private String mAccessToken = null;
private long mAccessExpires = 0;
public Facebook() {
}
/**
* Invalidates the current access token in memory, and generates a
* prepared URL that can be used to log the user out.
*
* @throws MalformedURLException
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl logout()
throws MalformedURLException, IOException
{
setAccessToken(null);
setAccessExpires(0);
Bundle b = new Bundle();
b.putString("method", "auth.expireSession");
return requestUrl(b);
}
/**
* Build a url to Facebook's old (pre-graph) API with the given
* parameters. One of the parameter keys must be "method" and its value
* should be a valid REST server API method.
*
* See http://developers.facebook.com/docs/reference/rest/
*
* Example:
* <code>
* Bundle parameters = new Bundle();
* parameters.putString("method", "auth.expireSession");
* PreparedUrl preparedUrl = requestUrl(parameters);
* </code>
*
* @param parameters
* Key-value pairs of parameters to the request. Refer to the
* documentation: one of the parameters must be "method".
* @throws MalformedURLException
* if accessing an invalid endpoint
* @throws IllegalArgumentException
* if one of the parameters is not "method"
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl requestUrl(Bundle parameters)
throws MalformedURLException {
if (!parameters.containsKey("method")) {
throw new IllegalArgumentException("API method must be specified. "
+ "(parameters must contain key \"method\" and value). See"
+ " http://developers.facebook.com/docs/reference/rest/");
}
return requestUrl(null, parameters, "GET");
}
/**
* Build a url to the Facebook Graph API without any parameters.
*
* See http://developers.facebook.com/docs/api
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @throws MalformedURLException
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl requestUrl(String graphPath)
throws MalformedURLException {
return requestUrl(graphPath, new Bundle(), "GET");
}
/**
* Build a url to the Facebook Graph API with the given string
* parameters using an HTTP GET (default method).
*
* See http://developers.facebook.com/docs/api
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters "q" : "facebook" would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @throws MalformedURLException
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl requestUrl(String graphPath, Bundle parameters)
throws MalformedURLException {
return requestUrl(graphPath, parameters, "GET");
}
/**
* Build a PreparedUrl object which can be used with Util.openUrl().
* You can also use the returned PreparedUrl.getUrl() to run the
* network operation yourself.
*
* Note that binary data parameters
* (e.g. pictures) are not yet supported by this helper function.
*
* See http://developers.facebook.com/docs/api
*
* @param graphPath
* Path to resource in the Facebook graph, e.g., to fetch data
* about the currently logged authenticated user, provide "me",
* which will fetch http://graph.facebook.com/me
* @param parameters
* key-value string parameters, e.g. the path "search" with
* parameters {"q" : "facebook"} would produce a query for the
* following graph resource:
* https://graph.facebook.com/search?q=facebook
* @param httpMethod
* http verb, e.g. "GET", "POST", "DELETE"
* @throws MalformedURLException
* @return PreparedUrl instance reflecting the full url of the service.
*/
public PreparedUrl requestUrl(String graphPath,
Bundle parameters,
String httpMethod)
throws MalformedURLException
{
parameters.putString("format", "json");
if (isSessionValid()) {
parameters.putString(TOKEN, getAccessToken());
}
String url = graphPath != null ?
GRAPH_BASE_URL + graphPath :
RESTSERVER_URL;
return new PreparedUrl(url, parameters, httpMethod);
}
public boolean isSessionValid() {
return (getAccessToken() != null) && ((getAccessExpires() == 0) ||
(System.currentTimeMillis() < getAccessExpires()));
}
public String getAccessToken() {
return mAccessToken;
}
public long getAccessExpires() {
return mAccessExpires;
}
public void setAccessToken(String token) {
mAccessToken = token;
}
public void setAccessExpires(long time) {
mAccessExpires = time;
}
public void setAccessExpiresIn(String expiresIn) {
if (expiresIn != null) {
setAccessExpires(System.currentTimeMillis()
+ Integer.parseInt(expiresIn) * 1000);
}
}
public String generateUrl(String action, String appId, String[] permissions) {
Bundle params = new Bundle();
String endpoint;
if (action.equals(LOGIN)) {
params.putString("client_id", appId);
if (permissions != null && permissions.length > 0) {
params.putString("scope", TextUtils.join(",", permissions));
}
endpoint = OAUTH_ENDPOINT;
params.putString("type", "user_agent");
params.putString("redirect_uri", REDIRECT_URI);
} else {
endpoint = UI_SERVER;
params.putString("method", action);
params.putString("next", REDIRECT_URI);
}
params.putString("display", "touch");
params.putString("sdk", "android");
if (isSessionValid()) {
params.putString(TOKEN, getAccessToken());
}
String url = endpoint + "?" + FacebookUtil.encodeUrl(params);
return url;
}
/**
* Stores a prepared url and parameters bundle from one of the <code>requestUrl</code>
* methods. It can then be used with Util.openUrl() to run the network operation.
* The Util.openUrl() requires the original params bundle and http method, so this
* is just a convenience wrapper around it.
*
* @author Mark Wyszomierski (markww@gmail.com)
*/
public static class PreparedUrl
{
private String mUrl;
private Bundle mParameters;
private String mHttpMethod;
public PreparedUrl(String url, Bundle parameters, String httpMethod) {
mUrl = url;
mParameters = parameters;
mHttpMethod = httpMethod;
}
public String getUrl() {
return mUrl;
}
public Bundle getParameters() {
return mParameters;
}
public String getHttpMethod() {
return mHttpMethod;
}
}
} | Java |
/*
* Copyright 2010 Mark Wyszomierski
* Portions Copyright (c) 2008-2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.android;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
/**
* Utility class supporting the Facebook Object.
*
* @author ssoneff@facebook.com
* -original author.
* @author Mark Wyszomierski (markww@gmail.com):
* -just removed alert dialog method which can be handled by managed
* dialogs in third party apps.
*/
public final class FacebookUtil {
public static String encodeUrl(Bundle parameters) {
if (parameters == null) {
return "";
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String key : parameters.keySet()) {
if (first) first = false; else sb.append("&");
sb.append(key + "=" + parameters.getString(key));
}
return sb.toString();
}
public static Bundle decodeUrl(String s) {
Bundle params = new Bundle();
if (s != null) {
String array[] = s.split("&");
for (String parameter : array) {
String v[] = parameter.split("=");
params.putString(v[0], v[1]);
}
}
return params;
}
/**
* Parse a URL query and fragment parameters into a key-value bundle.
*
* @param url the URL to parse
* @return a dictionary bundle of keys and values
*/
public static Bundle parseUrl(String url) {
// hack to prevent MalformedURLException
url = url.replace("fbconnect", "http");
try {
URL u = new URL(url);
Bundle b = decodeUrl(u.getQuery());
b.putAll(decodeUrl(u.getRef()));
return b;
} catch (MalformedURLException e) {
return new Bundle();
}
}
/**
* Connect to an HTTP URL and return the response as a string.
*
* Note that the HTTP method override is used on non-GET requests. (i.e.
* requests are made as "POST" with method specified in the body).
*
* @param url - the resource to open: must be a welformed URL
* @param method - the HTTP method to use ("GET", "POST", etc.)
* @param params - the query parameter for the URL (e.g. access_token=foo)
* @return the URL contents as a String
* @throws MalformedURLException - if the URL format is invalid
* @throws IOException - if a network problem occurs
*/
public static String openUrl(String url, String method, Bundle params)
throws MalformedURLException, IOException {
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
}
HttpURLConnection conn =
(HttpURLConnection) new URL(url).openConnection();
conn.setRequestProperty("User-Agent", System.getProperties().
getProperty("http.agent") + " FacebookAndroidSDK");
if (!method.equals("GET")) {
// use method override
params.putString("method", method);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.getOutputStream().write(
encodeUrl(params).getBytes("UTF-8"));
}
String response = "";
try {
response = read(conn.getInputStream());
} catch (FileNotFoundException e) {
// Error Stream contains JSON that we can parse to a FB error
response = read(conn.getErrorStream());
}
return response;
}
private static String read(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}
in.close();
return sb.toString();
}
/**
* Parse a server response into a JSON Object. This is a basic
* implementation using org.json.JSONObject representation. More
* sophisticated applications may wish to do their own parsing.
*
* The parsed JSON is checked for a variety of error fields and
* a FacebookException is thrown if an error condition is set,
* populated with the error message and error type or code if
* available.
*
* @param response - string representation of the response
* @return the response as a JSON Object
* @throws JSONException - if the response is not valid JSON
* @throws FacebookError - if an error condition is set
*/
public static JSONObject parseJson(String response)
throws JSONException, FacebookError {
// Edge case: when sending a POST request to /[post_id]/likes
// the return value is 'true' or 'false'. Unfortunately
// these values cause the JSONObject constructor to throw
// an exception.
if (response.equals("false")) {
throw new FacebookError("request failed");
}
if (response.equals("true")) {
response = "{value : true}";
}
JSONObject json = new JSONObject(response);
// errors set by the server are not consistent
// they depend on the method and endpoint
if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
throw new FacebookError(
error.getString("message"), error.getString("type"), 0);
}
if (json.has("error_code") && json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"), "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_code")) {
throw new FacebookError("request failed", "",
Integer.parseInt(json.getString("error_code")));
}
if (json.has("error_msg")) {
throw new FacebookError(json.getString("error_msg"));
}
if (json.has("error_reason")) {
throw new FacebookError(json.getString("error_reason"));
}
return json;
}
public static String printBundle(Bundle bundle) {
StringBuilder sb = new StringBuilder();
sb.append("Bundle: ");
if (bundle != null) {
sb.append(bundle.toString()); sb.append("\n");
Set<String> keys = bundle.keySet();
for (String it : keys) {
sb.append(" ");
sb.append(it);
sb.append(": ");
sb.append(bundle.get(it).toString());
sb.append("\n");
}
} else {
sb.append("(null)");
}
return sb.toString();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquare.util.VenueUtils;
import com.joelapenna.foursquared.maps.CheckinGroup;
import com.joelapenna.foursquared.maps.CheckinGroupItemizedOverlay;
import com.joelapenna.foursquared.maps.CheckinGroupItemizedOverlay.CheckinGroupOverlayTapListener;
import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay;
import com.joelapenna.foursquared.util.CheckinTimestampSort;
import com.joelapenna.foursquared.util.GeoUtils;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.widget.MapCalloutView;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Added support for checkingroup items, also stopped recreation
* of overlay group in onResume(). [2010-06-21]
*/
public class FriendsMapActivity extends MapActivity {
public static final String TAG = "FriendsMapActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_CHECKIN_PARCELS = Foursquared.PACKAGE_NAME
+ ".FriendsMapActivity.EXTRA_CHECKIN_PARCELS";
private StateHolder mStateHolder;
private Venue mTappedVenue;
private MapCalloutView mCallout;
private MapView mMapView;
private MapController mMapController;
private List<CheckinGroupItemizedOverlay> mCheckinGroupOverlays;
private MyLocationOverlay mMyLocationOverlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_map_activity);
if (getLastNonConfigurationInstance() != null) {
mStateHolder = (StateHolder) getLastNonConfigurationInstance();
} else {
if (getIntent().hasExtra(EXTRA_CHECKIN_PARCELS)) {
Parcelable[] parcelables = getIntent().getParcelableArrayExtra(EXTRA_CHECKIN_PARCELS);
Group<Checkin> checkins = new Group<Checkin>();
for (int i = 0; i < parcelables.length; i++) {
checkins.add((Checkin)parcelables[i]);
}
mStateHolder = new StateHolder();
mStateHolder.setCheckins(checkins);
} else {
Log.e(TAG, "FriendsMapActivity requires checkin array in intent extras.");
finish();
return;
}
}
initMap();
}
@Override
public void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
if (UiUtil.sdkVersion() > 3) {
mMyLocationOverlay.enableCompass();
}
}
@Override
public void onPause() {
super.onPause();
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
}
private void initMap() {
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mMyLocationOverlay);
loadSearchResults(mStateHolder.getCheckins());
mCallout = (MapCalloutView) findViewById(R.id.map_callout);
mCallout.setVisibility(View.GONE);
mCallout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(FriendsMapActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, mTappedVenue);
startActivity(intent);
}
});
recenterMap();
}
private void loadSearchResults(Group<Checkin> checkins) {
// One CheckinItemizedOverlay per group!
CheckinGroupItemizedOverlay mappableCheckinsOverlay = createMappableCheckinsOverlay(checkins);
mCheckinGroupOverlays = new ArrayList<CheckinGroupItemizedOverlay>();
if (mappableCheckinsOverlay != null) {
mCheckinGroupOverlays.add(mappableCheckinsOverlay);
}
// Only add the list of checkin group overlays if it contains any overlays.
if (mCheckinGroupOverlays.size() > 0) {
mMapView.getOverlays().addAll(mCheckinGroupOverlays);
} else {
Toast.makeText(this, getResources().getString(
R.string.friendsmapactivity_no_checkins), Toast.LENGTH_LONG).show();
}
}
/**
* Create an overlay that contains a specific group's list of mappable
* checkins.
*/
private CheckinGroupItemizedOverlay createMappableCheckinsOverlay(Group<Checkin> group) {
// We want to group checkins by venue. Do max three checkins per venue, a total
// of 100 venues total. We should only also display checkins that are within a
// city radius, and are at most three hours old.
CheckinTimestampSort timestamps = new CheckinTimestampSort();
Map<String, CheckinGroup> checkinMap = new HashMap<String, CheckinGroup>();
for (int i = 0, m = group.size(); i < m; i++) {
Checkin checkin = (Checkin)group.get(i);
Venue venue = checkin.getVenue();
if (VenueUtils.hasValidLocation(venue)) {
// Make sure the venue is within city radius.
try {
int distance = Integer.parseInt(checkin.getDistance());
if (distance > FriendsActivity.CITY_RADIUS_IN_METERS) {
continue;
}
} catch (NumberFormatException ex) {
// Distance was invalid, ignore this checkin.
continue;
}
// Make sure the checkin happened within the last three hours.
try {
Date date = new Date(checkin.getCreated());
if (date.before(timestamps.getBoundaryRecent())) {
continue;
}
} catch (Exception ex) {
// Timestamps was invalid, ignore this checkin.
continue;
}
String venueId = venue.getId();
CheckinGroup cg = checkinMap.get(venueId);
if (cg == null) {
cg = new CheckinGroup();
checkinMap.put(venueId, cg);
}
// Stop appending if we already have three checkins here.
if (cg.getCheckinCount() < 3) {
cg.appendCheckin(checkin);
}
}
// We can't have too many pins on the map.
if (checkinMap.size() > 99) {
break;
}
}
Group<CheckinGroup> mappableCheckins = new Group<CheckinGroup>(checkinMap.values());
if (mappableCheckins.size() > 0) {
CheckinGroupItemizedOverlay mappableCheckinsGroupOverlay = new CheckinGroupItemizedOverlay(
this,
((Foursquared) getApplication()).getRemoteResourceManager(),
this.getResources().getDrawable(R.drawable.pin_checkin_multiple),
mCheckinGroupOverlayTapListener);
mappableCheckinsGroupOverlay.setGroup(mappableCheckins);
return mappableCheckinsGroupOverlay;
} else {
return null;
}
}
private void recenterMap() {
// Previously we'd try to zoom to span, but this gives us odd results a lot of times,
// so falling back to zoom at a fixed level.
GeoPoint center = mMyLocationOverlay.getMyLocation();
if (center != null) {
Log.i(TAG, "Using my location overlay as center point for map centering.");
mMapController.animateTo(center);
mMapController.setZoom(16);
} else {
// Location overlay wasn't ready yet, try using last known geolocation from manager.
Location bestLocation = GeoUtils.getBestLastGeolocation(this);
if (bestLocation != null) {
Log.i(TAG, "Using last known location for map centering.");
mMapController.animateTo(GeoUtils.locationToGeoPoint(bestLocation));
mMapController.setZoom(16);
} else {
// We have no location information at all, so we'll just show the map at a high
// zoom level and the user can zoom in as they wish.
Log.i(TAG, "No location available for map centering.");
mMapController.setZoom(8);
}
}
}
/** Handle taps on one of the pins. */
private CheckinGroupOverlayTapListener mCheckinGroupOverlayTapListener =
new CheckinGroupOverlayTapListener() {
@Override
public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, CheckinGroup cg) {
mTappedVenue = cg.getVenue();
mCallout.setTitle(cg.getVenue().getName());
mCallout.setMessage(cg.getDescription());
mCallout.setVisibility(View.VISIBLE);
mMapController.animateTo(new GeoPoint(cg.getLatE6(), cg.getLonE6()));
}
@Override
public void onTap(GeoPoint p, MapView mapView) {
mCallout.setVisibility(View.GONE);
}
};
@Override
protected boolean isRouteDisplayed() {
return false;
}
private static class StateHolder {
private Group<Checkin> mCheckins;
public StateHolder() {
mCheckins = new Group<Checkin>();
}
public Group<Checkin> getCheckins() {
return mCheckins;
}
public void setCheckins(Group<Checkin> checkins) {
mCheckins = checkins;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquared.util.NotificationsUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnCancelListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
/**
* Handles fetching an image from the web, then writes it to a temporary file on
* the sdcard so we can hand it off to a view intent. This activity can be
* styled with a custom transparent-background theme, so that it appears like a
* simple progress dialog to the user over whichever activity launches it,
* instead of two seaparate activities before they finally get to the
* image-viewing activity. The only required intent extra is the URL to download
* the image, the others are optional:
* <ul>
* <li>IMAGE_URL - String, url of the image to download, either jpeg or png.</li>
* <li>CONNECTION_TIMEOUT_IN_SECONDS - int, optional, max timeout wait for
* download, in seconds.</li>
* <li>READ_TIMEOUT_IN_SECONDS - int, optional, max timeout wait for read of
* image, in seconds.</li>
* <li>PROGRESS_BAR_TITLE - String, optional, title of the progress bar during
* download.</li>
* <li>PROGRESS_BAR_MESSAGE - String, optional, message body of the progress bar
* during download.</li>
* </ul>
*
* When the download is complete, the activity will return the path of the
* saved image on disk. The calling activity can then choose to launch an
* intent to view the image.
*
* @date February 25, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class FetchImageForViewIntent extends Activity {
private static final String TAG = "FetchImageForViewIntent";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final String TEMP_FILE_NAME = "tmp_fsq";
public static final String IMAGE_URL = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.IMAGE_URL";
public static final String CONNECTION_TIMEOUT_IN_SECONDS = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.CONNECTION_TIMEOUT_IN_SECONDS";
public static final String READ_TIMEOUT_IN_SECONDS = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.READ_TIMEOUT_IN_SECONDS";
public static final String PROGRESS_BAR_TITLE = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.PROGRESS_BAR_TITLE";
public static final String PROGRESS_BAR_MESSAGE = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.PROGRESS_BAR_MESSAGE";
public static final String LAUNCH_VIEW_INTENT_ON_COMPLETION = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.LAUNCH_VIEW_INTENT_ON_COMPLETION";
public static final String EXTRA_SAVED_IMAGE_PATH_RETURNED = Foursquared.PACKAGE_NAME
+ ".FetchImageForViewIntent.EXTRA_SAVED_IMAGE_PATH_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
setContentView(R.layout.fetch_image_for_view_intent_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
String url = null;
if (getIntent().getExtras().containsKey(IMAGE_URL)) {
url = getIntent().getExtras().getString(IMAGE_URL);
} else {
Log.e(TAG, "FetchImageForViewIntent requires intent extras parameter 'IMAGE_URL'.");
finish();
return;
}
if (DEBUG) Log.d(TAG, "Fetching image: " + url);
// Grab the extension of the file that should be present at the end
// of the url. We can do a better job of this, and could even check
// that the extension is of an expected type.
int posdot = url.lastIndexOf(".");
if (posdot < 0) {
Log.e(TAG, "FetchImageForViewIntent requires a url to an image resource with a file extension in its name.");
finish();
return;
}
String progressBarTitle = getIntent().getStringExtra(PROGRESS_BAR_TITLE);
String progressBarMessage = getIntent().getStringExtra(PROGRESS_BAR_MESSAGE);
if (progressBarMessage == null) {
progressBarMessage = "Fetching image...";
}
mStateHolder = new StateHolder();
mStateHolder.setLaunchViewIntentOnCompletion(
getIntent().getBooleanExtra(LAUNCH_VIEW_INTENT_ON_COMPLETION, true));
mStateHolder.startTask(
FetchImageForViewIntent.this,
url,
url.substring(posdot),
progressBarTitle,
progressBarMessage,
getIntent().getIntExtra(CONNECTION_TIMEOUT_IN_SECONDS, 20),
getIntent().getIntExtra(READ_TIMEOUT_IN_SECONDS, 20));
}
}
@Override
public void onResume() {
super.onResume();
if (mStateHolder.getIsRunning()) {
startProgressBar(mStateHolder.getProgressTitle(), mStateHolder.getProgressMessage());
}
}
@Override
public void onPause() {
super.onPause();
stopProgressBar();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void startProgressBar(String title, String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, title, message);
mDlgProgress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dlg) {
mStateHolder.cancel();
finish();
}
});
mDlgProgress.setCancelable(true);
}
mDlgProgress.setTitle(title);
mDlgProgress.setMessage(message);
}
private void stopProgressBar() {
if (mDlgProgress != null && mDlgProgress.isShowing()) {
mDlgProgress.dismiss();
}
mDlgProgress = null;
}
private void onFetchImageTaskComplete(Boolean result, String path, String extension,
Exception ex) {
try {
// If successful, start an intent to view the image.
if (result != null && result.equals(Boolean.TRUE)) {
// If the image can't be loaded or an intent can't be found to
// view it, launchViewIntent() will create a toast with an error
// message.
if (mStateHolder.getLaunchViewIntentOnCompletion()) {
launchViewIntent(path, extension);
} else {
// We'll finish now by handing the save image path back to the
// calling activity.
Intent intent = new Intent();
intent.putExtra(EXTRA_SAVED_IMAGE_PATH_RETURNED, path);
setResult(Activity.RESULT_OK, intent);
}
} else {
NotificationsUtil.ToastReasonForFailure(FetchImageForViewIntent.this, ex);
}
} finally {
// Whether download worked or not, we finish ourselves now. If an
// error occurred, the toast should remain on the calling activity.
mStateHolder.setIsRunning(false);
stopProgressBar();
finish();
}
}
private boolean launchViewIntent(String outputPath, String extension) {
Foursquared foursquared = (Foursquared) getApplication();
if (foursquared.getUseNativeImageViewerForFullScreenImages()) {
// Try to open the file now to create the uri we'll hand to the intent.
Uri uri = null;
try {
File file = new File(outputPath);
uri = Uri.fromFile(file);
} catch (Exception ex) {
Log.e(TAG, "Error opening downloaded image from temp location: ", ex);
Toast.makeText(this, "No application could be found to diplay the full image.",
Toast.LENGTH_SHORT);
return false;
}
// Try to start an intent to view the image. It's possible that the user
// may not have any intents to handle the request.
try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/" + extension);
startActivity(intent);
} catch (Exception ex) {
Log.e(TAG, "Error starting intent to view image: ", ex);
Toast.makeText(this, "There was an error displaying the image.", Toast.LENGTH_SHORT);
return false;
}
} else {
Intent intent = new Intent(this, FullSizeImageActivity.class);
intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_IMAGE_PATH, outputPath);
startActivity(intent);
}
return true;
}
/**
* Handles fetching the image from the net and saving it to disk in a task.
*/
private static class FetchImageTask extends AsyncTask<Void, Void, Boolean> {
private FetchImageForViewIntent mActivity;
private final String mUrl;
private String mExtension;
private final String mOutputPath;
private final int mConnectionTimeoutInSeconds;
private final int mReadTimeoutInSeconds;
private Exception mReason;
public FetchImageTask(FetchImageForViewIntent activity, String url, String extension,
int connectionTimeoutInSeconds, int readTimeoutInSeconds) {
mActivity = activity;
mUrl = url;
mExtension = extension;
mOutputPath = Environment.getExternalStorageDirectory() + "/" + TEMP_FILE_NAME;
mConnectionTimeoutInSeconds = connectionTimeoutInSeconds;
mReadTimeoutInSeconds = readTimeoutInSeconds;
}
public void setActivity(FetchImageForViewIntent activity) {
mActivity = activity;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
saveImage(mUrl, mOutputPath, mConnectionTimeoutInSeconds, mReadTimeoutInSeconds);
return Boolean.TRUE;
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "FetchImageTask: Exception while fetching image.", e);
mReason = e;
}
return Boolean.FALSE;
}
@Override
protected void onPostExecute(Boolean result) {
if (DEBUG) Log.d(TAG, "FetchImageTask: onPostExecute()");
if (mActivity != null) {
mActivity.onFetchImageTaskComplete(result, mOutputPath, mExtension, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onFetchImageTaskComplete(null, null, null,
new FoursquareException("Image download cancelled."));
}
}
}
public static void saveImage(String urlImage, String savePath, int connectionTimeoutInSeconds,
int readTimeoutInSeconds) throws Exception {
URL url = new URL(urlImage);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(connectionTimeoutInSeconds * 1000);
conn.setReadTimeout(readTimeoutInSeconds * 1000);
int contentLength = conn.getContentLength();
InputStream raw = conn.getInputStream();
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int bytesRead = 0;
int offset = 0;
while (offset < contentLength) {
bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1) {
break;
}
offset += bytesRead;
}
in.close();
if (offset != contentLength) {
Log.e(TAG, "Error fetching image, only read " + offset + " bytes of " + contentLength
+ " total.");
throw new FoursquareException("Error fetching full image, please try again.");
}
// This will fail if the user has no sdcard present, catch it specifically
// to alert user.
try {
FileOutputStream out = new FileOutputStream(savePath);
out.write(data);
out.flush();
out.close();
} catch (Exception ex) {
Log.e(TAG, "Error saving fetched image to disk.", ex);
throw new FoursquareException("Error opening fetched image, make sure an sdcard is present.");
}
}
/** Maintains state between rotations. */
private static class StateHolder {
FetchImageTask mTaskFetchImage;
boolean mIsRunning;
String mProgressTitle;
String mProgressMessage;
boolean mLaunchViewIntentOnCompletion;
public StateHolder() {
mIsRunning = false;
mLaunchViewIntentOnCompletion = true;
}
public void startTask(FetchImageForViewIntent activity, String url, String extension,
String progressBarTitle, String progressBarMessage, int connectionTimeoutInSeconds,
int readTimeoutInSeconds) {
mIsRunning = true;
mProgressTitle = progressBarTitle;
mProgressMessage = progressBarMessage;
mTaskFetchImage = new FetchImageTask(activity, url, extension,
connectionTimeoutInSeconds, readTimeoutInSeconds);
mTaskFetchImage.execute();
}
public void setActivity(FetchImageForViewIntent activity) {
if (mTaskFetchImage != null) {
mTaskFetchImage.setActivity(activity);
}
}
public void setIsRunning(boolean isRunning) {
mIsRunning = isRunning;
}
public boolean getIsRunning() {
return mIsRunning;
}
public String getProgressTitle() {
return mProgressTitle;
}
public String getProgressMessage() {
return mProgressMessage;
}
public void cancel() {
if (mTaskFetchImage != null) {
mTaskFetchImage.cancel(true);
mIsRunning = false;
}
}
public boolean getLaunchViewIntentOnCompletion() {
return mLaunchViewIntentOnCompletion;
}
public void setLaunchViewIntentOnCompletion(boolean launchViewIntentOnCompletion) {
mLaunchViewIntentOnCompletion = launchViewIntentOnCompletion;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay;
import com.joelapenna.foursquared.maps.VenueItemizedOverlayWithIcons;
import com.joelapenna.foursquared.maps.VenueItemizedOverlayWithIcons.VenueItemizedOverlayTapListener;
import com.joelapenna.foursquared.util.GeoUtils;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.widget.MapCalloutView;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Takes an array of venues and shows them on a map.
*
* @date June 30, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class NearbyVenuesMapActivity extends MapActivity {
public static final String TAG = "NearbyVenuesMapActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_VENUES = Foursquared.PACKAGE_NAME
+ ".NearbyVenuesMapActivity.INTENT_EXTRA_VENUES";
private StateHolder mStateHolder;
private String mTappedVenueId;
private MapCalloutView mCallout;
private MapView mMapView;
private MapController mMapController;
private ArrayList<VenueItemizedOverlayWithIcons> mVenueGroupOverlays =
new ArrayList<VenueItemizedOverlayWithIcons>();
private MyLocationOverlay mMyLocationOverlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_map_activity);
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
} else {
if (getIntent().hasExtra(INTENT_EXTRA_VENUES)) {
Parcelable[] parcelables = getIntent().getParcelableArrayExtra(
INTENT_EXTRA_VENUES);
Group<Venue> venues = new Group<Venue>();
for (int i = 0; i < parcelables.length; i++) {
venues.add((Venue)parcelables[i]);
}
mStateHolder = new StateHolder(venues);
} else {
Log.e(TAG, TAG + " requires venue array in intent extras.");
finish();
return;
}
}
ensureUi();
}
private void ensureUi() {
mMapView = (MapView) findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mMyLocationOverlay);
mCallout = (MapCalloutView) findViewById(R.id.map_callout);
mCallout.setVisibility(View.GONE);
mCallout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(NearbyVenuesMapActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, mTappedVenueId);
startActivity(intent);
}
});
// One CheckinItemizedOverlay per group!
VenueItemizedOverlayWithIcons mappableVenuesOverlay = createMappableVenuesOverlay(
mStateHolder.getVenues());
if (mappableVenuesOverlay != null) {
mVenueGroupOverlays.add(mappableVenuesOverlay);
}
if (mVenueGroupOverlays.size() > 0) {
mMapView.getOverlays().addAll(mVenueGroupOverlays);
recenterMap();
} else {
Toast.makeText(this, getResources().getString(
R.string.friendsmapactivity_no_checkins), Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
if (UiUtil.sdkVersion() > 3) {
mMyLocationOverlay.enableCompass();
}
}
@Override
public void onPause() {
super.onPause();
mMyLocationOverlay.disableMyLocation();
if (UiUtil.sdkVersion() > 3) {
mMyLocationOverlay.disableCompass();
}
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
/**
* We can do something more fun here like create an overlay per category, so the user
* can hide parks and show only bars, for example.
*/
private VenueItemizedOverlayWithIcons createMappableVenuesOverlay(Group<Venue> venues) {
Group<Venue> mappableVenues = new Group<Venue>();
for (Venue it : venues) {
mappableVenues.add(it);
}
if (mappableVenues.size() > 0) {
VenueItemizedOverlayWithIcons overlay = new VenueItemizedOverlayWithIcons(
this,
((Foursquared) getApplication()).getRemoteResourceManager(),
getResources().getDrawable(R.drawable.pin_checkin_multiple),
mVenueOverlayTapListener);
overlay.setGroup(mappableVenues);
return overlay;
} else {
return null;
}
}
private void recenterMap() {
// Previously we'd try to zoom to span, but this gives us odd results a lot of times,
// so falling back to zoom at a fixed level.
GeoPoint center = mMyLocationOverlay.getMyLocation();
if (center != null) {
mMapController.animateTo(center);
mMapController.setZoom(14);
} else {
// Location overlay wasn't ready yet, try using last known geolocation from manager.
Location bestLocation = GeoUtils.getBestLastGeolocation(this);
if (bestLocation != null) {
mMapController.animateTo(GeoUtils.locationToGeoPoint(bestLocation));
mMapController.setZoom(14);
} else {
// We have no location information at all, so we'll just show the map at a high
// zoom level and the user can zoom in as they wish.
Venue venue = mStateHolder.getVenues().get(0);
mMapController.animateTo(new GeoPoint(
(int)(Float.valueOf(venue.getGeolat()) * 1E6),
(int)(Float.valueOf(venue.getGeolong()) * 1E6)));
mMapController.setZoom(8);
}
}
}
/**
* Handle taps on one of the pins.
*/
private VenueItemizedOverlayTapListener mVenueOverlayTapListener =
new VenueItemizedOverlayTapListener() {
@Override
public void onTap(OverlayItem itemSelected, OverlayItem itemLastSelected, Venue venue) {
mTappedVenueId = venue.getId();
mCallout.setTitle(venue.getName());
mCallout.setMessage(venue.getAddress());
mCallout.setVisibility(View.VISIBLE);
mMapController.animateTo(GeoUtils.stringLocationToGeoPoint(
venue.getGeolat(), venue.getGeolong()));
}
@Override
public void onTap(GeoPoint p, MapView mapView) {
mCallout.setVisibility(View.GONE);
}
};
private class StateHolder {
private Group<Venue> mVenues;
public StateHolder(Group<Venue> venues) {
mVenues = venues;
}
public Group<Venue> getVenues() {
return mVenues;
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Response;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
/**
* Allows the user to add a new venue. This activity can also be used to submit
* edits to an existing venue. Pass a venue parcelable using the EXTRA_VENUE_TO_EDIT
* key to put the activity into edit mode.
*
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Added support for using this activity to edit existing venues (June 8, 2010).
*/
public class AddVenueActivity extends Activity {
private static final String TAG = "AddVenueActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_VENUE_TO_EDIT = "com.joelapenna.foursquared.VenueParcel";
private static final double MINIMUM_ACCURACY_FOR_ADDRESS = 100.0;
private static final int DIALOG_PICK_CATEGORY = 1;
private static final int DIALOG_ERROR = 2;
private StateHolder mStateHolder;
private EditText mNameEditText;
private EditText mAddressEditText;
private EditText mCrossstreetEditText;
private EditText mCityEditText;
private EditText mStateEditText;
private EditText mZipEditText;
private EditText mPhoneEditText;
private Button mAddOrEditVenueButton;
private LinearLayout mCategoryLayout;
private ImageView mCategoryImageView;
private TextView mCategoryTextView;
private ProgressBar mCategoryProgressBar;
private ProgressDialog mDlgProgress;
private TextWatcher mNameFieldWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mAddOrEditVenueButton.setEnabled(canEnableSaveButton());
}
};
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.add_venue_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
mAddOrEditVenueButton = (Button) findViewById(R.id.addVenueButton);
mNameEditText = (EditText) findViewById(R.id.nameEditText);
mAddressEditText = (EditText) findViewById(R.id.addressEditText);
mCrossstreetEditText = (EditText) findViewById(R.id.crossstreetEditText);
mCityEditText = (EditText) findViewById(R.id.cityEditText);
mStateEditText = (EditText) findViewById(R.id.stateEditText);
mZipEditText = (EditText) findViewById(R.id.zipEditText);
mPhoneEditText = (EditText) findViewById(R.id.phoneEditText);
mCategoryLayout = (LinearLayout) findViewById(R.id.addVenueCategoryLayout);
mCategoryImageView = (ImageView) findViewById(R.id.addVenueCategoryIcon);
mCategoryTextView = (TextView) findViewById(R.id.addVenueCategoryTextView);
mCategoryProgressBar = (ProgressBar) findViewById(R.id.addVenueCategoryProgressBar);
mCategoryLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showDialog(DIALOG_PICK_CATEGORY);
}
});
mCategoryLayout.setEnabled(false);
mAddOrEditVenueButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String name = mNameEditText.getText().toString();
String address = mAddressEditText.getText().toString();
String crossstreet = mCrossstreetEditText.getText().toString();
String city = mCityEditText.getText().toString();
String state = mStateEditText.getText().toString();
String zip = mZipEditText.getText().toString();
String phone = mPhoneEditText.getText().toString();
if (mStateHolder.getVenueBeingEdited() != null) {
if (TextUtils.isEmpty(name)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_name));
return;
} else if (TextUtils.isEmpty(address)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_address));
return;
} else if (TextUtils.isEmpty(city)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_city));
return;
} else if (TextUtils.isEmpty(state)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_state));
return;
}
}
mStateHolder.startTaskAddOrEditVenue(
AddVenueActivity.this,
new String[] {
name,
address,
crossstreet,
city,
state,
zip,
phone,
mStateHolder.getChosenCategory() != null ?
mStateHolder.getChosenCategory().getId() : ""
},
// If editing a venue, pass in its id.
mStateHolder.getVenueBeingEdited() != null ?
mStateHolder.getVenueBeingEdited().getId() : null);
}
});
mNameEditText.addTextChangedListener(mNameFieldWatcher);
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
setFields(mStateHolder.getAddressLookup());
setChosenCategory(mStateHolder.getChosenCategory());
if (mStateHolder.getCategories() != null && mStateHolder.getCategories().size() > 0) {
mCategoryLayout.setEnabled(true);
mCategoryProgressBar.setVisibility(View.GONE);
}
} else {
mStateHolder = new StateHolder();
mStateHolder.startTaskGetCategories(this);
// If passed the venue parcelable, then we are in 'edit' mode.
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EXTRA_VENUE_TO_EDIT)) {
Venue venue = getIntent().getExtras().getParcelable(EXTRA_VENUE_TO_EDIT);
if (venue != null) {
mStateHolder.setVenueBeingEdited(venue);
setFields(venue);
setTitle(getResources().getString(R.string.add_venue_activity_label_edit_venue));
mAddOrEditVenueButton.setText(getResources().getString(
R.string.add_venue_activity_btn_submit_edits));
} else {
Log.e(TAG, "Null venue parcelable supplied at startup, will finish immediately.");
finish();
}
} else {
mStateHolder.startTaskAddressLookup(this);
}
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(true);
if (mStateHolder.getIsRunningTaskAddOrEditVenue()) {
startProgressBar();
}
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates();
stopProgressBar();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void showDialogError(String message) {
mStateHolder.setError(message);
showDialog(DIALOG_ERROR);
}
/**
* Set fields from an address lookup, only used when adding a venue. This is done
* to prepopulate some fields for the user.
*/
private void setFields(AddressLookup addressLookup) {
if (mStateHolder.getVenueBeingEdited() == null &&
addressLookup != null &&
addressLookup.getAddress() != null) {
// Don't fill in the street unless we're reasonably confident we
// know where the user is.
String address = addressLookup.getAddress().getAddressLine(0);
double accuracy = addressLookup.getLocation().getAccuracy();
if (address != null && (accuracy > 0.0 && accuracy < MINIMUM_ACCURACY_FOR_ADDRESS)) {
if (DEBUG) Log.d(TAG, "Accuracy good enough, setting address field.");
mAddressEditText.setText(address);
}
String city = addressLookup.getAddress().getLocality();
if (city != null) {
mCityEditText.setText(city);
}
String state = addressLookup.getAddress().getAdminArea();
if (state != null) {
mStateEditText.setText(state);
}
String zip = addressLookup.getAddress().getPostalCode();
if (zip != null) {
mZipEditText.setText(zip);
}
String phone = addressLookup.getAddress().getPhone();
if (phone != null) {
mPhoneEditText.setText(phone);
}
}
}
/**
* Set fields from an existing venue, this is only used when editing a venue.
*/
private void setFields(Venue venue) {
mNameEditText.setText(venue.getName());
mCrossstreetEditText.setText(venue.getCrossstreet());
mAddressEditText.setText(venue.getAddress());
mCityEditText.setText(venue.getCity());
mStateEditText.setText(venue.getState());
mZipEditText.setText(venue.getZip());
mPhoneEditText.setText(venue.getPhone());
}
private void startProgressBar() {
startProgressBar(
getResources().getString(
mStateHolder.getVenueBeingEdited() == null ?
R.string.add_venue_progress_bar_message_add_venue :
R.string.add_venue_progress_bar_message_edit_venue));
}
private void startProgressBar(String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, null, message);
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
private void onGetCategoriesTaskComplete(Group<Category> categories, Exception ex) {
mStateHolder.setIsRunningTaskGetCategories(false);
try {
// Populate the categories list now.
if (categories != null) {
mStateHolder.setCategories(categories);
mCategoryLayout.setEnabled(true);
mCategoryTextView.setText(getResources().getString(R.string.add_venue_activity_pick_category_label));
mCategoryProgressBar.setVisibility(View.GONE);
// If we are editing a venue, set its category here.
if (mStateHolder.getVenueBeingEdited() != null) {
Venue venue = mStateHolder.getVenueBeingEdited();
if (venue.getCategory() != null) {
setChosenCategory(venue.getCategory());
}
}
} else {
// If error, feed list adapter empty user group.
mStateHolder.setCategories(new Group<Category>());
NotificationsUtil.ToastReasonForFailure(this, ex);
}
} finally {
}
stopIndeterminateProgressBar();
}
private void ooGetAddressLookupTaskComplete(AddressLookup addressLookup, Exception ex) {
mStateHolder.setIsRunningTaskAddressLookup(false);
stopIndeterminateProgressBar();
if (addressLookup != null) {
mStateHolder.setAddressLookup(addressLookup);
setFields(addressLookup);
} else {
// Nothing to do on failure, don't need to report.
}
}
private void onAddOrEditVenueTaskComplete(Venue venue, String venueIdIfEditing, Exception ex) {
mStateHolder.setIsRunningTaskAddOrEditVenue(false);
stopProgressBar();
if (venueIdIfEditing == null) {
if (venue != null) {
// If they added the venue ok, then send them to an activity displaying it
// so they can play around with it.
Intent intent = new Intent(AddVenueActivity.this, VenueActivity.class);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
startActivity(intent);
finish();
} else {
// Error, let them hang out here.
NotificationsUtil.ToastReasonForFailure(this, ex);
}
} else {
if (venue != null) {
// Editing the venue worked ok, just return to caller.
Toast.makeText(this, getResources().getString(
R.string.add_venue_activity_edit_venue_success),
Toast.LENGTH_SHORT).show();
finish();
} else {
// Error, let them hang out here.
NotificationsUtil.ToastReasonForFailure(this, ex);
}
}
}
private void stopIndeterminateProgressBar() {
if (mStateHolder.getIsRunningTaskAddressLookup() == false &&
mStateHolder.getIsRunningTaskGetCategories() == false) {
setProgressBarIndeterminateVisibility(false);
}
}
private static class AddOrEditVenueTask extends AsyncTask<Void, Void, Venue> {
private AddVenueActivity mActivity;
private String[] mParams;
private String mVenueIdIfEditing;
private Exception mReason;
private Foursquared mFoursquared;
private String mErrorMsgForEditVenue;
public AddOrEditVenueTask(AddVenueActivity activity,
String[] params,
String venueIdIfEditing) {
mActivity = activity;
mParams = params;
mVenueIdIfEditing = venueIdIfEditing;
mFoursquared = (Foursquared) activity.getApplication();
mErrorMsgForEditVenue = activity.getResources().getString(
R.string.add_venue_activity_edit_venue_fail);
}
public void setActivity(AddVenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected Venue doInBackground(Void... params) {
try {
Foursquare foursquare = mFoursquared.getFoursquare();
Location location = mFoursquared.getLastKnownLocationOrThrow();
if (mVenueIdIfEditing == null) {
return foursquare.addVenue(
mParams[0], // name
mParams[1], // address
mParams[2], // cross street
mParams[3], // city
mParams[4], // state,
mParams[5], // zip
mParams[6], // phone
mParams[7], // category id
LocationUtils.createFoursquareLocation(location));
} else {
Response response =
foursquare.proposeedit(
mVenueIdIfEditing,
mParams[0], // name
mParams[1], // address
mParams[2], // cross street
mParams[3], // city
mParams[4], // state,
mParams[5], // zip
mParams[6], // phone
mParams[7], // category id
LocationUtils.createFoursquareLocation(location));
if (response != null && response.getValue().equals("ok")) {
// TODO: Come up with a better method than returning an empty venue on success.
return new Venue();
} else {
throw new Exception(mErrorMsgForEditVenue);
}
}
} catch (Exception e) {
Log.e(TAG, "Exception during add or edit venue.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Venue venue) {
if (DEBUG) Log.d(TAG, "onPostExecute()");
if (mActivity != null) {
mActivity.onAddOrEditVenueTaskComplete(venue, mVenueIdIfEditing, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onAddOrEditVenueTaskComplete(null, mVenueIdIfEditing, mReason);
}
}
}
private static class AddressLookupTask extends AsyncTask<Void, Void, AddressLookup> {
private AddVenueActivity mActivity;
private Exception mReason;
public AddressLookupTask(AddVenueActivity activity) {
mActivity = activity;
}
public void setActivity(AddVenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.setProgressBarIndeterminateVisibility(true);
}
@Override
protected AddressLookup doInBackground(Void... params) {
try {
Location location = ((Foursquared)mActivity.getApplication()).getLastKnownLocationOrThrow();
Geocoder geocoder = new Geocoder(mActivity);
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
Log.i(TAG, "Address found: " + addresses.toString());
return new AddressLookup(location, addresses.get(0));
} else {
Log.i(TAG, "No address could be found for current location.");
throw new FoursquareException("No address could be found for the current geolocation.");
}
} catch (Exception ex) {
Log.e(TAG, "Error during address lookup.", ex);
mReason = ex;
}
return null;
}
@Override
protected void onPostExecute(AddressLookup address) {
if (mActivity != null) {
mActivity.ooGetAddressLookupTaskComplete(address, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.ooGetAddressLookupTaskComplete(null, mReason);
}
}
}
private static class GetCategoriesTask extends AsyncTask<Void, Void, Group<Category>> {
private AddVenueActivity mActivity;
private Exception mReason;
public GetCategoriesTask(AddVenueActivity activity) {
mActivity = activity;
}
public void setActivity(AddVenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.setProgressBarIndeterminateVisibility(true);
}
@Override
protected Group<Category> doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.categories();
} catch (Exception e) {
if (DEBUG)
Log.d(TAG, "GetCategoriesTask: Exception doing send friend request.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Category> categories) {
if (DEBUG) Log.d(TAG, "GetCategoriesTask: onPostExecute()");
if (mActivity != null) {
mActivity.onGetCategoriesTaskComplete(categories, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onGetCategoriesTaskComplete(null,
new Exception("Get categories task request cancelled."));
}
}
}
private static class StateHolder {
private AddressLookupTask mTaskGetAddress;
private AddressLookup mAddressLookup;
private boolean mIsRunningTaskAddressLookup;
private GetCategoriesTask mTaskGetCategories;
private Group<Category> mCategories;
private boolean mIsRunningTaskGetCategories;
private AddOrEditVenueTask mTaskAddOrEditVenue;
private boolean mIsRunningTaskAddOrEditVenue;
private Category mChosenCategory;
private Venue mVenueBeingEdited;
private String mError;
public StateHolder() {
mCategories = new Group<Category>();
mIsRunningTaskAddressLookup = false;
mIsRunningTaskGetCategories = false;
mIsRunningTaskAddOrEditVenue = false;
mVenueBeingEdited = null;
}
public void setCategories(Group<Category> categories) {
mCategories = categories;
}
public void setAddressLookup(AddressLookup addressLookup) {
mAddressLookup = addressLookup;
}
public Group<Category> getCategories() {
return mCategories;
}
public AddressLookup getAddressLookup() {
return mAddressLookup;
}
public Venue getVenueBeingEdited() {
return mVenueBeingEdited;
}
public void setVenueBeingEdited(Venue venue) {
mVenueBeingEdited = venue;
}
public void startTaskGetCategories(AddVenueActivity activity) {
mIsRunningTaskGetCategories = true;
mTaskGetCategories = new GetCategoriesTask(activity);
mTaskGetCategories.execute();
}
public void startTaskAddressLookup(AddVenueActivity activity) {
mIsRunningTaskAddressLookup = true;
mTaskGetAddress = new AddressLookupTask(activity);
mTaskGetAddress.execute();
}
public void startTaskAddOrEditVenue(AddVenueActivity activity, String[] params,
String venueIdIfEditing) {
mIsRunningTaskAddOrEditVenue = true;
mTaskAddOrEditVenue = new AddOrEditVenueTask(activity, params, venueIdIfEditing);
mTaskAddOrEditVenue.execute();
}
public void setActivity(AddVenueActivity activity) {
if (mTaskGetCategories != null) {
mTaskGetCategories.setActivity(activity);
}
if (mTaskGetAddress != null) {
mTaskGetAddress.setActivity(activity);
}
if (mTaskAddOrEditVenue != null) {
mTaskAddOrEditVenue.setActivity(activity);
}
}
public void setIsRunningTaskAddressLookup(boolean isRunning) {
mIsRunningTaskAddressLookup = isRunning;
}
public void setIsRunningTaskGetCategories(boolean isRunning) {
mIsRunningTaskGetCategories = isRunning;
}
public void setIsRunningTaskAddOrEditVenue(boolean isRunning) {
mIsRunningTaskAddOrEditVenue = isRunning;
}
public boolean getIsRunningTaskAddressLookup() {
return mIsRunningTaskAddressLookup;
}
public boolean getIsRunningTaskGetCategories() {
return mIsRunningTaskGetCategories;
}
public boolean getIsRunningTaskAddOrEditVenue() {
return mIsRunningTaskAddOrEditVenue;
}
public Category getChosenCategory() {
return mChosenCategory;
}
public void setChosenCategory(Category category) {
mChosenCategory = category;
}
public String getError() {
return mError;
}
public void setError(String error) {
mError = error;
}
}
private static class AddressLookup {
private Location mLocation;
private Address mAddress;
public AddressLookup(Location location, Address address) {
mLocation = location;
mAddress = address;
}
public Location getLocation() {
return mLocation;
}
public Address getAddress() {
return mAddress;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_PICK_CATEGORY:
// When the user cancels the dialog (by hitting the 'back' key), we
// finish this activity. We don't listen to onDismiss() for this
// action, because a device rotation will fire onDismiss(), and our
// dialog would not be re-displayed after the rotation is complete.
CategoryPickerDialog dlg = new CategoryPickerDialog(
this,
mStateHolder.getCategories(),
((Foursquared)getApplication()));
dlg.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
CategoryPickerDialog dlg = (CategoryPickerDialog)dialog;
setChosenCategory(dlg.getChosenCategory());
removeDialog(DIALOG_PICK_CATEGORY);
}
});
return dlg;
case DIALOG_ERROR:
AlertDialog dlgInfo = new AlertDialog.Builder(this)
.setIcon(0)
.setTitle(getResources().getString(R.string.add_venue_progress_bar_title_edit_venue))
.setMessage(mStateHolder.getError()).create();
dlgInfo.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
removeDialog(DIALOG_ERROR);
}
});
return dlgInfo;
}
return null;
}
private void setChosenCategory(Category category) {
if (category == null) {
mCategoryTextView.setText(getResources().getString(
R.string.add_venue_activity_pick_category_label));
return;
}
try {
Bitmap bitmap = BitmapFactory.decodeStream(
((Foursquared)getApplication()).getRemoteResourceManager().getInputStream(
Uri.parse(category.getIconUrl())));
mCategoryImageView.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.e(TAG, "Error loading category icon.", e);
}
mCategoryTextView.setText(category.getNodeName());
// Record the chosen category.
mStateHolder.setChosenCategory(category);
if (canEnableSaveButton()) {
mAddOrEditVenueButton.setEnabled(canEnableSaveButton());
}
}
private boolean canEnableSaveButton() {
return mNameEditText.getText().length() > 0;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.TipUtils;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.joelapenna.foursquared.widget.TodosListAdapter;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.Observable;
import java.util.Observer;
/**
* Shows a list of a user's todos. We can operate on the logged-in user,
* or a friend user, specified through the intent extras.
*
* If operating on the logged-in user, we remove items from the todo list
* if they mark a todo as done or un-mark it. If operating on another user,
* we do not remove them from the list.
*
* @date September 12, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TodosActivity extends LoadableListActivityWithViewAndHeader {
static final String TAG = "TodosActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_USER_ID = Foursquared.PACKAGE_NAME
+ ".TodosActivity.INTENT_EXTRA_USER_ID";
public static final String INTENT_EXTRA_USER_NAME = Foursquared.PACKAGE_NAME
+ ".TodosActivity.INTENT_EXTRA_USER_NAME";
private static final int ACTIVITY_TIP = 500;
private StateHolder mStateHolder;
private TodosListAdapter mListAdapter;
private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver();
private View mLayoutEmpty;
private static final int MENU_REFRESH = 0;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
// Optional user id and username, if not present, will be null and default to
// logged-in user.
mStateHolder = new StateHolder(
getIntent().getStringExtra(INTENT_EXTRA_USER_ID),
getIntent().getStringExtra(INTENT_EXTRA_USER_NAME));
mStateHolder.setRecentOnly(false);
}
ensureUi();
// Nearby todos is shown first by default so auto-fetch it if necessary.
// Nearby is the right button, not the left one, which is a bit strange
// but this was a design req.
if (!mStateHolder.getRanOnceTodosNearby()) {
mStateHolder.startTaskTodos(this, false);
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver);
if (isFinishing()) {
mStateHolder.cancelTasks();
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void ensureUi() {
LayoutInflater inflater = LayoutInflater.from(this);
setTitle(getString(R.string.todos_activity_title, mStateHolder.getUsername()));
mLayoutEmpty = inflater.inflate(
R.layout.todos_activity_empty, null);
mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
mListAdapter = new TodosListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
if (mStateHolder.getRecentOnly()) {
mListAdapter.setGroup(mStateHolder.getTodosRecent());
if (mStateHolder.getTodosRecent().size() == 0) {
if (mStateHolder.getRanOnceTodosRecent()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
} else {
mListAdapter.setGroup(mStateHolder.getTodosNearby());
if (mStateHolder.getTodosNearby().size() == 0) {
if (mStateHolder.getRanOnceTodosNearby()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
}
SegmentedButton buttons = getHeaderButton();
buttons.clearButtons();
buttons.addButtons(
getString(R.string.todos_activity_btn_recent),
getString(R.string.todos_activity_btn_nearby));
if (mStateHolder.getRecentOnly()) {
buttons.setPushedButtonIndex(0);
} else {
buttons.setPushedButtonIndex(1);
}
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
if (index == 0) {
mStateHolder.setRecentOnly(true);
mListAdapter.setGroup(mStateHolder.getTodosRecent());
if (mStateHolder.getTodosRecent().size() < 1) {
if (mStateHolder.getRanOnceTodosRecent()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTodos(TodosActivity.this, true);
}
}
} else {
mStateHolder.setRecentOnly(false);
mListAdapter.setGroup(mStateHolder.getTodosNearby());
if (mStateHolder.getTodosNearby().size() < 1) {
if (mStateHolder.getRanOnceTodosNearby()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTodos(TodosActivity.this, false);
}
}
}
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
});
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(false);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Todo todo = (Todo) parent.getAdapter().getItem(position);
if (todo.getTip() != null) {
Intent intent = new Intent(TodosActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, todo.getTip());
startActivityForResult(intent, ACTIVITY_TIP);
}
}
});
if (mStateHolder.getIsRunningTaskTodosRecent() ||
mStateHolder.getIsRunningTaskTodosNearby()) {
setProgressBarIndeterminateVisibility(true);
} else {
setProgressBarIndeterminateVisibility(false);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh)
.setIcon(R.drawable.ic_menu_refresh);
MenuUtils.addPreferencesToMenu(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
mStateHolder.startTaskTodos(this, mStateHolder.getRecentOnly());
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// We ignore the returned to-do (if any). We search for any to-dos in our
// state holder by the linked tip ID for update.
if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) {
if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) {
updateTodo((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED));
}
}
}
private void updateTodo(Tip tip) {
mStateHolder.updateTodo(tip);
mListAdapter.notifyDataSetInvalidated();
}
private void onStartTaskTodos() {
if (mListAdapter != null) {
if (mStateHolder.getRecentOnly()) {
mStateHolder.setIsRunningTaskTodosRecent(true);
mListAdapter.setGroup(mStateHolder.getTodosRecent());
} else {
mStateHolder.setIsRunningTaskTodosNearby(true);
mListAdapter.setGroup(mStateHolder.getTodosNearby());
}
mListAdapter.notifyDataSetChanged();
}
setProgressBarIndeterminateVisibility(true);
setLoadingView();
}
private void onTaskTodosComplete(Group<Todo> group, boolean recentOnly, Exception ex) {
SegmentedButton buttons = getHeaderButton();
boolean update = false;
if (group != null) {
if (recentOnly) {
mStateHolder.setTodosRecent(group);
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTodosRecent());
update = true;
}
} else {
mStateHolder.setTodosNearby(group);
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTodosNearby());
update = true;
}
}
}
else {
if (recentOnly) {
mStateHolder.setTodosRecent(new Group<Todo>());
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTodosRecent());
update = true;
}
} else {
mStateHolder.setTodosNearby(new Group<Todo>());
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTodosNearby());
update = true;
}
}
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (recentOnly) {
mStateHolder.setIsRunningTaskTodosRecent(false);
mStateHolder.setRanOnceTodosRecent(true);
if (mStateHolder.getTodosRecent().size() == 0 &&
buttons.getSelectedButtonIndex() == 0) {
setEmptyView(mLayoutEmpty);
}
} else {
mStateHolder.setIsRunningTaskTodosNearby(false);
mStateHolder.setRanOnceTodosNearby(true);
if (mStateHolder.getTodosNearby().size() == 0 &&
buttons.getSelectedButtonIndex() == 1) {
setEmptyView(mLayoutEmpty);
}
}
if (update) {
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
if (!mStateHolder.getIsRunningTaskTodosRecent() &&
!mStateHolder.getIsRunningTaskTodosNearby()) {
setProgressBarIndeterminateVisibility(false);
}
}
/**
* Gets friends of the current user we're working for.
*/
private static class TaskTodos extends AsyncTask<Void, Void, Group<Todo>> {
private String mUserId;
private TodosActivity mActivity;
private boolean mRecentOnly;
private Exception mReason;
public TaskTodos(TodosActivity activity, String userId, boolean friendsOnly) {
mActivity = activity;
mUserId = userId;
mRecentOnly = friendsOnly;
}
@Override
protected void onPreExecute() {
mActivity.onStartTaskTodos();
}
@Override
protected Group<Todo> doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
Location loc = foursquared.getLastKnownLocation();
if (loc == null) {
try { Thread.sleep(3000); } catch (InterruptedException ex) {}
loc = foursquared.getLastKnownLocation();
if (loc == null) {
throw new FoursquareException("Your location could not be determined!");
}
}
return foursquare.todos(
LocationUtils.createFoursquareLocation(loc),
mUserId,
mRecentOnly,
!mRecentOnly,
30);
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Todo> todos) {
if (mActivity != null) {
mActivity.onTaskTodosComplete(todos, mRecentOnly, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskTodosComplete(null, mRecentOnly, mReason);
}
}
public void setActivity(TodosActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private Group<Todo> mTodosRecent;
private Group<Todo> mTodosNearby;
private boolean mIsRunningTaskTodosRecent;
private boolean mIsRunningTaskTodosNearby;
private boolean mRecentOnly;
private boolean mRanOnceTodosRecent;
private boolean mRanOnceTodosNearby;
private TaskTodos mTaskTodosRecent;
private TaskTodos mTaskTodosNearby;
private String mUserId;
private String mUsername;
public StateHolder(String userId, String username) {
mIsRunningTaskTodosRecent = false;
mIsRunningTaskTodosNearby = false;
mRanOnceTodosRecent = false;
mRanOnceTodosNearby = false;
mTodosRecent = new Group<Todo>();
mTodosNearby = new Group<Todo>();
mRecentOnly = false;
mUserId = userId;
mUsername = username;
}
public String getUsername() {
return mUsername;
}
public Group<Todo> getTodosRecent() {
return mTodosRecent;
}
public void setTodosRecent(Group<Todo> todosRecent) {
mTodosRecent = todosRecent;
}
public Group<Todo> getTodosNearby() {
return mTodosNearby;
}
public void setTodosNearby(Group<Todo> todosNearby) {
mTodosNearby = todosNearby;
}
public void startTaskTodos(TodosActivity activity,
boolean recentOnly) {
if (recentOnly) {
if (mIsRunningTaskTodosRecent) {
return;
}
mIsRunningTaskTodosRecent = true;
mTaskTodosRecent = new TaskTodos(activity, mUserId, recentOnly);
mTaskTodosRecent.execute();
} else {
if (mIsRunningTaskTodosNearby) {
return;
}
mIsRunningTaskTodosNearby = true;
mTaskTodosNearby = new TaskTodos(activity, mUserId, recentOnly);
mTaskTodosNearby.execute();
}
}
public void setActivity(TodosActivity activity) {
if (mTaskTodosRecent != null) {
mTaskTodosRecent.setActivity(activity);
}
if (mTaskTodosNearby != null) {
mTaskTodosNearby.setActivity(activity);
}
}
public boolean getIsRunningTaskTodosRecent() {
return mIsRunningTaskTodosRecent;
}
public void setIsRunningTaskTodosRecent(boolean isRunning) {
mIsRunningTaskTodosRecent = isRunning;
}
public boolean getIsRunningTaskTodosNearby() {
return mIsRunningTaskTodosNearby;
}
public void setIsRunningTaskTodosNearby(boolean isRunning) {
mIsRunningTaskTodosNearby = isRunning;
}
public void cancelTasks() {
if (mTaskTodosRecent != null) {
mTaskTodosRecent.setActivity(null);
mTaskTodosRecent.cancel(true);
}
if (mTaskTodosNearby != null) {
mTaskTodosNearby.setActivity(null);
mTaskTodosNearby.cancel(true);
}
}
public boolean getRecentOnly() {
return mRecentOnly;
}
public void setRecentOnly(boolean recentOnly) {
mRecentOnly = recentOnly;
}
public boolean getRanOnceTodosRecent() {
return mRanOnceTodosRecent;
}
public void setRanOnceTodosRecent(boolean ranOnce) {
mRanOnceTodosRecent = ranOnce;
}
public boolean getRanOnceTodosNearby() {
return mRanOnceTodosNearby;
}
public void setRanOnceTodosNearby(boolean ranOnce) {
mRanOnceTodosNearby = ranOnce;
}
public void updateTodo(Tip tip) {
updateTodoFromArray(tip, mTodosRecent);
updateTodoFromArray(tip, mTodosNearby);
}
private void updateTodoFromArray(Tip tip, Group<Todo> target) {
for (int i = 0, m = target.size(); i < m; i++) {
Todo todo = target.get(i);
if (todo.getTip() != null) { // Fix for old garbage todos/tips from the API.
if (todo.getTip().getId().equals(tip.getId())) {
if (mUserId == null) {
// Activity is operating on logged-in user, only removing todos
// from the list, don't have to worry about updating states.
if (!TipUtils.isTodo(tip)) {
target.remove(todo);
}
} else {
// Activity is operating on another user, so just update the status
// of the tip within the todo.
todo.getTip().setStatus(tip.getStatus());
}
break;
}
}
}
}
}
/**
* This is really just a dummy observer to get the GPS running
* since this is the new splash page. After getting a fix, we
* might want to stop registering this observer thereafter so
* it doesn't annoy the user too much.
*/
private class SearchLocationObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.app.LoadableListActivity;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.VenueListAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
/**
* Shows a list of venues that the specified user is mayor of.
* We can fetch these ourselves given a userId, or work from
* a venue array parcel.
*
* @date March 15, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserMayorshipsActivity extends LoadableListActivity {
static final String TAG = "UserMayorshipsActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_USER_ID = Foursquared.PACKAGE_NAME
+ ".UserMayorshipsActivity.EXTRA_USER_ID";
public static final String EXTRA_USER_NAME = Foursquared.PACKAGE_NAME
+ ".UserMayorshipsActivity.EXTRA_USER_NAME";
public static final String EXTRA_VENUE_LIST_PARCEL = Foursquared.PACKAGE_NAME
+ ".UserMayorshipsActivity.EXTRA_VENUE_LIST_PARCEL";
private StateHolder mStateHolder;
private SeparatedListAdapter mListAdapter;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivityForTaskVenues(this);
} else {
if (getIntent().hasExtra(EXTRA_USER_ID) && getIntent().hasExtra(EXTRA_USER_NAME)) {
mStateHolder = new StateHolder(
getIntent().getStringExtra(EXTRA_USER_ID),
getIntent().getStringExtra(EXTRA_USER_NAME));
} else {
Log.e(TAG, "UserMayorships requires a userid in its intent extras.");
finish();
return;
}
if (getIntent().getExtras().containsKey(EXTRA_VENUE_LIST_PARCEL)) {
// Can't jump from ArrayList to Group, argh.
ArrayList<Venue> venues = getIntent().getExtras().getParcelableArrayList(
EXTRA_VENUE_LIST_PARCEL);
Group<Venue> group = new Group<Venue>();
for (Venue it : venues) {
group.add(it);
}
mStateHolder.setVenues(group);
} else {
mStateHolder.startTaskVenues(this);
}
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mStateHolder.cancelTasks();
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTaskVenues(null);
return mStateHolder;
}
private void ensureUi() {
mListAdapter = new SeparatedListAdapter(this);
VenueListAdapter adapter = new VenueListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
if (mStateHolder.getVenues().size() > 0) {
adapter.setGroup(mStateHolder.getVenues());
mListAdapter.addSection(
getResources().getString(R.string.user_mayorships_activity_adapter_title),
adapter);
}
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Venue venue = (Venue)mListAdapter.getItem(position);
Intent intent = new Intent(UserMayorshipsActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
startActivity(intent);
}
});
if (mStateHolder.getIsRunningVenuesTask()) {
setLoadingView();
} else if (mStateHolder.getFetchedVenuesOnce() && mStateHolder.getVenues().size() == 0) {
setEmptyView();
}
setTitle(getString(R.string.user_mayorships_activity_title, mStateHolder.getUsername()));
}
private void onVenuesTaskComplete(User user, Exception ex) {
mListAdapter.removeObserver();
mListAdapter = new SeparatedListAdapter(this);
if (user != null) {
mStateHolder.setVenues(user.getMayorships());
}
else {
mStateHolder.setVenues(new Group<Venue>());
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (mStateHolder.getVenues().size() > 0) {
VenueListAdapter adapter = new VenueListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(mStateHolder.getVenues());
mListAdapter.addSection(
getResources().getString(R.string.user_mayorships_activity_adapter_title),
adapter);
}
getListView().setAdapter(mListAdapter);
mStateHolder.setIsRunningVenuesTask(false);
mStateHolder.setFetchedVenuesOnce(true);
// TODO: We can probably tighten this up by just calling ensureUI() again.
if (mStateHolder.getVenues().size() == 0) {
setEmptyView();
}
}
@Override
public int getNoSearchResultsStringId() {
return R.string.user_mayorships_activity_no_info;
}
/**
* Gets venues that the current user is mayor of.
*/
private static class VenuesTask extends AsyncTask<String, Void, User> {
private UserMayorshipsActivity mActivity;
private Exception mReason;
public VenuesTask(UserMayorshipsActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.setLoadingView();
}
@Override
protected User doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.user(params[0], true, false, false,
LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(User user) {
if (mActivity != null) {
mActivity.onVenuesTaskComplete(user, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onVenuesTaskComplete(null, mReason);
}
}
public void setActivity(UserMayorshipsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private String mUserId;
private String mUsername;
private Group<Venue> mVenues;
private VenuesTask mTaskVenues;
private boolean mIsRunningVenuesTask;
private boolean mFetchedVenuesOnce;
public StateHolder(String userId, String username) {
mUserId = userId;
mUsername = username;
mIsRunningVenuesTask = false;
mFetchedVenuesOnce = false;
mVenues = new Group<Venue>();
}
public String getUsername() {
return mUsername;
}
public Group<Venue> getVenues() {
return mVenues;
}
public void setVenues(Group<Venue> venues) {
mVenues = venues;
}
public void startTaskVenues(UserMayorshipsActivity activity) {
mIsRunningVenuesTask = true;
mTaskVenues = new VenuesTask(activity);
mTaskVenues.execute(mUserId);
}
public void setActivityForTaskVenues(UserMayorshipsActivity activity) {
if (mTaskVenues != null) {
mTaskVenues.setActivity(activity);
}
}
public void setIsRunningVenuesTask(boolean isRunning) {
mIsRunningVenuesTask = isRunning;
}
public boolean getIsRunningVenuesTask() {
return mIsRunningVenuesTask;
}
public void setFetchedVenuesOnce(boolean fetchedOnce) {
mFetchedVenuesOnce = fetchedOnce;
}
public boolean getFetchedVenuesOnce() {
return mFetchedVenuesOnce;
}
public void cancelTasks() {
if (mTaskVenues != null) {
mTaskVenues.setActivity(null);
mTaskVenues.cancel(true);
}
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Mayor;
import com.joelapenna.foursquare.types.Stats;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.UserUtils;
import com.joelapenna.foursquared.util.VenueUtils;
import com.joelapenna.foursquared.widget.PhotoStrip;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* We may be given a pre-fetched venue ready to display, or we might also get just
* a venue ID. If we only get a venue ID, then we need to fetch it immediately from
* the API.
*
* The activity will set an intent result in EXTRA_VENUE_RETURNED if the venue status
* changes as a result of a user modifying todos at the venue. Parent activities can
* check the returned venue to see if this status has changed to update their UI.
* For example, the NearbyVenues activity wants to show the todo corner png if the
* venue has a todo.
*
* The result will also be set if the venue is fully fetched if originally given only
* a venue id or partial venue object. This way the parent can also cache the full venue
* object for next time they want to display this venue activity.
*
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Replaced shout activity with CheckinGatherInfoActivity (3/10/2010).
* -Redesign from tabbed layout (9/15/2010).
*/
public class VenueActivity extends Activity {
private static final String TAG = "VenueActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int MENU_TIP_ADD = 1;
private static final int MENU_TODO_ADD = 2;
private static final int MENU_EDIT_VENUE = 3;
private static final int MENU_CALL = 4;
private static final int MENU_SHARE = 5;
private static final int RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE = 1;
private static final int RESULT_CODE_ACTIVITY_ADD_TIP = 2;
private static final int RESULT_CODE_ACTIVITY_ADD_TODO = 3;
private static final int RESULT_CODE_ACTIVITY_TIP = 4;
private static final int RESULT_CODE_ACTIVITY_TIPS = 5;
private static final int RESULT_CODE_ACTIVITY_TODO = 6;
private static final int RESULT_CODE_ACTIVITY_TODOS = 7;
public static final String INTENT_EXTRA_VENUE_ID = Foursquared.PACKAGE_NAME
+ ".VenueActivity.INTENT_EXTRA_VENUE_ID";
public static final String INTENT_EXTRA_VENUE_PARTIAL = Foursquared.PACKAGE_NAME
+ ".VenueActivity.INTENT_EXTRA_VENUE_PARTIAL";
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".VenueActivity.INTENT_EXTRA_VENUE";
public static final String EXTRA_VENUE_RETURNED = Foursquared.PACKAGE_NAME
+ ".VenueActivity.EXTRA_VENUE_RETURNED";
private StateHolder mStateHolder;
private Handler mHandler;
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.venue_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
mHandler = new Handler();
StateHolder holder = (StateHolder) getLastNonConfigurationInstance();
if (holder != null) {
mStateHolder = holder;
mStateHolder.setActivityForTasks(this);
prepareResultIntent();
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_FULL);
mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE));
} else if (getIntent().hasExtra(INTENT_EXTRA_VENUE_PARTIAL)) {
mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_PARTIAL);
mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE_PARTIAL));
mStateHolder.startTaskVenue(this);
} else if (getIntent().hasExtra(INTENT_EXTRA_VENUE_ID)) {
mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_ID);
mStateHolder.setVenueId(getIntent().getStringExtra(INTENT_EXTRA_VENUE_ID));
mStateHolder.startTaskVenue(this);
} else {
Log.e(TAG, "VenueActivity must be given a venue id or a venue parcel as intent extras.");
finish();
return;
}
}
mRrm = ((Foursquared) getApplication()).getRemoteResourceManager();
mResourcesObserver = new RemoteResourceManagerObserver();
mRrm.addObserver(mResourcesObserver);
ensureUi();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
mHandler.removeCallbacks(mRunnableMayorPhoto);
if (mRrm != null) {
mRrm.deleteObserver(mResourcesObserver);
}
}
@Override
public void onResume() {
super.onResume();
ensureUiCheckinButton();
// TODO: ensure mayor photo.
}
private void ensureUi() {
TextView tvVenueTitle = (TextView)findViewById(R.id.venueActivityName);
TextView tvVenueAddress = (TextView)findViewById(R.id.venueActivityAddress);
LinearLayout progress = (LinearLayout)findViewById(R.id.venueActivityDetailsProgress);
View viewMayor = findViewById(R.id.venueActivityMayor);
TextView tvMayorTitle = (TextView)findViewById(R.id.venueActivityMayorName);
TextView tvMayorText = (TextView)findViewById(R.id.venueActivityMayorText);
ImageView ivMayorPhoto = (ImageView)findViewById(R.id.venueActivityMayorPhoto);
ImageView ivMayorChevron = (ImageView)findViewById(R.id.venueActivityMayorChevron);
View viewCheckins = findViewById(R.id.venueActivityCheckins);
TextView tvPeopleText = (TextView)findViewById(R.id.venueActivityPeopleText);
PhotoStrip psPeoplePhotos = (PhotoStrip)findViewById(R.id.venueActivityPeoplePhotos);
View viewTips = findViewById(R.id.venueActivityTips);
TextView tvTipsText = (TextView)findViewById(R.id.venueActivityTipsText);
TextView tvTipsTextExtra = (TextView)findViewById(R.id.venueActivityTipsExtra);
ImageView ivTipsChevron = (ImageView)findViewById(R.id.venueActivityTipsChevron);
View viewMoreInfo = findViewById(R.id.venueActivityMoreInfo);
TextView tvMoreInfoText = (TextView)findViewById(R.id.venueActivityMoreTitle);
Venue venue = mStateHolder.getVenue();
if (mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_FULL ||
mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_PARTIAL) {
tvVenueTitle.setText(venue.getName());
tvVenueAddress.setText(StringFormatters.getVenueLocationFull(venue));
ensureUiCheckinButton();
if (mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_FULL) {
Stats stats = venue.getStats();
Mayor mayor = stats != null ? stats.getMayor() : null;
if (mayor != null) {
tvMayorTitle.setText(StringFormatters.getUserFullName(mayor.getUser()));
tvMayorText.setText(getResources().getString(R.string.venue_activity_mayor_text));
String photoUrl = mayor.getUser().getPhoto();
Uri uriPhoto = Uri.parse(photoUrl);
if (mRrm.exists(uriPhoto)) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(photoUrl)));
ivMayorPhoto.setImageBitmap(bitmap);
} catch (IOException e) {
}
} else {
ivMayorPhoto.setImageResource(UserUtils.getDrawableByGenderForUserThumbnail(mayor.getUser()));
ivMayorPhoto.setTag(photoUrl);
mRrm.request(uriPhoto);
}
ivMayorChevron.setVisibility(View.VISIBLE);
setClickHandlerMayor(viewMayor);
} else {
tvMayorTitle.setText(getResources().getString(R.string.venue_activity_mayor_name_none));
tvMayorText.setText(getResources().getString(R.string.venue_activity_mayor_text_none));
ivMayorChevron.setVisibility(View.INVISIBLE);
}
viewMayor.setVisibility(View.VISIBLE);
if (venue.getCheckins() != null && venue.getCheckins().size() > 0) {
int friendCount = getFriendCountAtVenue();
int rest = venue.getCheckins().size() - friendCount;
if (friendCount > 0 && rest == 0) {
// N friends are here
tvPeopleText.setText(getResources().getString(
friendCount == 1 ?
R.string.venue_activity_people_count_friend_single :
R.string.venue_activity_people_count_friend_plural,
friendCount));
} else if (friendCount > 0 && rest > 0) {
// N friends are here with N other people
if (friendCount == 1 && rest == 1) {
tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_single_single,
friendCount, rest));
} else if (friendCount == 1 && rest > 1) {
tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_single_plural,
friendCount, rest));
} else if (friendCount > 1 && rest == 1) {
tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_plural_single,
friendCount, rest));
} else {
tvPeopleText.setText(getString(R.string.venue_activity_people_count_friend_plural_plural,
friendCount, rest));
}
} else {
// N people are here
tvPeopleText.setText(getResources().getString(
venue.getCheckins().size() == 1 ?
R.string.venue_activity_people_count_single :
R.string.venue_activity_people_count_plural,
venue.getCheckins().size()));
}
psPeoplePhotos.setCheckinsAndRemoteResourcesManager(venue.getCheckins(), mRrm);
viewCheckins.setVisibility(View.VISIBLE);
setClickHandlerCheckins(viewCheckins);
} else {
viewCheckins.setVisibility(View.GONE);
}
if (venue.getTips() != null && venue.getTips().size() > 0) {
int tipCountFriends = getTipCountFriendsAtVenue();
if (tipCountFriends > 0) {
tvTipsText.setText(
getString(tipCountFriends == 1 ?
R.string.venue_activity_tip_count_friend_single :
R.string.venue_activity_tip_count_friend_plural,
tipCountFriends));
int rest = venue.getTips().size() - tipCountFriends;
if (rest > 0) {
tvTipsTextExtra.setText(
getString(R.string.venue_activity_tip_count_other_people, rest));
tvTipsTextExtra.setVisibility(View.VISIBLE);
}
} else {
tvTipsText.setText(
getString(venue.getTips().size() == 1 ?
R.string.venue_activity_tip_count_single :
R.string.venue_activity_tip_count_plural,
venue.getTips().size()));
tvTipsTextExtra.setVisibility(View.GONE);
}
ivTipsChevron.setVisibility(View.VISIBLE);
setClickHandlerTips(viewTips);
} else {
tvTipsText.setText(getResources().getString(R.string.venue_activity_tip_count_none));
tvTipsTextExtra.setVisibility(View.GONE);
ivTipsChevron.setVisibility(View.INVISIBLE);
}
viewTips.setVisibility(View.VISIBLE);
if (tvTipsTextExtra.getVisibility() != View.VISIBLE) {
tvTipsText.setPadding(tvTipsText.getPaddingLeft(), tvMoreInfoText.getPaddingTop(),
tvTipsText.getPaddingRight(), tvMoreInfoText.getPaddingBottom());
}
viewMoreInfo.setVisibility(View.VISIBLE);
setClickHandlerMoreInfo(viewMoreInfo);
progress.setVisibility(View.GONE);
}
}
ensureUiTodosHere();
ImageView ivSpecialHere = (ImageView)findViewById(R.id.venueActivitySpecialHere);
if (VenueUtils.getSpecialHere(venue)) {
ivSpecialHere.setVisibility(View.VISIBLE);
ivSpecialHere.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showWebViewForSpecial();
}
});
} else {
ivSpecialHere.setVisibility(View.GONE);
}
}
private void ensureUiCheckinButton() {
Button btnCheckin = (Button)findViewById(R.id.venueActivityButtonCheckin);
if (mStateHolder.getCheckedInHere()) {
btnCheckin.setEnabled(false);
} else {
if (mStateHolder.getLoadType() == StateHolder.LOAD_TYPE_VENUE_ID) {
btnCheckin.setEnabled(false);
} else {
btnCheckin.setEnabled(true);
btnCheckin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(
VenueActivity.this);
if (settings.getBoolean(Preferences.PREFERENCE_IMMEDIATE_CHECKIN, false)) {
startCheckinQuick();
} else {
startCheckin();
}
}
});
}
}
}
private void ensureUiTipAdded() {
Venue venue = mStateHolder.getVenue();
TextView tvTipsText = (TextView)findViewById(R.id.venueActivityTipsText);
ImageView ivTipsChevron = (ImageView)findViewById(R.id.venueActivityTipsChevron);
if (venue.getTips().size() == 1) {
tvTipsText.setText(getResources().getString(
R.string.venue_activity_tip_count_single, venue.getTips().size()));
} else {
tvTipsText.setText(getResources().getString(
R.string.venue_activity_tip_count_plural, venue.getTips().size()));
}
ivTipsChevron.setVisibility(View.VISIBLE);
}
private void ensureUiTodosHere() {
Venue venue = mStateHolder.getVenue();
RelativeLayout rlTodoHere = (RelativeLayout)findViewById(R.id.venueActivityTodoHere);
if (venue != null && venue.getHasTodo()) {
rlTodoHere.setVisibility(View.VISIBLE);
rlTodoHere.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showTodoHereActivity();
}
});
} else {
rlTodoHere.setVisibility(View.GONE);
}
}
private void setClickHandlerMayor(View view) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(VenueActivity.this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL,
mStateHolder.getVenue().getStats().getMayor().getUser());
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
startActivity(intent);
}
});
}
private void setClickHandlerCheckins(View view) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(VenueActivity.this, VenueCheckinsActivity.class);
intent.putExtra(VenueCheckinsActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivity(intent);
}
});
}
private void setClickHandlerTips(View view) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = null;
if (mStateHolder.getVenue().getTips().size() == 1) {
Venue venue = new Venue();
venue.setName(mStateHolder.getVenue().getName());
venue.setAddress(mStateHolder.getVenue().getAddress());
venue.setCrossstreet(mStateHolder.getVenue().getCrossstreet());
Tip tip = mStateHolder.getVenue().getTips().get(0);
tip.setVenue(venue);
intent = new Intent(VenueActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip);
intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false);
startActivityForResult(intent, RESULT_CODE_ACTIVITY_TIP);
} else {
intent = new Intent(VenueActivity.this, VenueTipsActivity.class);
intent.putExtra(VenueTipsActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivityForResult(intent, RESULT_CODE_ACTIVITY_TIPS);
}
}
});
}
private void setClickHandlerMoreInfo(View view) {
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(VenueActivity.this, VenueMapActivity.class);
intent.putExtra(VenueMapActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivity(intent);
}
});
}
private void prepareResultIntent() {
Venue venue = mStateHolder.getVenue();
Intent intent = new Intent();
if (venue != null) {
intent.putExtra(EXTRA_VENUE_RETURNED, venue);
}
setResult(Activity.RESULT_OK, intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_TIP_ADD, 1, R.string.venue_activity_menu_add_tip).setIcon(
R.drawable.ic_menu_venue_leave_tip);
menu.add(Menu.NONE, MENU_TODO_ADD, 2, R.string.venue_activity_menu_add_todo).setIcon(
R.drawable.ic_menu_venue_add_todo);
menu.add(Menu.NONE, MENU_EDIT_VENUE, 3, R.string.venue_activity_menu_flag).setIcon(
R.drawable.ic_menu_venue_flag);
menu.add(Menu.NONE, MENU_CALL, 4, R.string.venue_activity_menu_call).setIcon(
R.drawable.ic_menu_venue_contact);
menu.add(Menu.NONE, MENU_SHARE, 5, R.string.venue_activity_menu_share).setIcon(
R.drawable.ic_menu_venue_share);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean callEnabled = mStateHolder.getVenue() != null
&& !TextUtils.isEmpty(mStateHolder.getVenue().getPhone());
menu.findItem(MENU_CALL).setEnabled(callEnabled);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_TIP_ADD:
Intent intentTip = new Intent(VenueActivity.this, AddTipActivity.class);
intentTip.putExtra(AddTipActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivityForResult(intentTip, RESULT_CODE_ACTIVITY_ADD_TIP);
return true;
case MENU_TODO_ADD:
Intent intentTodo = new Intent(VenueActivity.this, AddTodoActivity.class);
intentTodo.putExtra(AddTodoActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivityForResult(intentTodo, RESULT_CODE_ACTIVITY_ADD_TODO);
return true;
case MENU_EDIT_VENUE:
Intent intentEditVenue = new Intent(this, EditVenueOptionsActivity.class);
intentEditVenue.putExtra(
EditVenueOptionsActivity.EXTRA_VENUE_PARCELABLE, mStateHolder.getVenue());
startActivity(intentEditVenue);
return true;
case MENU_CALL:
try {
Intent dial = new Intent();
dial.setAction(Intent.ACTION_DIAL);
dial.setData(Uri.parse("tel:" + mStateHolder.getVenue().getPhone()));
startActivity(dial);
} catch (Exception ex) {
Log.e(TAG, "Error starting phone dialer intent.", ex);
Toast.makeText(this, "Sorry, we couldn't find any app to place a phone call!",
Toast.LENGTH_SHORT).show();
}
return true;
case MENU_SHARE:
Intent intentShare = new Intent(this, VenueShareActivity.class);
intentShare.putExtra(VenueShareActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivity(intentShare);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTasks(null);
return mStateHolder;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE:
if (resultCode == Activity.RESULT_OK) {
mStateHolder.setCheckedInHere(true);
ensureUiCheckinButton();
}
break;
case RESULT_CODE_ACTIVITY_ADD_TIP:
if (resultCode == Activity.RESULT_OK) {
Tip tip = data.getParcelableExtra(AddTipActivity.EXTRA_TIP_RETURNED);
VenueUtils.addTip(mStateHolder.getVenue(), tip);
ensureUiTipAdded();
prepareResultIntent();
Toast.makeText(this, getResources().getString(R.string.venue_activity_tip_added_ok),
Toast.LENGTH_SHORT).show();
}
break;
case RESULT_CODE_ACTIVITY_ADD_TODO:
if (resultCode == Activity.RESULT_OK) {
Todo todo = data.getParcelableExtra(AddTodoActivity.EXTRA_TODO_RETURNED);
VenueUtils.addTodo(mStateHolder.getVenue(), todo.getTip(), todo);
ensureUiTodosHere();
prepareResultIntent();
Toast.makeText(this, getResources().getString(R.string.venue_activity_todo_added_ok),
Toast.LENGTH_SHORT).show();
}
break;
case RESULT_CODE_ACTIVITY_TIP:
case RESULT_CODE_ACTIVITY_TODO:
if (resultCode == Activity.RESULT_OK && data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) {
Tip tip = (Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED);
Todo todo = data.hasExtra(TipActivity.EXTRA_TODO_RETURNED) ?
(Todo)data.getParcelableExtra(TipActivity.EXTRA_TODO_RETURNED) : null;
VenueUtils.handleTipChange(mStateHolder.getVenue(), tip, todo);
ensureUiTodosHere();
prepareResultIntent();
}
break;
case RESULT_CODE_ACTIVITY_TIPS:
if (resultCode == Activity.RESULT_OK && data.hasExtra(VenueTipsActivity.INTENT_EXTRA_RETURN_VENUE)) {
Venue venue = (Venue)data.getParcelableExtra(VenueTipsActivity.INTENT_EXTRA_RETURN_VENUE);
VenueUtils.replaceTipsAndTodos(mStateHolder.getVenue(), venue);
ensureUiTodosHere();
prepareResultIntent();
}
break;
case RESULT_CODE_ACTIVITY_TODOS:
if (resultCode == Activity.RESULT_OK && data.hasExtra(VenueTodosActivity.INTENT_EXTRA_RETURN_VENUE)) {
Venue venue = (Venue)data.getParcelableExtra(VenueTodosActivity.INTENT_EXTRA_RETURN_VENUE);
VenueUtils.replaceTipsAndTodos(mStateHolder.getVenue(), venue);
ensureUiTodosHere();
prepareResultIntent();
}
break;
}
}
private void startCheckin() {
Intent intent = new Intent(this, CheckinOrShoutGatherInfoActivity.class);
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_IS_CHECKIN, true);
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.getVenue().getId());
intent.putExtra(CheckinOrShoutGatherInfoActivity.INTENT_EXTRA_VENUE_NAME, mStateHolder.getVenue().getName());
startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE);
}
private void startCheckinQuick() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean tellFriends = settings.getBoolean(Preferences.PREFERENCE_SHARE_CHECKIN, true);
boolean tellTwitter = settings.getBoolean(Preferences.PREFERENCE_TWITTER_CHECKIN, false);
boolean tellFacebook = settings.getBoolean(Preferences.PREFERENCE_FACEBOOK_CHECKIN, false);
Intent intent = new Intent(VenueActivity.this, CheckinExecuteActivity.class);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_VENUE_ID, mStateHolder.getVenue().getId());
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_SHOUT, "");
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FRIENDS, tellFriends);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_TWITTER, tellTwitter);
intent.putExtra(CheckinExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK, tellFacebook);
startActivityForResult(intent, RESULT_CODE_ACTIVITY_CHECKIN_EXECUTE);
}
private void showWebViewForSpecial() {
Intent intent = new Intent(this, SpecialWebViewActivity.class);
intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_USERNAME,
PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_LOGIN, ""));
intent.putExtra(SpecialWebViewActivity.EXTRA_CREDENTIALS_PASSWORD,
PreferenceManager.getDefaultSharedPreferences(this).getString(Preferences.PREFERENCE_PASSWORD, ""));
intent.putExtra(SpecialWebViewActivity.EXTRA_SPECIAL_ID,
mStateHolder.getVenue().getSpecials().get(0).getId());
startActivity(intent);
}
private void showTodoHereActivity() {
Venue venue = new Venue();
venue.setName(mStateHolder.getVenue().getName());
venue.setAddress(mStateHolder.getVenue().getAddress());
venue.setCrossstreet(mStateHolder.getVenue().getCrossstreet());
Group<Todo> todos = mStateHolder.getVenue().getTodos();
for (Todo it : todos) {
it.getTip().setVenue(venue);
}
if (todos.size() == 1) {
Todo todo = (Todo) todos.get(0);
Intent intent = new Intent(VenueActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, todo.getTip());
intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false);
startActivityForResult(intent, RESULT_CODE_ACTIVITY_TODO);
} else if (todos.size() > 1) {
Intent intent = new Intent(VenueActivity.this, VenueTodosActivity.class);
intent.putExtra(VenueTodosActivity.INTENT_EXTRA_VENUE, mStateHolder.getVenue());
startActivityForResult(intent, RESULT_CODE_ACTIVITY_TODOS);
}
}
private int getFriendCountAtVenue() {
int count = 0;
Venue venue = mStateHolder.getVenue();
if (venue.getCheckins() != null) {
for (Checkin it : venue.getCheckins()) {
User user = it.getUser();
if (UserUtils.isFriend(user)) {
count++;
}
}
}
return count;
}
private int getTipCountFriendsAtVenue() {
int count = 0;
Venue venue = mStateHolder.getVenue();
if (venue.getTips() != null) {
for (Tip it : venue.getTips()) {
User user = it.getUser();
if (UserUtils.isFriend(user)) {
count++;
}
}
}
return count;
}
private static class TaskVenue extends AsyncTask<String, Void, Venue> {
private VenueActivity mActivity;
private Exception mReason;
public TaskVenue(VenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
}
@Override
protected Venue doInBackground(String... params) {
try {
Foursquared foursquared = (Foursquared)mActivity.getApplication();
return foursquared.getFoursquare().venue(
params[0],
LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
} catch (Exception e) {
Log.e(TAG, "Error getting venue details.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Venue venue) {
if (mActivity != null) {
mActivity.mStateHolder.setIsRunningTaskVenue(false);
if (venue != null) {
mActivity.mStateHolder.setLoadType(StateHolder.LOAD_TYPE_VENUE_FULL);
mActivity.mStateHolder.setVenue(venue);
mActivity.prepareResultIntent();
mActivity.ensureUi();
} else {
NotificationsUtil.ToastReasonForFailure(mActivity, mReason);
mActivity.finish();
}
}
}
@Override
protected void onCancelled() {
}
public void setActivity(VenueActivity activity) {
mActivity = activity;
}
}
private static final class StateHolder {
private Venue mVenue;
private String mVenueId;
private boolean mCheckedInHere;
private TaskVenue mTaskVenue;
private boolean mIsRunningTaskVenue;
private int mLoadType;
public static final int LOAD_TYPE_VENUE_ID = 0;
public static final int LOAD_TYPE_VENUE_PARTIAL = 1;
public static final int LOAD_TYPE_VENUE_FULL = 2;
public StateHolder() {
mIsRunningTaskVenue = false;
}
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
}
public void setVenueId(String venueId) {
mVenueId = venueId;
}
public boolean getCheckedInHere() {
return mCheckedInHere;
}
public void setCheckedInHere(boolean checkedInHere) {
mCheckedInHere = checkedInHere;
}
public void setIsRunningTaskVenue(boolean isRunningTaskVenue) {
mIsRunningTaskVenue = isRunningTaskVenue;
}
public void startTaskVenue(VenueActivity activity) {
if (!mIsRunningTaskVenue) {
mIsRunningTaskVenue = true;
mTaskVenue = new TaskVenue(activity);
if (mLoadType == LOAD_TYPE_VENUE_ID) {
mTaskVenue.execute(mVenueId);
} else if (mLoadType == LOAD_TYPE_VENUE_PARTIAL) {
mTaskVenue.execute(mVenue.getId());
}
}
}
public void setActivityForTasks(VenueActivity activity) {
if (mTaskVenue != null) {
mTaskVenue.setActivity(activity);
}
}
public int getLoadType() {
return mLoadType;
}
public void setLoadType(int loadType) {
mLoadType = loadType;
}
}
/**
* Handles population of the mayor photo. The strip of checkin photos has its own
* internal observer.
*/
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
mHandler.post(mRunnableMayorPhoto);
}
}
private Runnable mRunnableMayorPhoto = new Runnable() {
@Override
public void run() {
ImageView ivMayorPhoto = (ImageView)findViewById(R.id.venueActivityMayorPhoto);
if (ivMayorPhoto.getTag() != null) {
String mayorPhotoUrl = (String)ivMayorPhoto.getTag();
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(mayorPhotoUrl)));
ivMayorPhoto.setImageBitmap(bitmap);
ivMayorPhoto.setTag(null);
ivMayorPhoto.invalidate();
} catch (IOException ex) {
Log.e(TAG, "Error decoding mayor photo on notification, ignoring.", ex);
}
}
}
};
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.joelapenna.foursquared.widget.TipsListAdapter;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.Observable;
import java.util.Observer;
/**
* Shows a list of nearby tips. User can sort tips by friends-only.
*
* @date August 31, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TipsActivity extends LoadableListActivityWithViewAndHeader {
static final String TAG = "TipsActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int ACTIVITY_TIP = 500;
private StateHolder mStateHolder;
private TipsListAdapter mListAdapter;
private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver();
private View mLayoutEmpty;
private static final int MENU_REFRESH = 0;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
mStateHolder = new StateHolder();
mStateHolder.setFriendsOnly(true);
}
ensureUi();
// Friend tips is shown first by default so auto-fetch it if necessary.
if (!mStateHolder.getRanOnceTipsFriends()) {
mStateHolder.startTaskTips(this, true);
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver);
if (isFinishing()) {
mStateHolder.cancelTasks();
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void ensureUi() {
LayoutInflater inflater = LayoutInflater.from(this);
mLayoutEmpty = inflater.inflate(R.layout.tips_activity_empty, null);
mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
mListAdapter = new TipsListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item);
if (mStateHolder.getFriendsOnly()) {
mListAdapter.setGroup(mStateHolder.getTipsFriends());
if (mStateHolder.getTipsFriends().size() == 0) {
if (mStateHolder.getRanOnceTipsFriends()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
} else {
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
if (mStateHolder.getTipsEveryone().size() == 0) {
if (mStateHolder.getRanOnceTipsEveryone()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
}
SegmentedButton buttons = getHeaderButton();
buttons.clearButtons();
buttons.addButtons(
getString(R.string.tips_activity_btn_friends_only),
getString(R.string.tips_activity_btn_everyone));
if (mStateHolder.mFriendsOnly) {
buttons.setPushedButtonIndex(0);
} else {
buttons.setPushedButtonIndex(1);
}
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
if (index == 0) {
mStateHolder.setFriendsOnly(true);
mListAdapter.setGroup(mStateHolder.getTipsFriends());
if (mStateHolder.getTipsFriends().size() < 1) {
if (mStateHolder.getRanOnceTipsFriends()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(TipsActivity.this, true);
}
}
} else {
mStateHolder.setFriendsOnly(false);
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
if (mStateHolder.getTipsEveryone().size() < 1) {
if (mStateHolder.getRanOnceTipsEveryone()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(TipsActivity.this, false);
}
}
}
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
});
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(false);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tip tip = (Tip) parent.getAdapter().getItem(position);
Intent intent = new Intent(TipsActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip);
startActivityForResult(intent, ACTIVITY_TIP);
}
});
if (mStateHolder.getIsRunningTaskTipsFriends() ||
mStateHolder.getIsRunningTaskTipsEveryone()) {
setProgressBarIndeterminateVisibility(true);
} else {
setProgressBarIndeterminateVisibility(false);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh)
.setIcon(R.drawable.ic_menu_refresh);
MenuUtils.addPreferencesToMenu(this, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
mStateHolder.startTaskTips(this, mStateHolder.getFriendsOnly());
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// We don't care about the returned to-do (if any) since we're not bound
// to a venue in this activity for update. We just update the status member
// of the target tip.
if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) {
if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) {
Log.d(TAG, "onActivityResult(), return tip intent extra found, processing.");
updateTip((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED));
} else {
Log.d(TAG, "onActivityResult(), no return tip intent extra found.");
}
}
}
private void updateTip(Tip tip) {
mStateHolder.updateTip(tip);
mListAdapter.notifyDataSetInvalidated();
}
private void onStartTaskTips() {
if (mListAdapter != null) {
if (mStateHolder.getFriendsOnly()) {
mStateHolder.setIsRunningTaskTipsFriends(true);
mListAdapter.setGroup(mStateHolder.getTipsFriends());
} else {
mStateHolder.setIsRunningTaskTipsEveryone(true);
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
}
mListAdapter.notifyDataSetChanged();
}
setProgressBarIndeterminateVisibility(true);
setLoadingView();
}
private void onTaskTipsComplete(Group<Tip> group, boolean friendsOnly, Exception ex) {
SegmentedButton buttons = getHeaderButton();
boolean update = false;
if (group != null) {
if (friendsOnly) {
mStateHolder.setTipsFriends(group);
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsFriends());
update = true;
}
} else {
mStateHolder.setTipsEveryone(group);
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
update = true;
}
}
}
else {
if (friendsOnly) {
mStateHolder.setTipsFriends(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsFriends());
update = true;
}
} else {
mStateHolder.setTipsEveryone(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsEveryone());
update = true;
}
}
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (friendsOnly) {
mStateHolder.setIsRunningTaskTipsFriends(false);
mStateHolder.setRanOnceTipsFriends(true);
if (mStateHolder.getTipsFriends().size() == 0 &&
buttons.getSelectedButtonIndex() == 0) {
setEmptyView(mLayoutEmpty);
}
} else {
mStateHolder.setIsRunningTaskTipsEveryone(false);
mStateHolder.setRanOnceTipsEveryone(true);
if (mStateHolder.getTipsEveryone().size() == 0 &&
buttons.getSelectedButtonIndex() == 1) {
setEmptyView(mLayoutEmpty);
}
}
if (update) {
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
if (!mStateHolder.getIsRunningTaskTipsFriends() &&
!mStateHolder.getIsRunningTaskTipsEveryone()) {
setProgressBarIndeterminateVisibility(false);
}
}
/**
* Gets friends of the current user we're working for.
*/
private static class TaskTips extends AsyncTask<Void, Void, Group<Tip>> {
private TipsActivity mActivity;
private boolean mFriendsOnly;
private Exception mReason;
public TaskTips(TipsActivity activity, boolean friendsOnly) {
mActivity = activity;
mFriendsOnly = friendsOnly;
}
@Override
protected void onPreExecute() {
mActivity.onStartTaskTips();
}
@Override
protected Group<Tip> doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
Location loc = foursquared.getLastKnownLocation();
if (loc == null) {
try { Thread.sleep(3000); } catch (InterruptedException ex) {}
loc = foursquared.getLastKnownLocation();
if (loc == null) {
throw new FoursquareException("Your location could not be determined!");
}
}
return foursquare.tips(
LocationUtils.createFoursquareLocation(loc),
null,
mFriendsOnly ? "friends" : "nearby",
null,
30);
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Tip> tips) {
if (mActivity != null) {
mActivity.onTaskTipsComplete(tips, mFriendsOnly, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskTipsComplete(null, mFriendsOnly, mReason);
}
}
public void setActivity(TipsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
/** Tips by friends. */
private Group<Tip> mTipsFriends;
/** Tips by everyone. */
private Group<Tip> mTipsEveryone;
private TaskTips mTaskTipsFriends;
private TaskTips mTaskTipsEveryone;
private boolean mIsRunningTaskTipsFriends;
private boolean mIsRunningTaskTipsEveryone;
private boolean mFriendsOnly;
private boolean mRanOnceTipsFriends;
private boolean mRanOnceTipsEveryone;
public StateHolder() {
mIsRunningTaskTipsFriends = false;
mIsRunningTaskTipsEveryone = false;
mRanOnceTipsFriends = false;
mRanOnceTipsEveryone = false;
mTipsFriends = new Group<Tip>();
mTipsEveryone = new Group<Tip>();
mFriendsOnly = true;
}
public Group<Tip> getTipsFriends() {
return mTipsFriends;
}
public void setTipsFriends(Group<Tip> tipsFriends) {
mTipsFriends = tipsFriends;
}
public Group<Tip> getTipsEveryone() {
return mTipsEveryone;
}
public void setTipsEveryone(Group<Tip> tipsEveryone) {
mTipsEveryone = tipsEveryone;
}
public void startTaskTips(TipsActivity activity,
boolean friendsOnly) {
if (friendsOnly) {
if (mIsRunningTaskTipsFriends) {
return;
}
mIsRunningTaskTipsFriends = true;
mTaskTipsFriends = new TaskTips(activity, friendsOnly);
mTaskTipsFriends.execute();
} else {
if (mIsRunningTaskTipsEveryone) {
return;
}
mIsRunningTaskTipsEveryone = true;
mTaskTipsEveryone = new TaskTips(activity, friendsOnly);
mTaskTipsEveryone.execute();
}
}
public void setActivity(TipsActivity activity) {
if (mTaskTipsFriends != null) {
mTaskTipsFriends.setActivity(activity);
}
if (mTaskTipsEveryone != null) {
mTaskTipsEveryone.setActivity(activity);
}
}
public boolean getIsRunningTaskTipsFriends() {
return mIsRunningTaskTipsFriends;
}
public void setIsRunningTaskTipsFriends(boolean isRunning) {
mIsRunningTaskTipsFriends = isRunning;
}
public boolean getIsRunningTaskTipsEveryone() {
return mIsRunningTaskTipsEveryone;
}
public void setIsRunningTaskTipsEveryone(boolean isRunning) {
mIsRunningTaskTipsEveryone = isRunning;
}
public void cancelTasks() {
if (mTaskTipsFriends != null) {
mTaskTipsFriends.setActivity(null);
mTaskTipsFriends.cancel(true);
}
if (mTaskTipsEveryone != null) {
mTaskTipsEveryone.setActivity(null);
mTaskTipsEveryone.cancel(true);
}
}
public boolean getFriendsOnly() {
return mFriendsOnly;
}
public void setFriendsOnly(boolean friendsOnly) {
mFriendsOnly = friendsOnly;
}
public boolean getRanOnceTipsFriends() {
return mRanOnceTipsFriends;
}
public void setRanOnceTipsFriends(boolean ranOnce) {
mRanOnceTipsFriends = ranOnce;
}
public boolean getRanOnceTipsEveryone() {
return mRanOnceTipsEveryone;
}
public void setRanOnceTipsEveryone(boolean ranOnce) {
mRanOnceTipsEveryone = ranOnce;
}
public void updateTip(Tip tip) {
updateTipFromArray(tip, mTipsFriends);
updateTipFromArray(tip, mTipsEveryone);
}
private void updateTipFromArray(Tip tip, Group<Tip> target) {
for (Tip it : target) {
if (it.getId().equals(tip.getId())) {
it.setStatus(tip.getStatus());
break;
}
}
}
}
/**
* This is really just a dummy observer to get the GPS running
* since this is the new splash page. After getting a fix, we
* might want to stop registering this observer thereafter so
* it doesn't annoy the user too much.
*/
private class SearchLocationObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.NotificationsUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class LoginActivity extends Activity {
public static final String TAG = "LoginActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private AsyncTask<Void, Void, Boolean> mLoginTask;
private TextView mNewAccountTextView;
private EditText mPhoneUsernameEditText;
private EditText mPasswordEditText;
private ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login_activity);
Preferences.logoutUser( //
((Foursquared) getApplication()).getFoursquare(), //
PreferenceManager.getDefaultSharedPreferences(this).edit());
// Set up the UI.
ensureUi();
// Re-task if the request was cancelled.
mLoginTask = (LoginTask) getLastNonConfigurationInstance();
if (mLoginTask != null && mLoginTask.isCancelled()) {
if (DEBUG) Log.d(TAG, "LoginTask previously cancelled, trying again.");
mLoginTask = new LoginTask().execute();
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(false);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates();
}
@Override
public Object onRetainNonConfigurationInstance() {
if (DEBUG) Log.d(TAG, "onRetainNonConfigurationInstance()");
if (mLoginTask != null) {
mLoginTask.cancel(true);
}
return mLoginTask;
}
private ProgressDialog showProgressDialog() {
if (mProgressDialog == null) {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setTitle(R.string.login_dialog_title);
dialog.setMessage(getString(R.string.login_dialog_message));
dialog.setIndeterminate(true);
dialog.setCancelable(true);
mProgressDialog = dialog;
}
mProgressDialog.show();
return mProgressDialog;
}
private void dismissProgressDialog() {
try {
mProgressDialog.dismiss();
} catch (IllegalArgumentException e) {
// We don't mind. android cleared it for us.
}
}
private void ensureUi() {
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mLoginTask = new LoginTask().execute();
}
});
mNewAccountTextView = (TextView) findViewById(R.id.newAccountTextView);
mNewAccountTextView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(
Intent.ACTION_VIEW, Uri.parse(Foursquare.FOURSQUARE_MOBILE_SIGNUP)));
}
});
mPhoneUsernameEditText = ((EditText) findViewById(R.id.phoneEditText));
mPasswordEditText = ((EditText) findViewById(R.id.passwordEditText));
TextWatcher fieldValidatorTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
button.setEnabled(phoneNumberEditTextFieldIsValid()
&& passwordEditTextFieldIsValid());
}
private boolean phoneNumberEditTextFieldIsValid() {
// This can be either a phone number or username so we don't
// care too much about the
// format.
return !TextUtils.isEmpty(mPhoneUsernameEditText.getText());
}
private boolean passwordEditTextFieldIsValid() {
return !TextUtils.isEmpty(mPasswordEditText.getText());
}
};
mPhoneUsernameEditText.addTextChangedListener(fieldValidatorTextWatcher);
mPasswordEditText.addTextChangedListener(fieldValidatorTextWatcher);
}
private class LoginTask extends AsyncTask<Void, Void, Boolean> {
private static final String TAG = "LoginTask";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Exception mReason;
@Override
protected void onPreExecute() {
if (DEBUG) Log.d(TAG, "onPreExecute()");
showProgressDialog();
}
@Override
protected Boolean doInBackground(Void... params) {
if (DEBUG) Log.d(TAG, "doInBackground()");
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
Editor editor = prefs.edit();
Foursquared foursquared = (Foursquared) getApplication();
Foursquare foursquare = foursquared.getFoursquare();
try {
String phoneNumber = mPhoneUsernameEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
Foursquare.Location location = null;
location = LocationUtils.createFoursquareLocation(
foursquared.getLastKnownLocation());
boolean loggedIn = Preferences.loginUser(foursquare, phoneNumber, password,
location, editor);
// Make sure prefs makes a round trip.
String userId = Preferences.getUserId(prefs);
if (TextUtils.isEmpty(userId)) {
if (DEBUG) Log.d(TAG, "Preference store calls failed");
throw new FoursquareException(getResources().getString(
R.string.login_failed_login_toast));
}
return loggedIn;
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "Caught Exception logging in.", e);
mReason = e;
Preferences.logoutUser(foursquare, editor);
return false;
}
}
@Override
protected void onPostExecute(Boolean loggedIn) {
if (DEBUG) Log.d(TAG, "onPostExecute(): " + loggedIn);
Foursquared foursquared = (Foursquared) getApplication();
if (loggedIn) {
sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_IN));
Toast.makeText(LoginActivity.this, getString(R.string.login_welcome_toast),
Toast.LENGTH_LONG).show();
// Launch the service to update any widgets, etc.
foursquared.requestStartService();
// Launch the main activity to let the user do anything.
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
// Be done with the activity.
finish();
} else {
sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_OUT));
NotificationsUtil.ToastReasonForFailure(LoginActivity.this, mReason);
}
dismissProgressDialog();
}
@Override
protected void onCancelled() {
dismissProgressDialog();
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.error.LocationException;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.providers.VenueQuerySuggestionsProvider;
import com.joelapenna.foursquared.util.Comparators;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.TabsUtil;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.VenueListAdapter;
import android.app.Activity;
import android.app.SearchManager;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.SearchRecentSuggestions;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Collections;
import java.util.Observable;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class SearchVenuesActivity extends TabActivity {
static final String TAG = "SearchVenuesActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String QUERY_NEARBY = null;
public static SearchResultsObservable searchResultsObservable;
private static final int MENU_SEARCH = 0;
private static final int MENU_REFRESH = 1;
private static final int MENU_NEARBY = 2;
private static final int MENU_ADD_VENUE = 3;
private static final int MENU_GROUP_SEARCH = 0;
private SearchTask mSearchTask;
private SearchHolder mSearchHolder = new SearchHolder();
private ListView mListView;
private LinearLayout mEmpty;
private TextView mEmptyText;
private ProgressBar mEmptyProgress;
private TabHost mTabHost;
private SeparatedListAdapter mListAdapter;
private boolean mIsShortcutPicker;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.search_venues_activity);
setDefaultKeyMode(Activity.DEFAULT_KEYS_SEARCH_LOCAL);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
searchResultsObservable = new SearchResultsObservable();
initTabHost();
initListViewAdapter();
// Watch to see if we've been called as a shortcut intent.
mIsShortcutPicker = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction());
if (getLastNonConfigurationInstance() != null) {
if (DEBUG) Log.d(TAG, "Restoring state.");
SearchHolder holder = (SearchHolder) getLastNonConfigurationInstance();
if (holder.results != null) {
mSearchHolder.query = holder.query;
setSearchResults(holder.results);
putSearchResultsInAdapter(holder.results);
}
} else {
onNewIntent(getIntent());
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(true);
if (mSearchHolder.results == null && mSearchTask == null) {
mSearchTask = (SearchTask) new SearchTask().execute();
}
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates();
if (isFinishing()) {
mListAdapter.removeObserver();
}
}
@Override
public void onStop() {
super.onStop();
if (mSearchTask != null) {
mSearchTask.cancel(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Always show these.
menu.add(MENU_GROUP_SEARCH, MENU_SEARCH, Menu.NONE, R.string.search_label) //
.setIcon(R.drawable.ic_menu_search) //
.setAlphabeticShortcut(SearchManager.MENU_KEY);
menu.add(MENU_GROUP_SEARCH, MENU_NEARBY, Menu.NONE, R.string.nearby_label) //
.setIcon(R.drawable.ic_menu_places);
menu.add(MENU_GROUP_SEARCH, MENU_REFRESH, Menu.NONE, R.string.refresh) //
.setIcon(R.drawable.ic_menu_refresh);
menu.add(MENU_GROUP_SEARCH, MENU_ADD_VENUE, Menu.NONE, R.string.nearby_menu_add_venue) //
.setIcon(R.drawable.ic_menu_add);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_SEARCH:
onSearchRequested();
return true;
case MENU_NEARBY:
executeSearchTask(null);
return true;
case MENU_REFRESH:
executeSearchTask(mSearchHolder.query);
return true;
case MENU_ADD_VENUE:
Intent intent = new Intent(SearchVenuesActivity.this, AddVenueActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onNewIntent(Intent intent) {
if (intent != null) {
String action = intent.getAction();
String query = intent.getStringExtra(SearchManager.QUERY);
Log.i(TAG, "New Intent: action[" + action + "].");
if (!TextUtils.isEmpty(action)) {
if (action.equals(Intent.ACTION_CREATE_SHORTCUT)) {
Log.i(TAG, " action = create shortcut, user can click one of the current venues.");
} else if (action.equals(Intent.ACTION_VIEW)) {
if (!TextUtils.isEmpty(query)) {
Log.i(TAG, " action = view, query term provided, prepopulating search.");
startSearch(query, false, null, false);
} else {
Log.i(TAG, " action = view, but no query term provided, doing nothing.");
}
} else if (action.equals(Intent.ACTION_SEARCH) && !TextUtils.isEmpty(query)) {
Log.i(TAG, " action = search, query term provided, executing search immediately.");
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
VenueQuerySuggestionsProvider.AUTHORITY, VenueQuerySuggestionsProvider.MODE);
suggestions.saveRecentQuery(query, null);
executeSearchTask(query);
}
}
}
}
@Override
public Object onRetainNonConfigurationInstance() {
return mSearchHolder;
}
public void putSearchResultsInAdapter(Group<Group<Venue>> searchResults) {
mListAdapter.removeObserver();
mListAdapter = new SeparatedListAdapter(this);
int groupCount = searchResults.size();
for (int groupsIndex = 0; groupsIndex < groupCount; groupsIndex++) {
Group<Venue> group = searchResults.get(groupsIndex);
if (group.size() > 0) {
VenueListAdapter groupAdapter = new VenueListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
groupAdapter.setGroup(group);
if (DEBUG) Log.d(TAG, "Adding Section: " + group.getType());
mListAdapter.addSection(group.getType(), groupAdapter);
}
}
mListView.setAdapter(mListAdapter);
}
public void setSearchResults(Group<Group<Venue>> searchResults) {
if (DEBUG) Log.d(TAG, "Setting search results.");
mSearchHolder.results = searchResults;
searchResultsObservable.notifyObservers();
}
void executeSearchTask(String query) {
if (DEBUG) Log.d(TAG, "sendQuery()");
mSearchHolder.query = query;
// not going through set* because we don't want to notify search result
// observers.
mSearchHolder.results = null;
// If a task is already running, don't start a new one.
if (mSearchTask != null && mSearchTask.getStatus() != AsyncTask.Status.FINISHED) {
if (DEBUG) Log.d(TAG, "Query already running attempting to cancel: " + mSearchTask);
if (!mSearchTask.cancel(true) && !mSearchTask.isCancelled()) {
if (DEBUG) Log.d(TAG, "Unable to cancel search? Notifying the user.");
Toast.makeText(this, getString(R.string.search_already_in_progress_toast),
Toast.LENGTH_SHORT);
return;
}
}
mSearchTask = (SearchTask) new SearchTask().execute();
}
void startItemActivity(Venue venue) {
Intent intent = new Intent(SearchVenuesActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
startActivity(intent);
}
private void ensureSearchResults() {
if (mListAdapter.getCount() > 0) {
mEmpty.setVisibility(LinearLayout.GONE);
mListView.setVisibility(ViewGroup.VISIBLE);
} else {
mEmpty.setVisibility(LinearLayout.VISIBLE);
mEmptyProgress.setVisibility(ViewGroup.GONE);
mEmptyText.setText(R.string.no_search_results);
mListView.setVisibility(ViewGroup.GONE);
}
}
private void ensureTitle(boolean finished) {
if (finished) {
if (mSearchHolder.query == QUERY_NEARBY) {
setTitle(getString(R.string.title_search_finished_noquery));
} else {
setTitle(getString(R.string.title_search_finished, mSearchHolder.query));
}
} else {
if (mSearchHolder.query == QUERY_NEARBY) {
setTitle(getString(R.string.title_search_inprogress_noquery));
} else {
setTitle(getString(R.string.title_search_inprogress, mSearchHolder.query));
}
}
}
private void initListViewAdapter() {
if (mListView != null) {
throw new IllegalStateException("Trying to initialize already initialized ListView");
}
mEmpty = (LinearLayout) findViewById(R.id.empty);
mEmptyText = (TextView) findViewById(R.id.emptyText);
mEmptyProgress = (ProgressBar) findViewById(R.id.emptyProgress);
mListView = (ListView) findViewById(R.id.list);
mListAdapter = new SeparatedListAdapter(this);
mListView.setAdapter(mListAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Venue venue = (Venue) parent.getAdapter().getItem(position);
if (mIsShortcutPicker) {
setupShortcut(venue);
finish();
} else {
startItemActivity(venue);
}
finish();
}
});
}
protected void setupShortcut(Venue venue) {
// First, set up the shortcut intent. For this example, we simply create
// an intent that will bring us directly back to this activity. A more
// typical implementation would use a data Uri in order to display a more
// specific result, or a custom action in order to launch a specific operation.
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, VenueActivity.class.getName());
shortcutIntent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, venue.getId());
// Then, set up the container intent (the response to the caller)
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, venue.getName());
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this,
R.drawable.venue_shortcut_icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Now, return the result to the launcher
setResult(RESULT_OK, intent);
}
private void initTabHost() {
if (mTabHost != null) {
throw new IllegalStateException("Trying to intialize already initializd TabHost");
}
mTabHost = getTabHost();
TabsUtil.addTab(mTabHost, getString(R.string.tab_search_nav_venues),
R.drawable.tab_search_nav_venues_selector, 0, R.id.listviewLayout);
TabsUtil.addTab(mTabHost, getString(R.string.tab_search_nav_map),
R.drawable.tab_search_nav_map_selector,
1, new Intent(this, SearchVenuesMapActivity.class));
mTabHost.setCurrentTab(0);
// Fix layout for 1.5.
if (UiUtil.sdkVersion() < 4) {
FrameLayout flTabContent = (FrameLayout)findViewById(android.R.id.tabcontent);
flTabContent.setPadding(0, 0, 0, 0);
}
}
private class SearchTask extends AsyncTask<Void, Void, Group<Group<Venue>>> {
private Exception mReason = null;
@Override
public void onPreExecute() {
if (DEBUG) Log.d(TAG, "SearchTask: onPreExecute()");
setProgressBarIndeterminateVisibility(true);
ensureTitle(false);
}
@Override
public Group<Group<Venue>> doInBackground(Void... params) {
try {
return search();
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
public void onPostExecute(Group<Group<Venue>> groups) {
try {
if (groups == null) {
NotificationsUtil.ToastReasonForFailure(SearchVenuesActivity.this, mReason);
} else {
setSearchResults(groups);
putSearchResultsInAdapter(groups);
}
} finally {
setProgressBarIndeterminateVisibility(false);
ensureTitle(true);
ensureSearchResults();
}
}
public Group<Group<Venue>> search() throws FoursquareException, LocationException,
IOException {
Foursquare foursquare = ((Foursquared) getApplication()).getFoursquare();
Location location = ((Foursquared) getApplication()).getLastKnownLocationOrThrow();
Group<Group<Venue>> groups = foursquare.venues(LocationUtils
.createFoursquareLocation(location), mSearchHolder.query, 30);
for (int i = 0; i < groups.size(); i++) {
Collections.sort(groups.get(i), Comparators.getVenueDistanceComparator());
}
return groups;
}
}
private static class SearchHolder {
Group<Group<Venue>> results;
String query;
}
class SearchResultsObservable extends Observable {
@Override
public void notifyObservers(Object data) {
setChanged();
super.notifyObservers(data);
}
public Group<Group<Venue>> getSearchResults() {
return mSearchHolder.results;
}
public String getQuery() {
return mSearchHolder.query;
}
};
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.MenuUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.util.StringFormatters;
import com.joelapenna.foursquared.util.UiUtil;
import com.joelapenna.foursquared.util.UserUtils;
import com.joelapenna.foursquared.widget.PhotoStrip;
import com.joelapenna.foursquared.widget.UserContactAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* @date March 8, 2010.
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserDetailsActivity extends Activity {
private static final String TAG = "UserDetailsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int ACTIVITY_REQUEST_CODE_PINGS = 815;
private static final int ACTIVITY_REQUEST_CODE_FETCH_IMAGE = 816;
private static final int ACTIVITY_REQUEST_CODE_VIEW_AND_SET_IMAGE = 817;
public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME
+ ".UserDetailsActivity.EXTRA_USER_PARCEL";
public static final String EXTRA_USER_ID = Foursquared.PACKAGE_NAME
+ ".UserDetailsActivity.EXTRA_USER_ID";
public static final String EXTRA_SHOW_ADD_FRIEND_OPTIONS = Foursquared.PACKAGE_NAME
+ ".UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS";
private static final int LOAD_TYPE_USER_NONE = 0;
private static final int LOAD_TYPE_USER_ID = 1;
private static final int LOAD_TYPE_USER_PARTIAL = 2;
private static final int LOAD_TYPE_USER_FULL = 3;
private static final int MENU_REFRESH = 0;
private static final int MENU_CONTACT = 1;
private static final int MENU_PINGS = 2;
private static final int DIALOG_CONTACTS = 0;
private StateHolder mStateHolder;
private RemoteResourceManager mRrm;
private RemoteResourceManagerObserver mResourcesObserver;
private Handler mHandler;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.user_details_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivityForTasks(this);
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(EXTRA_USER_PARCEL)) {
Log.i(TAG, "Starting " + TAG + " with full user parcel.");
User user = getIntent().getExtras().getParcelable(EXTRA_USER_PARCEL);
mStateHolder.setUser(user);
mStateHolder.setLoadType(LOAD_TYPE_USER_PARTIAL);
} else if (getIntent().hasExtra(EXTRA_USER_ID)) {
Log.i(TAG, "Starting " + TAG + " with user ID.");
User user = new User();
user.setId(getIntent().getExtras().getString(EXTRA_USER_ID));
mStateHolder.setUser(user);
mStateHolder.setLoadType(LOAD_TYPE_USER_ID);
} else {
Log.i(TAG, "Starting " + TAG + " as logged-in user.");
User user = new User();
user.setId(null);
mStateHolder.setUser(user);
mStateHolder.setLoadType(LOAD_TYPE_USER_ID);
}
mStateHolder.setIsLoggedInUser(
mStateHolder.getUser().getId() == null ||
mStateHolder.getUser().getId().equals(
((Foursquared) getApplication()).getUserId()));
}
mHandler = new Handler();
mRrm = ((Foursquared) getApplication()).getRemoteResourceManager();
mResourcesObserver = new RemoteResourceManagerObserver();
mRrm.addObserver(mResourcesObserver);
ensureUi();
if (mStateHolder.getLoadType() != LOAD_TYPE_USER_FULL &&
!mStateHolder.getIsRunningUserDetailsTask() &&
!mStateHolder.getRanOnce()) {
mStateHolder.startTaskUserDetails(this, mStateHolder.getUser().getId());
}
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mStateHolder.cancelTasks();
mHandler.removeCallbacks(mRunnableUpdateUserPhoto);
RemoteResourceManager rrm = ((Foursquared) getApplication()).getRemoteResourceManager();
rrm.deleteObserver(mResourcesObserver);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
private void ensureUi() {
int sdk = UiUtil.sdkVersion();
View viewProgressBar = findViewById(R.id.venueActivityDetailsProgress);
TextView tvUsername = (TextView)findViewById(R.id.userDetailsActivityUsername);
TextView tvLastSeen = (TextView)findViewById(R.id.userDetailsActivityHometownOrLastSeen);
Button btnFriend = (Button)findViewById(R.id.userDetailsActivityFriendButton);
View viewMayorships = findViewById(R.id.userDetailsActivityGeneralMayorships);
View viewBadges = findViewById(R.id.userDetailsActivityGeneralBadges);
View viewTips = findViewById(R.id.userDetailsActivityGeneralTips);
TextView tvMayorships = (TextView)findViewById(R.id.userDetailsActivityGeneralMayorshipsValue);
TextView tvBadges = (TextView)findViewById(R.id.userDetailsActivityGeneralBadgesValue);
TextView tvTips = (TextView)findViewById(R.id.userDetailsActivityGeneralTipsValue);
ImageView ivMayorshipsChevron = (ImageView)findViewById(R.id.userDetailsActivityGeneralMayorshipsChevron);
ImageView ivBadgesChevron = (ImageView)findViewById(R.id.userDetailsActivityGeneralBadgesChevron);
ImageView ivTipsChevron = (ImageView)findViewById(R.id.userDetailsActivityGeneralTipsChevron);
View viewCheckins = findViewById(R.id.userDetailsActivityCheckins);
View viewFriendsFollowers = findViewById(R.id.userDetailsActivityFriendsFollowers);
View viewAddFriends = findViewById(R.id.userDetailsActivityAddFriends);
View viewTodos = findViewById(R.id.userDetailsActivityTodos);
View viewFriends = findViewById(R.id.userDetailsActivityFriends);
TextView tvCheckins = (TextView)findViewById(R.id.userDetailsActivityCheckinsText);
ImageView ivCheckinsChevron = (ImageView)findViewById(R.id.userDetailsActivityCheckinsChevron);
TextView tvFriendsFollowers = (TextView)findViewById(R.id.userDetailsActivityFriendsFollowersText);
ImageView ivFriendsFollowersChevron = (ImageView)findViewById(R.id.userDetailsActivityFriendsFollowersChevron);
TextView tvTodos = (TextView)findViewById(R.id.userDetailsActivityTodosText);
ImageView ivTodos = (ImageView)findViewById(R.id.userDetailsActivityTodosChevron);
TextView tvFriends = (TextView)findViewById(R.id.userDetailsActivityFriendsText);
ImageView ivFriends = (ImageView)findViewById(R.id.userDetailsActivityFriendsChevron);
PhotoStrip psFriends = (PhotoStrip)findViewById(R.id.userDetailsActivityFriendsPhotos);
viewProgressBar.setVisibility(View.VISIBLE);
tvUsername.setText("");
tvLastSeen.setText("");
viewMayorships.setFocusable(false);
viewBadges.setFocusable(false);
viewTips.setFocusable(false);
tvMayorships.setText("0");
tvBadges.setText("0");
tvTips.setText("0");
ivMayorshipsChevron.setVisibility(View.INVISIBLE);
ivBadgesChevron.setVisibility(View.INVISIBLE);
ivTipsChevron.setVisibility(View.INVISIBLE);
btnFriend.setVisibility(View.INVISIBLE);
viewCheckins.setFocusable(false);
viewFriendsFollowers.setFocusable(false);
viewAddFriends.setFocusable(false);
viewTodos.setFocusable(false);
viewFriends.setFocusable(false);
viewCheckins.setVisibility(View.GONE);
viewFriendsFollowers.setVisibility(View.GONE);
viewAddFriends.setVisibility(View.GONE);
viewTodos.setVisibility(View.GONE);
viewFriends.setVisibility(View.GONE);
ivCheckinsChevron.setVisibility(View.INVISIBLE);
ivFriendsFollowersChevron.setVisibility(View.INVISIBLE);
ivTodos.setVisibility(View.INVISIBLE);
ivFriends.setVisibility(View.INVISIBLE);
psFriends.setVisibility(View.GONE);
tvCheckins.setText("");
tvFriendsFollowers.setText("");
tvTodos.setText("");
tvFriends.setText("");
if (mStateHolder.getLoadType() >= LOAD_TYPE_USER_PARTIAL) {
User user = mStateHolder.getUser();
ensureUiPhoto(user);
if (mStateHolder.getIsLoggedInUser() || UserUtils.isFriend(user)) {
tvUsername.setText(StringFormatters.getUserFullName(user));
} else {
tvUsername.setText(StringFormatters.getUserAbbreviatedName(user));
}
tvLastSeen.setText(user.getHometown());
if (mStateHolder.getIsLoggedInUser() ||
UserUtils.isFriend(user) ||
UserUtils.isFriendStatusPendingThem(user) ||
UserUtils.isFriendStatusFollowingThem(user)) {
btnFriend.setVisibility(View.INVISIBLE);
} else if (UserUtils.isFriendStatusPendingYou(user)) {
btnFriend.setVisibility(View.VISIBLE);
btnFriend.setText(getString(R.string.user_details_activity_friend_confirm));
btnFriend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mStateHolder.startTaskFriend(UserDetailsActivity.this, StateHolder.TASK_FRIEND_ACCEPT);
}
});
} else {
btnFriend.setVisibility(View.VISIBLE);
btnFriend.setText(getString(R.string.user_details_activity_friend_add));
btnFriend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
view.setEnabled(false);
mStateHolder.startTaskFriend(UserDetailsActivity.this, StateHolder.TASK_FRIEND_ADD);
}
});
}
if (mStateHolder.getLoadType() >= LOAD_TYPE_USER_FULL) {
viewProgressBar.setVisibility(View.GONE);
tvMayorships.setText(String.valueOf(user.getMayorCount()));
tvBadges.setText(String.valueOf(user.getBadgeCount()));
tvTips.setText(String.valueOf(user.getTipCount()));
if (user.getCheckin() != null && user.getCheckin().getVenue() != null) {
String fixed = getResources().getString(R.string.user_details_activity_last_seen);
String full = fixed + " " + user.getCheckin().getVenue().getName();
CharacterStyle bold = new StyleSpan(Typeface.BOLD);
SpannableString ss = new SpannableString(full);
ss.setSpan(bold, fixed.length(), full.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
tvLastSeen.setText(ss);
tvLastSeen.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
startVenueActivity();
}
});
}
if (user.getMayorships() != null && user.getMayorships().size() > 0) {
viewMayorships.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startMayorshipsActivity();
}
});
viewMayorships.setFocusable(true);
if (sdk > 3) {
ivMayorshipsChevron.setVisibility(View.VISIBLE);
}
}
if (user.getBadges() != null && user.getBadges().size() > 0) {
viewBadges.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startBadgesActivity();
}
});
viewBadges.setFocusable(true);
if (sdk > 3) {
ivBadgesChevron.setVisibility(View.VISIBLE);
}
}
if (user.getTipCount() > 0) {
viewTips.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startTipsActivity();
}
});
viewTips.setFocusable(true);
if (sdk > 3) {
ivTipsChevron.setVisibility(View.VISIBLE);
}
}
// The rest of the items depend on if we're viewing ourselves or not.
if (mStateHolder.getIsLoggedInUser()) {
viewCheckins.setVisibility(View.VISIBLE);
viewFriendsFollowers.setVisibility(View.VISIBLE);
viewAddFriends.setVisibility(View.VISIBLE);
tvCheckins.setText(
user.getCheckinCount() == 1 ?
getResources().getString(
R.string.user_details_activity_checkins_text_single, user.getCheckinCount()) :
getResources().getString(
R.string.user_details_activity_checkins_text_plural, user.getCheckinCount()));
if (user.getCheckinCount() > 0) {
viewCheckins.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startCheckinsActivity();
}
});
viewCheckins.setFocusable(true);
ivCheckinsChevron.setVisibility(View.VISIBLE);
}
if (user.getFollowerCount() > 0) {
tvFriendsFollowers.setText(
user.getFollowerCount() == 1 ?
getResources().getString(
R.string.user_details_activity_friends_followers_text_celeb_single,
user.getFollowerCount()) :
getResources().getString(
R.string.user_details_activity_friends_followers_text_celeb_plural,
user.getFollowerCount()));
if (user.getFriendCount() > 0) {
tvFriendsFollowers.setText(tvFriendsFollowers.getText() + ", ");
}
}
tvFriendsFollowers.setText(tvFriendsFollowers.getText().toString() +
(user.getFriendCount() == 1 ?
getResources().getString(
R.string.user_details_activity_friends_followers_text_single,
user.getFriendCount()) :
getResources().getString(
R.string.user_details_activity_friends_followers_text_plural,
user.getFriendCount())));
if (user.getFollowerCount() + user.getFriendCount() > 0) {
viewFriendsFollowers.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startFriendsFollowersActivity();
}
});
viewFriendsFollowers.setFocusable(true);
ivFriendsFollowersChevron.setVisibility(View.VISIBLE);
}
viewAddFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startAddFriendsActivity();
}
});
viewAddFriends.setFocusable(true);
} else {
viewTodos.setVisibility(View.VISIBLE);
viewFriends.setVisibility(View.VISIBLE);
tvTodos.setText(
user.getTodoCount() == 1 ?
getResources().getString(
R.string.user_details_activity_todos_text_single, user.getTodoCount()) :
getResources().getString(
R.string.user_details_activity_todos_text_plural, user.getTodoCount()));
if (user.getTodoCount() > 0 && UserUtils.isFriend(user)) {
viewTodos.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startTodosActivity();
}
});
viewTodos.setFocusable(true);
ivTodos.setVisibility(View.VISIBLE);
}
tvFriends.setText(
user.getFriendCount() == 1 ?
getResources().getString(
R.string.user_details_activity_friends_text_single,
user.getFriendCount()) :
getResources().getString(
R.string.user_details_activity_friends_text_plural,
user.getFriendCount()));
int friendsInCommon = user.getFriendsInCommon() == null ? 0 :
user.getFriendsInCommon().size();
if (friendsInCommon > 0) {
tvFriends.setText(tvFriends.getText().toString() +
(friendsInCommon == 1 ?
getResources().getString(
R.string.user_details_activity_friends_in_common_text_single,
friendsInCommon) :
getResources().getString(
R.string.user_details_activity_friends_in_common_text_plural,
friendsInCommon)));
}
if (user.getFriendCount() > 0) {
viewFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startFriendsInCommonActivity();
}
});
viewFriends.setFocusable(true);
ivFriends.setVisibility(View.VISIBLE);
}
if (friendsInCommon > 0) {
psFriends.setVisibility(View.VISIBLE);
psFriends.setUsersAndRemoteResourcesManager(user.getFriendsInCommon(), mRrm);
} else {
tvFriends.setPadding(tvFriends.getPaddingLeft(), tvTodos.getPaddingTop(),
tvFriends.getPaddingRight(), tvTodos.getPaddingBottom());
}
}
} else {
// Haven't done a full load.
if (mStateHolder.getRanOnce()) {
viewProgressBar.setVisibility(View.GONE);
}
}
} else {
// Haven't done a full load.
if (mStateHolder.getRanOnce()) {
viewProgressBar.setVisibility(View.GONE);
}
}
// Regardless of load state, if running a task, show titlebar progress bar.
if (mStateHolder.getIsTaskRunning()) {
setProgressBarIndeterminateVisibility(true);
} else {
setProgressBarIndeterminateVisibility(false);
}
// Disable friend button if running friend task.
if (mStateHolder.getIsRunningFriendTask()) {
btnFriend.setEnabled(false);
} else {
btnFriend.setEnabled(true);
}
}
private void ensureUiPhoto(User user) {
ImageView ivPhoto = (ImageView)findViewById(R.id.userDetailsActivityPhoto);
if (user == null || user.getPhoto() == null) {
ivPhoto.setImageResource(R.drawable.blank_boy);
return;
}
Uri uriPhoto = Uri.parse(user.getPhoto());
if (mRrm.exists(uriPhoto)) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(Uri.parse(user
.getPhoto())));
ivPhoto.setImageBitmap(bitmap);
} catch (IOException e) {
setUserPhotoMissing(ivPhoto, user);
}
} else {
mRrm.request(uriPhoto);
setUserPhotoMissing(ivPhoto, user);
}
ivPhoto.postInvalidate();
ivPhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mStateHolder.getLoadType() == LOAD_TYPE_USER_FULL) {
User user = mStateHolder.getUser();
// If "_thumbs" exists, remove it to get the url of the
// full-size image.
String photoUrl = user.getPhoto().replace("_thumbs", "");
// If we're viewing our own page, clicking the thumbnail should send the user
// to our built-in image viewer. Here we can give them the option of setting
// a new photo for themselves.
Intent intent = new Intent(UserDetailsActivity.this, FetchImageForViewIntent.class);
intent.putExtra(FetchImageForViewIntent.IMAGE_URL, photoUrl);
intent.putExtra(FetchImageForViewIntent.PROGRESS_BAR_MESSAGE, getResources()
.getString(R.string.user_activity_fetch_full_image_message));
if (mStateHolder.getIsLoggedInUser()) {
intent.putExtra(FetchImageForViewIntent.LAUNCH_VIEW_INTENT_ON_COMPLETION, false);
startActivityForResult(intent, ACTIVITY_REQUEST_CODE_FETCH_IMAGE);
} else {
startActivity(intent);
}
}
}
});
}
private void setUserPhotoMissing(ImageView ivPhoto, User user) {
if (Foursquare.MALE.equals(user.getGender())) {
ivPhoto.setImageResource(R.drawable.blank_boy);
} else {
ivPhoto.setImageResource(R.drawable.blank_girl);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTasks(null);
return mStateHolder;
}
private void startBadgesActivity() {
if (mStateHolder.getUser() != null) {
Intent intent = new Intent(UserDetailsActivity.this, BadgesActivity.class);
intent.putParcelableArrayListExtra(BadgesActivity.EXTRA_BADGE_ARRAY_LIST_PARCEL,
mStateHolder.getUser().getBadges());
intent.putExtra(BadgesActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
}
private void startMayorshipsActivity() {
if (mStateHolder.getUser() != null) {
Intent intent = new Intent(UserDetailsActivity.this, UserMayorshipsActivity.class);
intent.putExtra(UserMayorshipsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(UserMayorshipsActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
}
private void startCheckinsActivity() {
Intent intent = new Intent(UserDetailsActivity.this, UserHistoryActivity.class);
intent.putExtra(UserHistoryActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
private void startFriendsFollowersActivity() {
User user = mStateHolder.getUser();
Intent intent = null;
if (user.getFollowerCount() > 0) {
intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsFollowersActivity.class);
intent.putExtra(UserDetailsFriendsFollowersActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
} else {
intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsActivity.class);
intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
}
startActivity(intent);
}
private void startAddFriendsActivity() {
Intent intent = new Intent(UserDetailsActivity.this, AddFriendsActivity.class);
startActivity(intent);
}
private void startFriendsInCommonActivity() {
User user = mStateHolder.getUser();
Intent intent = null;
if (user.getFriendsInCommon() != null && user.getFriendsInCommon().size() > 0) {
intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsInCommonActivity.class);
intent.putExtra(UserDetailsFriendsInCommonActivity.EXTRA_USER_PARCEL, mStateHolder.getUser());
} else {
intent = new Intent(UserDetailsActivity.this, UserDetailsFriendsActivity.class);
intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(UserDetailsFriendsActivity.EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
}
startActivity(intent);
}
private void startTodosActivity() {
Intent intent = new Intent(UserDetailsActivity.this, TodosActivity.class);
intent.putExtra(TodosActivity.INTENT_EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(TodosActivity.INTENT_EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
private void startTipsActivity() {
Intent intent = new Intent(UserDetailsActivity.this, UserDetailsTipsActivity.class);
intent.putExtra(UserDetailsTipsActivity.INTENT_EXTRA_USER_ID, mStateHolder.getUser().getId());
intent.putExtra(UserDetailsTipsActivity.INTENT_EXTRA_USER_NAME, mStateHolder.getUser().getFirstname());
startActivity(intent);
}
private void startVenueActivity() {
User user = mStateHolder.getUser();
if (user.getCheckin() != null &&
user.getCheckin().getVenue() != null) {
Intent intent = new Intent(this, VenueActivity.class);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, user.getCheckin().getVenue());
startActivity(intent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh)
.setIcon(R.drawable.ic_menu_refresh);
if (mStateHolder.getIsLoggedInUser()) {
MenuUtils.addPreferencesToMenu(this, menu);
} else {
menu.add(Menu.NONE, MENU_CONTACT, Menu.NONE, R.string.user_details_activity_friends_menu_contact)
.setIcon(R.drawable.ic_menu_user_contact);
if (UserUtils.isFriend(mStateHolder.getUser())) {
menu.add(Menu.NONE, MENU_PINGS, Menu.NONE, R.string.user_details_activity_friends_menu_pings)
.setIcon(android.R.drawable.ic_menu_rotate);
}
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
User user = mStateHolder.getUser();
MenuItem refresh = menu.findItem(MENU_REFRESH);
MenuItem contact = menu.findItem(MENU_CONTACT);
MenuItem pings = menu.findItem(MENU_PINGS);
if (!mStateHolder.getIsRunningUserDetailsTask()) {
refresh.setEnabled(true);
if (contact != null) {
boolean contactEnabled =
!TextUtils.isEmpty(user.getFacebook()) ||
!TextUtils.isEmpty(user.getTwitter()) ||
!TextUtils.isEmpty(user.getEmail()) ||
!TextUtils.isEmpty(user.getPhone());
contact.setEnabled(contactEnabled);
}
if (pings != null) {
pings.setEnabled(true);
}
} else {
refresh.setEnabled(false);
if (contact != null) {
contact.setEnabled(false);
}
if (pings != null) {
pings.setEnabled(false);
}
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
mStateHolder.startTaskUserDetails(this, mStateHolder.getUser().getId());
return true;
case MENU_CONTACT:
showDialog(DIALOG_CONTACTS);
return true;
case MENU_PINGS:
Intent intentPings = new Intent(this, UserDetailsPingsActivity.class);
intentPings.putExtra(UserDetailsPingsActivity.EXTRA_USER_PARCEL, mStateHolder.getUser());
startActivityForResult(intentPings, ACTIVITY_REQUEST_CODE_PINGS);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_REQUEST_CODE_PINGS:
if (resultCode == Activity.RESULT_OK) {
User user = (User)data.getParcelableExtra(UserDetailsPingsActivity.EXTRA_USER_RETURNED);
if (user != null) {
mStateHolder.getUser().getSettings().setGetPings(user.getSettings().getGetPings());
}
}
break;
case ACTIVITY_REQUEST_CODE_FETCH_IMAGE:
if (resultCode == Activity.RESULT_OK) {
String imagePath = data.getStringExtra(FetchImageForViewIntent.EXTRA_SAVED_IMAGE_PATH_RETURNED);
if (mStateHolder.getIsLoggedInUser() && !TextUtils.isEmpty(imagePath)) {
Intent intent = new Intent(this, FullSizeImageActivity.class);
intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_IMAGE_PATH, imagePath);
intent.putExtra(FullSizeImageActivity.INTENT_EXTRA_ALLOW_SET_NEW_PHOTO, true);
startActivityForResult(intent, ACTIVITY_REQUEST_CODE_VIEW_AND_SET_IMAGE);
}
}
break;
case ACTIVITY_REQUEST_CODE_VIEW_AND_SET_IMAGE:
if (resultCode == Activity.RESULT_OK) {
String imageUrl = data.getStringExtra(FullSizeImageActivity.INTENT_RETURN_NEW_PHOTO_URL);
if (!TextUtils.isEmpty(imageUrl)) {
mStateHolder.getUser().setPhoto(imageUrl);
ensureUiPhoto(mStateHolder.getUser());
}
}
break;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_CONTACTS:
final UserContactAdapter adapter = new UserContactAdapter(this, mStateHolder.getUser());
AlertDialog dlgInfo = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.user_details_activity_friends_menu_contact))
.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlg, int pos) {
UserContactAdapter.Action action = (UserContactAdapter.Action)adapter.getItem(pos);
switch (action.getActionId()) {
case UserContactAdapter.Action.ACTION_ID_SMS:
UiUtil.startSmsIntent(UserDetailsActivity.this, mStateHolder.getUser().getPhone());
break;
case UserContactAdapter.Action.ACTION_ID_EMAIL:
UiUtil.startEmailIntent(UserDetailsActivity.this, mStateHolder.getUser().getEmail());
break;
case UserContactAdapter.Action.ACTION_ID_PHONE:
UiUtil.startDialer(UserDetailsActivity.this, mStateHolder.getUser().getPhone());
break;
case UserContactAdapter.Action.ACTION_ID_TWITTER:
UiUtil.startWebIntent(UserDetailsActivity.this, "http://www.twitter.com/" +
mStateHolder.getUser().getTwitter());
break;
case UserContactAdapter.Action.ACTION_ID_FACEBOOK:
UiUtil.startWebIntent(UserDetailsActivity.this, "http://www.facebook.com/profile.php?id=" +
mStateHolder.getUser().getFacebook());
break;
}
}
})
.create();
return dlgInfo;
}
return null;
}
private void onUserDetailsTaskComplete(User user, Exception ex) {
mStateHolder.setIsRunningUserDetailsTask(false);
mStateHolder.setRanOnce(true);
if (user != null) {
mStateHolder.setUser(user);
mStateHolder.setLoadType(LOAD_TYPE_USER_FULL);
} else if (ex != null) {
NotificationsUtil.ToastReasonForFailure(this, ex);
} else {
Toast.makeText(this, "A surprising new error has occurred!", Toast.LENGTH_SHORT).show();
}
ensureUi();
}
/**
* Even if the caller supplies us with a User object parcelable, it won't
* have all the badge etc extra info in it. As soon as the activity starts,
* we launch this task to fetch a full user object, and merge it with
* whatever is already supplied in mUser.
*/
private static class UserDetailsTask extends AsyncTask<String, Void, User> {
private UserDetailsActivity mActivity;
private Exception mReason;
public UserDetailsTask(UserDetailsActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.ensureUi();
}
@Override
protected User doInBackground(String... params) {
try {
return ((Foursquared) mActivity.getApplication()).getFoursquare().user(
params[0],
true,
true,
true,
LocationUtils.createFoursquareLocation(((Foursquared) mActivity
.getApplication()).getLastKnownLocation()));
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(User user) {
if (mActivity != null) {
mActivity.onUserDetailsTaskComplete(user, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onUserDetailsTaskComplete(null, mReason);
}
}
public void setActivity(UserDetailsActivity activity) {
mActivity = activity;
}
}
private void onFriendTaskComplete(User user, int action, Exception ex) {
mStateHolder.setIsRunningFriendTask(false);
// The api isn't returning an updated friend status flag here, so we'll
// overwrite it manually for now, assuming success if the user object
// was not null.
User userCurrent = mStateHolder.getUser();
if (user != null) {
switch (action) {
case StateHolder.TASK_FRIEND_ACCEPT:
userCurrent.setFirstname(user.getFirstname());
userCurrent.setLastname(user.getLastname());
userCurrent.setFriendstatus("friend");
break;
case StateHolder.TASK_FRIEND_ADD:
userCurrent.setFriendstatus("pendingthem");
break;
}
} else {
NotificationsUtil.ToastReasonForFailure(this, ex);
}
ensureUi();
}
private static class FriendTask extends AsyncTask<Void, Void, User> {
private UserDetailsActivity mActivity;
private String mUserId;
private int mAction;
private Exception mReason;
public FriendTask(UserDetailsActivity activity, String userId, int action) {
mActivity = activity;
mUserId = userId;
mAction = action;
}
@Override
protected void onPreExecute() {
mActivity.ensureUi();
}
@Override
protected User doInBackground(Void... params) {
Foursquare foursquare = ((Foursquared) mActivity.getApplication()).getFoursquare();
try {
switch (mAction) {
case StateHolder.TASK_FRIEND_ACCEPT:
return foursquare.friendApprove(mUserId);
case StateHolder.TASK_FRIEND_ADD:
return foursquare.friendSendrequest(mUserId);
default:
throw new FoursquareException("Unknown action type supplied.");
}
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(User user) {
if (mActivity != null) {
mActivity.onFriendTaskComplete(user, mAction, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onFriendTaskComplete(null, mAction, mReason);
}
}
public void setActivity(UserDetailsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
public static final int TASK_FRIEND_ACCEPT = 0;
public static final int TASK_FRIEND_ADD = 1;
private User mUser;
private boolean mIsLoggedInUser;
private UserDetailsTask mTaskUserDetails;
private boolean mIsRunningUserDetailsTask;
private boolean mRanOnce;
private int mLoadType;
private FriendTask mTaskFriend;
private boolean mIsRunningFriendTask;
public StateHolder() {
mIsRunningUserDetailsTask = false;
mIsRunningFriendTask = false;
mIsLoggedInUser = false;
mRanOnce = false;
mLoadType = LOAD_TYPE_USER_NONE;
}
public boolean getIsLoggedInUser() {
return mIsLoggedInUser;
}
public void setIsLoggedInUser(boolean isLoggedInUser) {
mIsLoggedInUser = isLoggedInUser;
}
public User getUser() {
return mUser;
}
public void setUser(User user) {
mUser = user;
}
public int getLoadType() {
return mLoadType;
}
public void setLoadType(int loadType) {
mLoadType = loadType;
}
public void startTaskUserDetails(UserDetailsActivity activity, String userId) {
if (!mIsRunningUserDetailsTask) {
mIsRunningUserDetailsTask = true;
mTaskUserDetails = new UserDetailsTask(activity);
mTaskUserDetails.execute(userId);
}
}
public void startTaskFriend(UserDetailsActivity activity, int action) {
if (!mIsRunningFriendTask) {
mIsRunningFriendTask = true;
mTaskFriend = new FriendTask(activity, mUser.getId(), action);
mTaskFriend.execute();
}
}
public void setActivityForTasks(UserDetailsActivity activity) {
if (mTaskUserDetails != null) {
mTaskUserDetails.setActivity(activity);
}
if (mTaskFriend != null) {
mTaskFriend.setActivity(activity);
}
}
public boolean getIsRunningUserDetailsTask() {
return mIsRunningUserDetailsTask;
}
public void setIsRunningUserDetailsTask(boolean isRunning) {
mIsRunningUserDetailsTask = isRunning;
}
public boolean getRanOnce() {
return mRanOnce;
}
public void setRanOnce(boolean ranOnce) {
mRanOnce = ranOnce;
}
public boolean getIsRunningFriendTask() {
return mIsRunningFriendTask;
}
public void setIsRunningFriendTask(boolean isRunning) {
mIsRunningFriendTask = isRunning;
}
public void cancelTasks() {
if (mTaskUserDetails != null) {
mTaskUserDetails.setActivity(null);
mTaskUserDetails.cancel(true);
}
if (mTaskFriend != null) {
mTaskFriend.setActivity(null);
mTaskFriend.cancel(true);
}
}
public boolean getIsTaskRunning() {
return mIsRunningUserDetailsTask || mIsRunningFriendTask;
}
}
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
mHandler.post(mRunnableUpdateUserPhoto);
}
}
private Runnable mRunnableUpdateUserPhoto = new Runnable() {
@Override
public void run() {
ensureUiPhoto(mStateHolder.getUser());
}
};
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.widget.CategoryPickerAdapter;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
/**
* Presents the user with a list of all available categories from foursquare
* that they can use to label a new venue.
*
* @date March 7, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class CategoryPickerDialog extends Dialog {
private static final String TAG = "FriendRequestsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Foursquared mApplication;
private Group<Category> mCategories;
private ViewFlipper mViewFlipper;
private Category mChosenCategory;
private int mFirstDialogHeight;
public CategoryPickerDialog(Context context, Group<Category> categories, Foursquared application) {
super(context);
mApplication = application;
mCategories = categories;
mChosenCategory = null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_picker_dialog);
setTitle(getContext().getResources().getString(R.string.category_picket_dialog_title));
mViewFlipper = (ViewFlipper) findViewById(R.id.categoryPickerViewFlipper);
mFirstDialogHeight = -1;
// By default we always have a top-level page.
Category root = new Category();
root.setNodeName("root");
root.setChildCategories(mCategories);
mViewFlipper.addView(makePage(root));
}
private View makePage(Category category) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.category_picker_page, null);
CategoryPickerPage page = new CategoryPickerPage();
page.ensureUI(view, mPageListItemSelected, category, mApplication
.getRemoteResourceManager());
view.setTag(page);
if (mViewFlipper.getChildCount() == 1 && mFirstDialogHeight == -1) {
mFirstDialogHeight = mViewFlipper.getChildAt(0).getHeight();
}
if (mViewFlipper.getChildCount() > 0) {
view.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, mFirstDialogHeight));
}
return view;
}
@Override
protected void onStop() {
super.onStop();
cleanupPageAdapters();
}
private void cleanupPageAdapters() {
for (int i = 0; i < mViewFlipper.getChildCount(); i++) {
CategoryPickerPage page = (CategoryPickerPage) mViewFlipper.getChildAt(i).getTag();
page.cleanup();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mViewFlipper.getChildCount() > 1) {
mViewFlipper.removeViewAt(mViewFlipper.getChildCount() - 1);
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/**
* After the user has dismissed the dialog, the parent activity can use this
* to see which category they picked, if any. Will return null if no
* category was picked.
*/
public Category getChosenCategory() {
return mChosenCategory;
}
private static class CategoryPickerPage {
private CategoryPickerAdapter mListAdapter;
private Category mCategory;
private PageListItemSelected mClickListener;
public void ensureUI(View view, PageListItemSelected clickListener, Category category,
RemoteResourceManager rrm) {
mCategory = category;
mClickListener = clickListener;
mListAdapter = new CategoryPickerAdapter(view.getContext(), rrm, category);
ListView listview = (ListView) view.findViewById(R.id.categoryPickerListView);
listview.setAdapter(mListAdapter);
listview.setOnItemClickListener(mOnItemClickListener);
LinearLayout llRootCategory = (LinearLayout) view
.findViewById(R.id.categoryPickerRootCategoryButton);
if (category.getNodeName().equals("root") == false) {
ImageView iv = (ImageView) view.findViewById(R.id.categoryPickerIcon);
try {
Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(Uri
.parse(category.getIconUrl())));
iv.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.e(TAG, "Error loading category icon from disk.", e);
}
TextView tv = (TextView) view.findViewById(R.id.categoryPickerName);
tv.setText(category.getNodeName());
llRootCategory.setClickable(true);
llRootCategory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mClickListener.onCategorySelected(mCategory);
}
});
} else {
llRootCategory.setVisibility(View.GONE);
}
}
public void cleanup() {
mListAdapter.removeObserver();
}
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
mClickListener.onPageListItemSelcected((Category) mListAdapter.getItem(position));
}
};
}
private PageListItemSelected mPageListItemSelected = new PageListItemSelected() {
@Override
public void onPageListItemSelcected(Category category) {
// If the item has children, create a new page for it.
if (category.getChildCategories() != null && category.getChildCategories().size() > 0) {
mViewFlipper.addView(makePage(category));
mViewFlipper.showNext();
} else {
// This is a leaf node, finally the user's selection. Record the
// category
// then cancel ourselves, parent activity should pick us up
// after that.
mChosenCategory = category;
cancel();
}
}
@Override
public void onCategorySelected(Category category) {
// The user has chosen the category parent listed at the top of the
// current page.
mChosenCategory = category;
cancel();
}
};
private interface PageListItemSelected {
public void onPageListItemSelcected(Category category);
public void onCategorySelected(Category category);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.util.StringFormatters;
/**
* Lets the user add a todo for a venue.
*
* @date September 16, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class AddTodoActivity extends Activity {
private static final String TAG = "AddTodoActivity";
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".AddTodoActivity.INTENT_EXTRA_VENUE";
public static final String EXTRA_TODO_RETURNED = Foursquared.PACKAGE_NAME
+ ".AddTodoActivity.EXTRA_TODO_RETURNED";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_todo_activity);
StateHolder holder = (StateHolder) getLastNonConfigurationInstance();
if (holder != null) {
mStateHolder = holder;
mStateHolder.setActivityForTasks(this);
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setVenue((Venue)getIntent().getParcelableExtra(INTENT_EXTRA_VENUE));
} else {
Log.e(TAG, "AddTodoActivity must be given a venue parcel as intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivityForTasks(null);
return mStateHolder;
}
private void ensureUi() {
TextView tvVenueName = (TextView)findViewById(R.id.addTodoActivityVenueName);
tvVenueName.setText(mStateHolder.getVenue().getName());
TextView tvVenueAddress = (TextView)findViewById(R.id.addTodoActivityVenueAddress);
tvVenueAddress.setText(StringFormatters.getVenueLocationCrossStreetOrCity(
mStateHolder.getVenue()));
Button btn = (Button) findViewById(R.id.addTodoActivityButton);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText et = (EditText)findViewById(R.id.addTodoActivityText);
String text = et.getText().toString();
mStateHolder.startTaskAddTodo(AddTodoActivity.this, mStateHolder.getVenue().getId(), text);
}
});
if (mStateHolder.getIsRunningTaskVenue()) {
startProgressBar();
}
}
private void startProgressBar() {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, "",
getResources().getString(R.string.add_tip_todo_activity_progress_message));
mDlgProgress.setCancelable(true);
mDlgProgress.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Log.e(TAG, "User cancelled add todo.");
mStateHolder.cancelTasks();
}
});
}
mDlgProgress.show();
setProgressBarIndeterminateVisibility(true);
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
setProgressBarIndeterminateVisibility(false);
}
private static class TaskAddTodo extends AsyncTask<Void, Void, Todo> {
private AddTodoActivity mActivity;
private String mVenueId;
private String mTipText;
private Exception mReason;
public TaskAddTodo(AddTodoActivity activity, String venueId, String tipText) {
mActivity = activity;
mVenueId = venueId;
mTipText = tipText;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected Todo doInBackground(Void... params) {
try {
// If the user entered optional text, we need to use one endpoint,
// if not, we need to use mark/todo.
Foursquared foursquared = (Foursquared)mActivity.getApplication();
Todo todo = null;
if (!TextUtils.isEmpty(mTipText)) {
// The returned tip won't have the user object or venue attached to it
// as part of the response. The venue is the parent venue and the user
// is the logged-in user.
Tip tip = foursquared.getFoursquare().addTip(
mVenueId, mTipText, "todo",
LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation()));
// So fetch the full tip for convenience.
Tip tipFull = foursquared.getFoursquare().tipDetail(tip.getId());
// The addtip API returns a tip instead of a todo, unlike the mark/todo endpoint,
// so we create a dummy todo object for now to wrap the tip.
String now = StringFormatters.createServerDateFormatV1();
todo = new Todo();
todo.setId("id_" + now);
todo.setCreated(now);
todo.setTip(tipFull);
Log.i(TAG, "Added todo with wrapper ID: " + todo.getId());
} else {
// No text, so in this case we need to mark the venue itself as a todo.
todo = foursquared.getFoursquare().markTodoVenue(mVenueId);
Log.i(TAG, "Added todo with ID: " + todo.getId());
}
return todo;
} catch (Exception e) {
Log.e(TAG, "Error adding tip.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Todo todo) {
mActivity.stopProgressBar();
mActivity.mStateHolder.setIsRunningTaskAddTip(false);
if (todo != null) {
Intent intent = new Intent();
intent.putExtra(EXTRA_TODO_RETURNED, todo);
mActivity.setResult(Activity.RESULT_OK, intent);
mActivity.finish();
} else {
NotificationsUtil.ToastReasonForFailure(mActivity, mReason);
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
}
@Override
protected void onCancelled() {
mActivity.stopProgressBar();
mActivity.setResult(Activity.RESULT_CANCELED);
mActivity.finish();
}
public void setActivity(AddTodoActivity activity) {
mActivity = activity;
}
}
private static final class StateHolder {
private Venue mVenue;
private TaskAddTodo mTaskAddTodo;
private boolean mIsRunningTaskAddTip;
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
}
public boolean getIsRunningTaskVenue() {
return mIsRunningTaskAddTip;
}
public void setIsRunningTaskAddTip(boolean isRunningTaskAddTip) {
mIsRunningTaskAddTip = isRunningTaskAddTip;
}
public void startTaskAddTodo(AddTodoActivity activity, String venueId, String text) {
mIsRunningTaskAddTip = true;
mTaskAddTodo = new TaskAddTodo(activity, venueId, text);
mTaskAddTodo.execute();
}
public void setActivityForTasks(AddTodoActivity activity) {
if (mTaskAddTodo != null) {
mTaskAddTodo.setActivity(activity);
}
}
public void cancelTasks() {
if (mTaskAddTodo != null) {
mTaskAddTodo.cancel(true);
}
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.providers;
import android.content.SearchRecentSuggestionsProvider;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueQuerySuggestionsProvider extends SearchRecentSuggestionsProvider {
public static final String AUTHORITY = "com.joelapenna.foursquared.providers.VenueQuerySuggestionsProvider";
public static final int MODE = DATABASE_MODE_QUERIES;
public VenueQuerySuggestionsProvider() {
super();
setupSuggestions(AUTHORITY, MODE);
}
}
| Java |
/**
* Copyright 2010 Tauno Talimaa
*/
package com.joelapenna.foursquared.providers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.error.LocationException;
import com.joelapenna.foursquared.location.BestLocationListener;
import com.joelapenna.foursquared.location.LocationUtils;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
/**
* A ContentProvider for Foursquare search results.
*
* @author Tauno Talimaa (tauntz@gmail.com)
*/
public class GlobalSearchProvider extends ContentProvider {
// TODO: Implement search for friends by name/phone number/twitter ID when
// API is implemented in Foursquare.java
private static final String TAG = GlobalSearchProvider.class.getSimpleName();
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final String[] QSB_COLUMNS = {
"_id", SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_QUERY,
SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
SearchManager.SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING,
SearchManager.SUGGEST_COLUMN_INTENT_DATA, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
};
private static final int URI_TYPE_QUERY = 1;
private static final int URI_TYPE_SHORTCUT = 2;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(Foursquared.PACKAGE_NAME, SearchManager.SUGGEST_URI_PATH_QUERY + "/*",
URI_TYPE_QUERY);
sUriMatcher.addURI(Foursquared.PACKAGE_NAME,
SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", URI_TYPE_SHORTCUT);
}
public static final String VENUE_DIRECTORY = "venue";
public static final String FRIEND_DIRECTORY = "friend";
// TODO: Use the argument from SUGGEST_PARAMETER_LIMIT from the Uri passed
// to query() instead of the hardcoded value (this is available starting
// from API level 5)
private static final int VENUE_QUERY_LIMIT = 30;
private Foursquare mFoursquare;
@Override
public boolean onCreate() {
synchronized (this) {
if (mFoursquare == null) mFoursquare = Foursquared.createFoursquare(getContext());
}
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
String query = uri.getLastPathSegment();
MatrixCursor cursor = new MatrixCursor(QSB_COLUMNS);
switch (sUriMatcher.match(uri)) {
case URI_TYPE_QUERY:
if (DEBUG) {
Log.d(TAG, "Global search for venue name: " + query);
}
Group<Group<Venue>> venueGroups;
try {
venueGroups = mFoursquare.venues(LocationUtils
.createFoursquareLocation(getBestRecentLocation()), query,
VENUE_QUERY_LIMIT);
} catch (FoursquareError e) {
if (DEBUG) Log.e(TAG, "Could not get venue list for query: " + query, e);
return cursor;
} catch (FoursquareException e) {
if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e);
return cursor;
} catch (LocationException e) {
if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e);
return cursor;
} catch (IOException e) {
if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e);
return cursor;
}
for (int groupIndex = 0; groupIndex < venueGroups.size(); groupIndex++) {
Group<Venue> venueGroup = venueGroups.get(groupIndex);
if (DEBUG) {
Log.d(TAG, venueGroup.size() + " results for group: "
+ venueGroup.getType());
}
for (int venueIndex = 0; venueIndex < venueGroup.size(); venueIndex++) {
Venue venue = venueGroup.get(venueIndex);
if (DEBUG) {
Log.d(TAG, "Venue " + venueIndex + ": " + venue.getName() + " ("
+ venue.getAddress() + ")");
}
cursor.addRow(new Object[] {
venue.getId(),
com.joelapenna.foursquared.R.drawable.venue_shortcut_icon,
venue.getName(), venue.getAddress(), venue.getName(),
venue.getId(), "true", VENUE_DIRECTORY, venue.getId()
});
}
}
break;
case URI_TYPE_SHORTCUT:
if (DEBUG) {
Log.d(TAG, "Global search for venue ID: " + query);
}
Venue venue;
try {
venue = mFoursquare.venue(query, LocationUtils
.createFoursquareLocation(getBestRecentLocation()));
} catch (FoursquareError e) {
if (DEBUG) Log.e(TAG, "Could not get venue details for venue ID: " + query, e);
return cursor;
} catch (LocationException e) {
if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e);
return cursor;
} catch (FoursquareException e) {
if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e);
return cursor;
} catch (IOException e) {
if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e);
return cursor;
}
if (DEBUG) {
Log.d(TAG, "Updated venue details: " + venue.getName() + " ("
+ venue.getAddress() + ")");
}
cursor.addRow(new Object[] {
venue.getId(), com.joelapenna.foursquared.R.drawable.venue_shortcut_icon,
venue.getName(), venue.getAddress(), venue.getName(), venue.getId(),
"true", VENUE_DIRECTORY, venue.getId()
});
break;
case UriMatcher.NO_MATCH:
if (DEBUG) {
Log.d(TAG, "No matching URI for: " + uri);
}
break;
}
return cursor;
}
@Override
public String getType(Uri uri) {
return SearchManager.SUGGEST_MIME_TYPE;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
/**
* Convenience method for getting the most recent Location
*
* @return the most recent Locations
* @throws LocationException when no recent Location could be determined
*/
private Location getBestRecentLocation() throws LocationException {
BestLocationListener locationListener = new BestLocationListener();
locationListener.updateLastKnownLocation((LocationManager) getContext().getSystemService(
Context.LOCATION_SERVICE));
Location location = locationListener.getLastKnownLocation();
if (location != null) {
return location;
}
throw new LocationException();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.util.IconUtils;
import com.joelapenna.foursquared.app.FoursquaredService;
import com.joelapenna.foursquared.error.LocationException;
import com.joelapenna.foursquared.location.BestLocationListener;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.JavaLoggingHandler;
import com.joelapenna.foursquared.util.NullDiskCache;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import android.app.Application;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Foursquared extends Application {
private static final String TAG = "Foursquared";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
static {
Logger.getLogger("com.joelapenna.foursquare").addHandler(new JavaLoggingHandler());
Logger.getLogger("com.joelapenna.foursquare").setLevel(Level.ALL);
}
public static final String PACKAGE_NAME = "com.joelapenna.foursquared";
public static final String INTENT_ACTION_LOGGED_OUT = "com.joelapenna.foursquared.intent.action.LOGGED_OUT";
public static final String INTENT_ACTION_LOGGED_IN = "com.joelapenna.foursquared.intent.action.LOGGED_IN";
private String mVersion = null;
private TaskHandler mTaskHandler;
private HandlerThread mTaskThread;
private SharedPreferences mPrefs;
private RemoteResourceManager mRemoteResourceManager;
private Foursquare mFoursquare;
private BestLocationListener mBestLocationListener = new BestLocationListener();
private boolean mIsFirstRun;
@Override
public void onCreate() {
Log.i(TAG, "Using Debug Server:\t" + FoursquaredSettings.USE_DEBUG_SERVER);
Log.i(TAG, "Using Dumpcatcher:\t" + FoursquaredSettings.USE_DUMPCATCHER);
Log.i(TAG, "Using Debug Log:\t" + DEBUG);
mVersion = getVersionString(this);
// Check if this is a new install by seeing if our preference file exists on disk.
mIsFirstRun = checkIfIsFirstRun();
// Setup Prefs (to load dumpcatcher)
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// Setup some defaults in our preferences if not set yet.
Preferences.setupDefaults(mPrefs, getResources());
// If we're on a high density device, request higher res images. This singleton
// is picked up by the parsers to replace their icon urls with high res versions.
float screenDensity = getApplicationContext().getResources().getDisplayMetrics().density;
IconUtils.get().setRequestHighDensityIcons(screenDensity > 1.0f);
// Setup Dumpcatcher - We've outgrown this infrastructure but we'll
// leave its calls in place for the day that someone pays for some
// appengine quota.
// if (FoursquaredSettings.USE_DUMPCATCHER) {
// Resources resources = getResources();
// new DumpcatcherHelper(Preferences.createUniqueId(mPrefs), resources);
// }
// Sometimes we want the application to do some work on behalf of the
// Activity. Lets do that
// asynchronously.
mTaskThread = new HandlerThread(TAG + "-AsyncThread");
mTaskThread.start();
mTaskHandler = new TaskHandler(mTaskThread.getLooper());
// Set up storage cache.
loadResourceManagers();
// Catch sdcard state changes
new MediaCardStateBroadcastReceiver().register();
// Catch logins or logouts.
new LoggedInOutBroadcastReceiver().register();
// Log into Foursquare, if we can.
loadFoursquare();
}
public boolean isReady() {
return getFoursquare().hasLoginAndPassword() && !TextUtils.isEmpty(getUserId());
}
public Foursquare getFoursquare() {
return mFoursquare;
}
public String getUserId() {
return Preferences.getUserId(mPrefs);
}
public String getUserName() {
return Preferences.getUserName(mPrefs);
}
public String getUserEmail() {
return Preferences.getUserEmail(mPrefs);
}
public String getUserGender() {
return Preferences.getUserGender(mPrefs);
}
public String getVersion() {
if (mVersion != null) {
return mVersion;
} else {
return "";
}
}
public String getLastSeenChangelogVersion() {
return Preferences.getLastSeenChangelogVersion(mPrefs);
}
public void storeLastSeenChangelogVersion(String version) {
Preferences.storeLastSeenChangelogVersion(mPrefs.edit(), version);
}
public boolean getUseNativeImageViewerForFullScreenImages() {
return Preferences.getUseNativeImageViewerForFullScreenImages(mPrefs);
}
public RemoteResourceManager getRemoteResourceManager() {
return mRemoteResourceManager;
}
public BestLocationListener requestLocationUpdates(boolean gps) {
mBestLocationListener.register(
(LocationManager) getSystemService(Context.LOCATION_SERVICE), gps);
return mBestLocationListener;
}
public BestLocationListener requestLocationUpdates(Observer observer) {
mBestLocationListener.addObserver(observer);
mBestLocationListener.register(
(LocationManager) getSystemService(Context.LOCATION_SERVICE), true);
return mBestLocationListener;
}
public void removeLocationUpdates() {
mBestLocationListener
.unregister((LocationManager) getSystemService(Context.LOCATION_SERVICE));
}
public void removeLocationUpdates(Observer observer) {
mBestLocationListener.deleteObserver(observer);
this.removeLocationUpdates();
}
public Location getLastKnownLocation() {
return mBestLocationListener.getLastKnownLocation();
}
public Location getLastKnownLocationOrThrow() throws LocationException {
Location location = mBestLocationListener.getLastKnownLocation();
if (location == null) {
throw new LocationException();
}
return location;
}
public void clearLastKnownLocation() {
mBestLocationListener.clearLastKnownLocation();
}
public void requestStartService() {
mTaskHandler.sendMessage( //
mTaskHandler.obtainMessage(TaskHandler.MESSAGE_START_SERVICE));
}
public void requestUpdateUser() {
mTaskHandler.sendEmptyMessage(TaskHandler.MESSAGE_UPDATE_USER);
}
private void loadFoursquare() {
// Try logging in and setting up foursquare oauth, then user
// credentials.
if (FoursquaredSettings.USE_DEBUG_SERVER) {
mFoursquare = new Foursquare(Foursquare.createHttpApi("10.0.2.2:8080", mVersion, false));
} else {
mFoursquare = new Foursquare(Foursquare.createHttpApi(mVersion, false));
}
if (FoursquaredSettings.DEBUG) Log.d(TAG, "loadCredentials()");
String phoneNumber = mPrefs.getString(Preferences.PREFERENCE_LOGIN, null);
String password = mPrefs.getString(Preferences.PREFERENCE_PASSWORD, null);
mFoursquare.setCredentials(phoneNumber, password);
if (mFoursquare.hasLoginAndPassword()) {
sendBroadcast(new Intent(INTENT_ACTION_LOGGED_IN));
} else {
sendBroadcast(new Intent(INTENT_ACTION_LOGGED_OUT));
}
}
/**
* Provides static access to a Foursquare instance. This instance is
* initiated without user credentials.
*
* @param context the context to use when constructing the Foursquare
* instance
* @return the Foursquare instace
*/
public static Foursquare createFoursquare(Context context) {
String version = getVersionString(context);
if (FoursquaredSettings.USE_DEBUG_SERVER) {
return new Foursquare(Foursquare.createHttpApi("10.0.2.2:8080", version, false));
} else {
return new Foursquare(Foursquare.createHttpApi(version, false));
}
}
/**
* Constructs the version string of the application.
*
* @param context the context to use for getting package info
* @return the versions string of the application
*/
private static String getVersionString(Context context) {
// Get a version string for the app.
try {
PackageManager pm = context.getPackageManager();
PackageInfo pi = pm.getPackageInfo(PACKAGE_NAME, 0);
return PACKAGE_NAME + ":" + String.valueOf(pi.versionCode);
} catch (NameNotFoundException e) {
if (DEBUG) Log.d(TAG, "Could not retrieve package info", e);
throw new RuntimeException(e);
}
}
private void loadResourceManagers() {
// We probably don't have SD card access if we get an
// IllegalStateException. If it did, lets
// at least have some sort of disk cache so that things don't npe when
// trying to access the
// resource managers.
try {
if (DEBUG) Log.d(TAG, "Attempting to load RemoteResourceManager(cache)");
mRemoteResourceManager = new RemoteResourceManager("cache");
} catch (IllegalStateException e) {
if (DEBUG) Log.d(TAG, "Falling back to NullDiskCache for RemoteResourceManager");
mRemoteResourceManager = new RemoteResourceManager(new NullDiskCache());
}
}
public boolean getIsFirstRun() {
return mIsFirstRun;
}
private boolean checkIfIsFirstRun() {
File file = new File(
"/data/data/com.joelapenna.foursquared/shared_prefs/com.joelapenna.foursquared_preferences.xml");
return !file.exists();
}
/**
* Set up resource managers on the application depending on SD card state.
*
* @author Joe LaPenna (joe@joelapenna.com)
*/
private class MediaCardStateBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG)
Log
.d(TAG, "Media state changed, reloading resource managers:"
+ intent.getAction());
if (Intent.ACTION_MEDIA_UNMOUNTED.equals(intent.getAction())) {
getRemoteResourceManager().shutdown();
loadResourceManagers();
} else if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())) {
loadResourceManagers();
}
}
public void register() {
// Register our media card broadcast receiver so we can
// enable/disable the cache as
// appropriate.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
// intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
// intentFilter.addAction(Intent.ACTION_MEDIA_SHARED);
// intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
// intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTABLE);
// intentFilter.addAction(Intent.ACTION_MEDIA_NOFS);
// intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
// intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter.addDataScheme("file");
registerReceiver(this, intentFilter);
}
}
private class LoggedInOutBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (INTENT_ACTION_LOGGED_IN.equals(intent.getAction())) {
requestUpdateUser();
}
}
public void register() {
// Register our media card broadcast receiver so we can
// enable/disable the cache as
// appropriate.
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(INTENT_ACTION_LOGGED_IN);
intentFilter.addAction(INTENT_ACTION_LOGGED_OUT);
registerReceiver(this, intentFilter);
}
}
private class TaskHandler extends Handler {
private static final int MESSAGE_UPDATE_USER = 1;
private static final int MESSAGE_START_SERVICE = 2;
public TaskHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (DEBUG) Log.d(TAG, "handleMessage: " + msg.what);
switch (msg.what) {
case MESSAGE_UPDATE_USER:
try {
// Update user info
Log.d(TAG, "Updating user.");
// Use location when requesting user information, if we
// have it.
Foursquare.Location location = LocationUtils
.createFoursquareLocation(getLastKnownLocation());
User user = getFoursquare().user(
null, false, false, false, location);
Editor editor = mPrefs.edit();
Preferences.storeUser(editor, user);
editor.commit();
if (location == null) {
// Pump the location listener, we don't have a
// location in our listener yet.
Log.d(TAG, "Priming Location from user city.");
Location primeLocation = new Location("foursquare");
// Very inaccurate, right?
primeLocation.setTime(System.currentTimeMillis());
mBestLocationListener.updateLocation(primeLocation);
}
} catch (FoursquareError e) {
if (DEBUG) Log.d(TAG, "FoursquareError", e);
// TODO Auto-generated catch block
} catch (FoursquareException e) {
if (DEBUG) Log.d(TAG, "FoursquareException", e);
// TODO Auto-generated catch block
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "IOException", e);
// TODO Auto-generated catch block
}
return;
case MESSAGE_START_SERVICE:
Intent serviceIntent = new Intent(Foursquared.this, FoursquaredService.class);
serviceIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
startService(serviceIntent);
return;
}
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.app.LoadableListActivity;
import com.joelapenna.foursquared.util.UserUtils;
import com.joelapenna.foursquared.util.VenueUtils;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.TipsListAdapter;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.List;
/**
* Shows tips left at a venue as a sectioned list adapter. Groups are split
* into tips left by friends and tips left by everyone else.
*
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -modified to start TipActivity on tip click (2010-03-25)
* -added photos for tips (2010-03-25)
* -refactored for new VenueActivity design (2010-09-16)
*/
public class VenueTipsActivity extends LoadableListActivity {
public static final String TAG = "VenueTipsActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".VenueTipsActivity.INTENT_EXTRA_VENUE";
public static final String INTENT_EXTRA_RETURN_VENUE = Foursquared.PACKAGE_NAME
+ ".VenueTipsActivity.INTENT_EXTRA_RETURN_VENUE";
private static final int ACTIVITY_TIP = 500;
private SeparatedListAdapter mListAdapter;
private StateHolder mStateHolder;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
setPreparedResultIntent();
} else {
mStateHolder = new StateHolder();
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder.setVenue((Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE));
} else {
Log.e(TAG, "VenueTipsActivity requires a venue parcel its intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mListAdapter.removeObserver();
}
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
return mStateHolder;
}
private void ensureUi() {
mListAdapter = new SeparatedListAdapter(this);
if (mStateHolder.getTipsFriends().size() > 0) {
TipsListAdapter adapter = new TipsListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item);
adapter.setDisplayTipVenueTitles(false);
adapter.setGroup(mStateHolder.getTipsFriends());
mListAdapter.addSection(getString(R.string.venue_tips_activity_section_friends,
mStateHolder.getTipsFriends().size()),
adapter);
}
TipsListAdapter adapter = new TipsListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_list_item);
adapter.setDisplayTipVenueTitles(false);
adapter.setGroup(mStateHolder.getTipsAll());
mListAdapter.addSection(getString(R.string.venue_tips_activity_section_all,
mStateHolder.getTipsAll().size()),
adapter);
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(true);
listView.setDividerHeight(0);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// The tip that was clicked won't have its venue member set, since we got
// here by viewing the parent venue. In this case, we request that the tip
// activity not let the user recursively start drilling down past here.
// Create a dummy venue which has only the name and address filled in.
Venue venue = new Venue();
venue.setName(mStateHolder.getVenue().getName());
venue.setAddress(mStateHolder.getVenue().getAddress());
venue.setCrossstreet(mStateHolder.getVenue().getCrossstreet());
Tip tip = (Tip)parent.getAdapter().getItem(position);
tip.setVenue(venue);
Intent intent = new Intent(VenueTipsActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip);
intent.putExtra(TipActivity.EXTRA_VENUE_CLICKABLE, false);
startActivityForResult(intent, ACTIVITY_TIP);
}
});
setTitle(getString(R.string.venue_tips_activity_title, mStateHolder.getVenue().getName()));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) {
if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) {
Tip tip = (Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED);
Todo todo = data.hasExtra(TipActivity.EXTRA_TODO_RETURNED) ?
(Todo)data.getParcelableExtra(TipActivity.EXTRA_TODO_RETURNED) : null;
updateTip(tip, todo);
}
}
}
private void updateTip(Tip tip, Todo todo) {
mStateHolder.updateTip(tip, todo);
mListAdapter.notifyDataSetInvalidated();
prepareResultIntent();
}
private void prepareResultIntent() {
Intent intent = new Intent();
intent.putExtra(INTENT_EXTRA_RETURN_VENUE, mStateHolder.getVenue());
mStateHolder.setPreparedResult(intent);
setPreparedResultIntent();
}
private void setPreparedResultIntent() {
if (mStateHolder.getPreparedResult() != null) {
setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult());
}
}
private static class StateHolder {
private Venue mVenue;
private Group<Tip> mTipsFriends;
private Group<Tip> mTipsAll;
private Intent mPreparedResult;
public StateHolder() {
mPreparedResult = null;
mTipsFriends = new Group<Tip>();
mTipsAll = new Group<Tip>();
}
public Venue getVenue() {
return mVenue;
}
public void setVenue(Venue venue) {
mVenue = venue;
mTipsFriends.clear();
mTipsAll.clear();
for (Tip tip : venue.getTips()) {
if (UserUtils.isFriend(tip.getUser())) {
mTipsFriends.add(tip);
} else {
mTipsAll.add(tip);
}
}
}
public Group<Tip> getTipsFriends() {
return mTipsFriends;
}
public Group<Tip> getTipsAll() {
return mTipsAll;
}
public Intent getPreparedResult() {
return mPreparedResult;
}
public void setPreparedResult(Intent intent) {
mPreparedResult = intent;
}
public void updateTip(Tip tip, Todo todo) {
// Changes to a tip status can produce or remove a to-do for its
// parent venue.
VenueUtils.handleTipChange(mVenue, tip, todo);
// Also update the tip from wherever it appears in the separated
// list adapter sections.
updateTip(tip, mTipsFriends);
updateTip(tip, mTipsAll);
}
private void updateTip(Tip tip, List<Tip> target) {
for (Tip it : target) {
if (it.getId().equals(tip.getId())) {
it.setStatus(tip.getStatus());
break;
}
}
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquared.app.LoadableListActivityWithViewAndHeader;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import com.joelapenna.foursquared.widget.SegmentedButton;
import com.joelapenna.foursquared.widget.SegmentedButton.OnClickListenerSegmentedButton;
import com.joelapenna.foursquared.widget.TipsListAdapter;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import java.util.Observable;
import java.util.Observer;
/**
* Shows a tips of a user, but not the logged-in user. This is pretty much a copy-paste
* of TipsActivity, but there are enough small differences to put it in its own activity.
* The direction of this activity is unknown too, so separating i here.
*
* @date September 23, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserDetailsTipsActivity extends LoadableListActivityWithViewAndHeader {
static final String TAG = "UserDetailsTipsActivity";
static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_USER_ID = Foursquared.PACKAGE_NAME
+ ".UserDetailsTipsActivity.INTENT_EXTRA_USER_ID";
public static final String INTENT_EXTRA_USER_NAME = Foursquared.PACKAGE_NAME
+ ".UserDetailsTipsActivity.INTENT_EXTRA_USER_NAME";
private static final int ACTIVITY_TIP = 500;
private StateHolder mStateHolder;
private TipsListAdapter mListAdapter;
private SearchLocationObserver mSearchLocationObserver = new SearchLocationObserver();
private View mLayoutEmpty;
private static final int MENU_REFRESH = 0;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
if (getIntent().hasExtra(INTENT_EXTRA_USER_ID) && getIntent().hasExtra(INTENT_EXTRA_USER_NAME)) {
mStateHolder = new StateHolder(
getIntent().getStringExtra(INTENT_EXTRA_USER_ID),
getIntent().getStringExtra(INTENT_EXTRA_USER_NAME));
mStateHolder.setRecentOnly(true);
} else {
Log.e(TAG, TAG + " requires user ID and name in intent extras.");
finish();
return;
}
}
ensureUi();
// Friend tips is shown first by default so auto-fetch it if necessary.
if (!mStateHolder.getRanOnceTipsRecent()) {
mStateHolder.startTaskTips(this, true);
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(mSearchLocationObserver);
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates(mSearchLocationObserver);
if (isFinishing()) {
mStateHolder.cancelTasks();
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void ensureUi() {
LayoutInflater inflater = LayoutInflater.from(this);
mLayoutEmpty = inflater.inflate(R.layout.tips_activity_empty, null);
mLayoutEmpty.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
mListAdapter = new TipsListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager(), R.layout.tip_venue_list_item);
if (mStateHolder.getRecentOnly()) {
mListAdapter.setGroup(mStateHolder.getTipsRecent());
if (mStateHolder.getTipsRecent().size() == 0) {
if (mStateHolder.getRanOnceTipsRecent()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
} else {
mListAdapter.setGroup(mStateHolder.getTipsPopular());
if (mStateHolder.getTipsPopular().size() == 0) {
if (mStateHolder.getRanOnceTipsPopular()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
}
}
}
SegmentedButton buttons = getHeaderButton();
buttons.clearButtons();
buttons.addButtons(
getString(R.string.user_details_tips_activity_btn_recent),
getString(R.string.user_details_tips_activity_btn_popular));
if (mStateHolder.mRecentOnly) {
buttons.setPushedButtonIndex(0);
} else {
buttons.setPushedButtonIndex(1);
}
buttons.setOnClickListener(new OnClickListenerSegmentedButton() {
@Override
public void onClick(int index) {
if (index == 0) {
mStateHolder.setRecentOnly(true);
mListAdapter.setGroup(mStateHolder.getTipsRecent());
if (mStateHolder.getTipsRecent().size() < 1) {
if (mStateHolder.getRanOnceTipsRecent()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(UserDetailsTipsActivity.this, true);
}
}
} else {
mStateHolder.setRecentOnly(false);
mListAdapter.setGroup(mStateHolder.getTipsPopular());
if (mStateHolder.getTipsPopular().size() < 1) {
if (mStateHolder.getRanOnceTipsPopular()) {
setEmptyView(mLayoutEmpty);
} else {
setLoadingView();
mStateHolder.startTaskTips(UserDetailsTipsActivity.this, false);
}
}
}
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
});
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(false);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Tip tip = (Tip) parent.getAdapter().getItem(position);
Intent intent = new Intent(UserDetailsTipsActivity.this, TipActivity.class);
intent.putExtra(TipActivity.EXTRA_TIP_PARCEL, tip);
startActivityForResult(intent, ACTIVITY_TIP);
}
});
if (mStateHolder.getIsRunningTaskTipsRecent() ||
mStateHolder.getIsRunningTaskTipsPopular()) {
setProgressBarIndeterminateVisibility(true);
} else {
setProgressBarIndeterminateVisibility(false);
}
setTitle(getString(R.string.user_details_tips_activity_title, mStateHolder.getUsername()));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_REFRESH, Menu.NONE, R.string.refresh)
.setIcon(R.drawable.ic_menu_refresh);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_REFRESH:
mStateHolder.startTaskTips(this, mStateHolder.getRecentOnly());
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// We don't care about the returned to-do (if any) since we're not bound
// to a venue in this activity for update. We just update the status member
// of the target tip.
if (requestCode == ACTIVITY_TIP && resultCode == Activity.RESULT_OK) {
if (data.hasExtra(TipActivity.EXTRA_TIP_RETURNED)) {
Log.i(TAG, "onActivityResult(), return tip intent extra found, processing.");
updateTip((Tip)data.getParcelableExtra(TipActivity.EXTRA_TIP_RETURNED));
} else {
Log.i(TAG, "onActivityResult(), no return tip intent extra found.");
}
}
}
private void updateTip(Tip tip) {
mStateHolder.updateTip(tip);
mListAdapter.notifyDataSetInvalidated();
}
private void onStartTaskTips() {
if (mListAdapter != null) {
if (mStateHolder.getRecentOnly()) {
mStateHolder.setIsRunningTaskTipsRecent(true);
mListAdapter.setGroup(mStateHolder.getTipsRecent());
} else {
mStateHolder.setIsRunningTaskTipsPopular(true);
mListAdapter.setGroup(mStateHolder.getTipsPopular());
}
mListAdapter.notifyDataSetChanged();
}
setProgressBarIndeterminateVisibility(true);
setLoadingView();
}
private void onTaskTipsComplete(Group<Tip> group, boolean recentOnly, Exception ex) {
SegmentedButton buttons = getHeaderButton();
boolean update = false;
if (group != null) {
if (recentOnly) {
mStateHolder.setTipsRecent(group);
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsRecent());
update = true;
}
} else {
mStateHolder.setTipsPopular(group);
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsPopular());
update = true;
}
}
}
else {
if (recentOnly) {
mStateHolder.setTipsRecent(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 0) {
mListAdapter.setGroup(mStateHolder.getTipsRecent());
update = true;
}
} else {
mStateHolder.setTipsPopular(new Group<Tip>());
if (buttons.getSelectedButtonIndex() == 1) {
mListAdapter.setGroup(mStateHolder.getTipsPopular());
update = true;
}
}
NotificationsUtil.ToastReasonForFailure(this, ex);
}
if (recentOnly) {
mStateHolder.setIsRunningTaskTipsRecent(false);
mStateHolder.setRanOnceTipsRecent(true);
if (mStateHolder.getTipsRecent().size() == 0 &&
buttons.getSelectedButtonIndex() == 0) {
setEmptyView(mLayoutEmpty);
}
} else {
mStateHolder.setIsRunningTaskTipsPopular(false);
mStateHolder.setRanOnceTipsPopular(true);
if (mStateHolder.getTipsPopular().size() == 0 &&
buttons.getSelectedButtonIndex() == 1) {
setEmptyView(mLayoutEmpty);
}
}
if (update) {
mListAdapter.notifyDataSetChanged();
getListView().setSelection(0);
}
if (!mStateHolder.getIsRunningTaskTipsRecent() &&
!mStateHolder.getIsRunningTaskTipsPopular()) {
setProgressBarIndeterminateVisibility(false);
}
}
private static class TaskTips extends AsyncTask<Void, Void, Group<Tip>> {
private String mUserId;
private UserDetailsTipsActivity mActivity;
private boolean mRecentOnly;
private Exception mReason;
public TaskTips(UserDetailsTipsActivity activity, String userId, boolean recentOnly) {
mActivity = activity;
mUserId = userId;
mRecentOnly = recentOnly;
}
@Override
protected void onPreExecute() {
mActivity.onStartTaskTips();
}
@Override
protected Group<Tip> doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
Location loc = foursquared.getLastKnownLocation();
if (loc == null) {
try { Thread.sleep(3000); } catch (InterruptedException ex) {}
loc = foursquared.getLastKnownLocation();
if (loc == null) {
throw new FoursquareException("Your location could not be determined!");
}
}
return foursquare.tips(
LocationUtils.createFoursquareLocation(loc),
mUserId,
"nearby",
mRecentOnly ? "recent" : "popular",
30);
} catch (Exception e) {
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Tip> tips) {
if (mActivity != null) {
mActivity.onTaskTipsComplete(tips, mRecentOnly, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onTaskTipsComplete(null, mRecentOnly, mReason);
}
}
public void setActivity(UserDetailsTipsActivity activity) {
mActivity = activity;
}
}
private static class StateHolder {
private String mUserId;
private String mUsername;
private Group<Tip> mTipsRecent;
private Group<Tip> mTipsPopular;
private TaskTips mTaskTipsRecent;
private TaskTips mTaskTipsPopular;
private boolean mIsRunningTaskTipsRecent;
private boolean mIsRunningTaskTipsPopular;
private boolean mRecentOnly;
private boolean mRanOnceTipsRecent;
private boolean mRanOnceTipsPopular;
public StateHolder(String userId, String username) {
mUserId = userId;
mUsername = username;
mIsRunningTaskTipsRecent = false;
mIsRunningTaskTipsPopular = false;
mRanOnceTipsRecent = false;
mRanOnceTipsPopular = false;
mTipsRecent = new Group<Tip>();
mTipsPopular = new Group<Tip>();
mRecentOnly = true;
}
public String getUsername() {
return mUsername;
}
public Group<Tip> getTipsRecent() {
return mTipsRecent;
}
public void setTipsRecent(Group<Tip> tipsRecent) {
mTipsRecent = tipsRecent;
}
public Group<Tip> getTipsPopular() {
return mTipsPopular;
}
public void setTipsPopular(Group<Tip> tipsPopular) {
mTipsPopular = tipsPopular;
}
public void startTaskTips(UserDetailsTipsActivity activity,
boolean recentOnly) {
if (recentOnly) {
if (mIsRunningTaskTipsRecent) {
return;
}
mIsRunningTaskTipsRecent = true;
mTaskTipsRecent = new TaskTips(activity, mUserId, recentOnly);
mTaskTipsRecent.execute();
} else {
if (mIsRunningTaskTipsPopular) {
return;
}
mIsRunningTaskTipsPopular = true;
mTaskTipsPopular = new TaskTips(activity, mUserId, recentOnly);
mTaskTipsPopular.execute();
}
}
public void setActivity(UserDetailsTipsActivity activity) {
if (mTaskTipsRecent != null) {
mTaskTipsRecent.setActivity(activity);
}
if (mTaskTipsPopular != null) {
mTaskTipsPopular.setActivity(activity);
}
}
public boolean getIsRunningTaskTipsRecent() {
return mIsRunningTaskTipsRecent;
}
public void setIsRunningTaskTipsRecent(boolean isRunning) {
mIsRunningTaskTipsRecent = isRunning;
}
public boolean getIsRunningTaskTipsPopular() {
return mIsRunningTaskTipsPopular;
}
public void setIsRunningTaskTipsPopular(boolean isRunning) {
mIsRunningTaskTipsPopular = isRunning;
}
public void cancelTasks() {
if (mTaskTipsRecent != null) {
mTaskTipsRecent.setActivity(null);
mTaskTipsRecent.cancel(true);
}
if (mTaskTipsPopular != null) {
mTaskTipsPopular.setActivity(null);
mTaskTipsPopular.cancel(true);
}
}
public boolean getRecentOnly() {
return mRecentOnly;
}
public void setRecentOnly(boolean recentOnly) {
mRecentOnly = recentOnly;
}
public boolean getRanOnceTipsRecent() {
return mRanOnceTipsRecent;
}
public void setRanOnceTipsRecent(boolean ranOnce) {
mRanOnceTipsRecent = ranOnce;
}
public boolean getRanOnceTipsPopular() {
return mRanOnceTipsPopular;
}
public void setRanOnceTipsPopular(boolean ranOnce) {
mRanOnceTipsPopular = ranOnce;
}
public void updateTip(Tip tip) {
updateTipFromArray(tip, mTipsRecent);
updateTipFromArray(tip, mTipsPopular);
}
private void updateTipFromArray(Tip tip, Group<Tip> target) {
for (Tip it : target) {
if (it.getId().equals(tip.getId())) {
it.setStatus(tip.getStatus());
break;
}
}
}
}
private class SearchLocationObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
}
}
}
| Java |
/**
* Copyright 2008 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.preferences.Preferences;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.preference.Preference.OnPreferenceChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -added notifications settings (May 21, 2010).
* -removed user update, moved to NotificationSettingsActivity (June 2, 2010)
*/
public class PreferenceActivity extends android.preference.PreferenceActivity {
private static final String TAG = "PreferenceActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final int DIALOG_TOS_PRIVACY = 1;
private static final int DIALOG_PROFILE_SETTINGS = 2;
private static final String URL_TOS = "http://foursquare.com/legal/terms";
private static final String URL_PRIVACY = "http://foursquare.com/legal/privacy";
private SharedPreferences mPrefs;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
addPreferencesFromResource(R.xml.preferences);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Preference advanceSettingsPreference = getPreferenceScreen().findPreference(
Preferences.PREFERENCE_ADVANCED_SETTINGS);
advanceSettingsPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
((Foursquared) getApplication()).requestUpdateUser();
return false;
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (DEBUG) Log.d(TAG, "onPreferenceTreeClick");
String key = preference.getKey();
if (Preferences.PREFERENCE_LOGOUT.equals(key)) {
mPrefs.edit().clear().commit();
// TODO: If we re-implement oAuth, we'll have to call
// clearAllCrendentials here.
((Foursquared) getApplication()).getFoursquare().setCredentials(null, null);
Intent intent = new Intent(this, LoginActivity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_CLEAR_TOP);
sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_OUT));
} else if (Preferences.PREFERENCE_ADVANCED_SETTINGS.equals(key)) {
startActivity(new Intent( //
Intent.ACTION_VIEW, Uri.parse(Foursquare.FOURSQUARE_PREFERENCES)));
} else if (Preferences.PREFERENCE_HELP.equals(key)) {
Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra(WebViewActivity.INTENT_EXTRA_URL, "http://foursquare.com/help/android");
startActivity(intent);
} else if (Preferences.PREFERENCE_SEND_FEEDBACK.equals(key)) {
startActivity(new Intent(this, SendLogActivity.class));
} else if (Preferences.PREFERENCE_FRIEND_ADD.equals(key)) {
startActivity(new Intent(this, AddFriendsActivity.class));
} else if (Preferences.PREFERENCE_FRIEND_REQUESTS.equals(key)) {
startActivity(new Intent(this, FriendRequestsActivity.class));
} else if (Preferences.PREFERENCE_CHANGELOG.equals(key)) {
startActivity(new Intent(this, ChangelogActivity.class));
} else if (Preferences.PREFERENCE_PINGS.equals(key)) {
startActivity(new Intent(this, PingsSettingsActivity.class));
} else if (Preferences.PREFERENCE_TOS_PRIVACY.equals(key)) {
showDialog(DIALOG_TOS_PRIVACY);
} else if (Preferences.PREFERENCE_PROFILE_SETTINGS.equals(key)) {
showDialog(DIALOG_PROFILE_SETTINGS);
}
return true;
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_TOS_PRIVACY:
ArrayAdapter<String> adapterTos = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
adapterTos.add(getResources().getString(R.string.preference_activity_tos));
adapterTos.add(getResources().getString(R.string.preference_activity_privacy));
AlertDialog dlgInfo = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.preference_activity_tos_privacy_dlg_title))
.setAdapter(adapterTos, new OnClickListener() {
@Override
public void onClick(DialogInterface dlg, int pos) {
Intent intent = new Intent(PreferenceActivity.this, WebViewActivity.class);
switch (pos) {
case 0:
intent.putExtra(WebViewActivity.INTENT_EXTRA_URL, URL_TOS);
break;
case 1:
intent.putExtra(WebViewActivity.INTENT_EXTRA_URL, URL_PRIVACY);
break;
default:
return;
}
startActivity(intent);
}
})
.create();
return dlgInfo;
case DIALOG_PROFILE_SETTINGS:
String userId = ((Foursquared) getApplication()).getUserId();
String userName = ((Foursquared) getApplication()).getUserName();
String userEmail = ((Foursquared) getApplication()).getUserEmail();
LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.settings_user_info,
(ViewGroup) findViewById(R.id.settings_user_info_layout_root));
TextView tvUserId = (TextView)layout.findViewById(R.id.settings_user_info_label_user_id);
TextView tvUserName = (TextView)layout.findViewById(R.id.settings_user_info_label_user_name);
TextView tvUserEmail = (TextView)layout.findViewById(R.id.settings_user_info_label_user_email);
tvUserId.setText(userId);
tvUserName.setText(userName);
tvUserEmail.setText(userEmail);
AlertDialog dlgProfileSettings = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.preference_activity_profile_settings_dlg_title))
.setView(layout)
.create();
return dlgProfileSettings;
}
return null;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Stats;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquare.util.VenueUtils;
import com.joelapenna.foursquared.maps.CrashFixMyLocationOverlay;
import com.joelapenna.foursquared.maps.VenueItemizedOverlay;
import com.joelapenna.foursquared.widget.MapCalloutView;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class SearchVenuesMapActivity extends MapActivity {
public static final String TAG = "SearchVenuesMapActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private String mTappedVenueId;
private Observer mSearchResultsObserver;
private MapCalloutView mCallout;
private MapView mMapView;
private MapController mMapController;
private VenueItemizedOverlay mVenueItemizedOverlay;
private MyLocationOverlay mMyLocationOverlay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_map_activity);
initMap();
mCallout = (MapCalloutView) findViewById(R.id.map_callout);
mCallout.setVisibility(View.GONE);
mCallout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(SearchVenuesMapActivity.this, VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_ID, mTappedVenueId);
startActivity(intent);
}
});
mSearchResultsObserver = new Observer() {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Observed search results change.");
clearMap();
loadSearchResults(SearchVenuesActivity.searchResultsObservable.getSearchResults());
recenterMap();
}
};
}
@Override
public void onResume() {
super.onResume();
if (DEBUG) Log.d(TAG, "onResume()");
mMyLocationOverlay.enableMyLocation();
// mMyLocationOverlay.enableCompass(); // Disabled due to a sdk 1.5 emulator bug
clearMap();
loadSearchResults(SearchVenuesActivity.searchResultsObservable.getSearchResults());
recenterMap();
SearchVenuesActivity.searchResultsObservable.addObserver(mSearchResultsObserver);
}
@Override
public void onPause() {
super.onPause();
if (DEBUG) Log.d(TAG, "onPause()");
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
SearchVenuesActivity.searchResultsObservable.deleteObserver(mSearchResultsObserver);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
private void initMap() {
mMapView = (MapView)findViewById(R.id.mapView);
mMapView.setBuiltInZoomControls(true);
mMapController = mMapView.getController();
mMyLocationOverlay = new CrashFixMyLocationOverlay(this, mMapView);
mMapView.getOverlays().add(mMyLocationOverlay);
mMyLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
if (DEBUG) Log.d(TAG, "runOnFirstFix()");
mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
mMapView.getController().setZoom(16);
}
});
}
private void loadSearchResults(Group<Group<Venue>> searchResults) {
if (searchResults == null) {
if (DEBUG) Log.d(TAG, "no search results. Not loading.");
return;
}
if (DEBUG) Log.d(TAG, "Loading search results");
// Put our location on the map.
mMapView.getOverlays().add(mMyLocationOverlay);
Group<Venue> mappableVenues = new Group<Venue>();
mappableVenues.setType("Mappable Venues");
// For each group of venues.
final int groupCount = searchResults.size();
for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
Group<Venue> group = searchResults.get(groupIndex);
// For each venue group
final int venueCount = group.size();
for (int venueIndex = 0; venueIndex < venueCount; venueIndex++) {
Venue venue = group.get(venueIndex);
if (VenueUtils.hasValidLocation(venue)) {
mappableVenues.add(venue);
}
}
}
// Construct the venues overlay and attach it if we have a mappable set of venues.
if (mappableVenues.size() > 0) {
mVenueItemizedOverlay = new VenueItemizedOverlayWithButton( //
this.getResources().getDrawable(R.drawable.map_marker_blue), //
this.getResources().getDrawable(R.drawable.map_marker_blue_muted));
mVenueItemizedOverlay.setGroup(mappableVenues);
mMapView.getOverlays().add(mVenueItemizedOverlay);
}
}
private void clearMap() {
if (DEBUG) Log.d(TAG, "clearMap()");
mMapView.getOverlays().clear();
mMapView.postInvalidate();
}
private void recenterMap() {
if (DEBUG) Log.d(TAG, "Recentering map.");
GeoPoint center = mMyLocationOverlay.getMyLocation();
// if we have venues in a search result, focus on those.
if (mVenueItemizedOverlay != null && mVenueItemizedOverlay.size() > 0) {
if (DEBUG) Log.d(TAG, "Centering on venues: "
+ String.valueOf(mVenueItemizedOverlay.getLatSpanE6()) + " "
+ String.valueOf(mVenueItemizedOverlay.getLonSpanE6()));
mMapController.setCenter(mVenueItemizedOverlay.getCenter());
mMapController.zoomToSpan(mVenueItemizedOverlay.getLatSpanE6(), mVenueItemizedOverlay
.getLonSpanE6());
} else if (center != null
&& SearchVenuesActivity.searchResultsObservable.getQuery() == SearchVenuesActivity.QUERY_NEARBY) {
if (DEBUG) Log.d(TAG, "recenterMap via MyLocation as we are doing a nearby search");
mMapController.animateTo(center);
mMapController.zoomToSpan(center.getLatitudeE6(), center.getLongitudeE6());
} else if (center != null) {
if (DEBUG) Log.d(TAG, "Fallback, recenterMap via MyLocation overlay");
mMapController.animateTo(center);
mMapController.setZoom(16);
return;
}
}
private class VenueItemizedOverlayWithButton extends VenueItemizedOverlay {
public static final String TAG = "VenueItemizedOverlayWithButton";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Drawable mBeenThereMarker;
public VenueItemizedOverlayWithButton(Drawable defaultMarker, Drawable beenThereMarker) {
super(defaultMarker);
mBeenThereMarker = boundCenterBottom(beenThereMarker);
}
@Override
public OverlayItem createItem(int i) {
VenueOverlayItem item = (VenueOverlayItem)super.createItem(i);
Stats stats = item.getVenue().getStats();
if (stats != null && stats.getBeenhere() != null && stats.getBeenhere().me()) {
if (DEBUG) Log.d(TAG, "using the beenThereMarker for: " + item.getVenue());
item.setMarker(mBeenThereMarker);
}
return item;
}
@Override
public boolean onTap(GeoPoint p, MapView mapView) {
if (DEBUG) Log.d(TAG, "onTap: " + this + " " + p + " " + mapView);
mCallout.setVisibility(View.GONE);
return super.onTap(p, mapView);
}
@Override
protected boolean onTap(int i) {
if (DEBUG) Log.d(TAG, "onTap: " + this + " " + i);
VenueOverlayItem item = (VenueOverlayItem)getItem(i);
mTappedVenueId = item.getVenue().getId();
mCallout.setTitle(item.getVenue().getName());
mCallout.setMessage(item.getVenue().getAddress());
mCallout.setVisibility(View.VISIBLE);
return true;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
/**
* Acts as an interface to the TabSpec class for setting the content view.
* The level 3 SDK doesn't support setting a View for the content sections
* of the tab, so we can only use the big native tab style. The level 4
* SDK and up support specifying a custom view for the tab.
*
* @date March 9, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class TabsUtil4 {
private TabsUtil4() {
}
public static void setTabIndicator(TabSpec spec, View view) {
spec.setIndicator(view);
}
public static int getTabCount(TabHost tabHost) {
return tabHost.getTabWidget().getTabCount();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.FoursquaredSettings;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.Observable;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.zip.GZIPInputStream;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
class RemoteResourceFetcher extends Observable {
public static final String TAG = "RemoteResourceFetcher";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
private DiskCache mResourceCache;
private ExecutorService mExecutor;
private HttpClient mHttpClient;
private ConcurrentHashMap<Request, Callable<Request>> mActiveRequestsMap = new ConcurrentHashMap<Request, Callable<Request>>();
public RemoteResourceFetcher(DiskCache cache) {
mResourceCache = cache;
mHttpClient = createHttpClient();
mExecutor = Executors.newCachedThreadPool();
}
@Override
public void notifyObservers(Object data) {
setChanged();
super.notifyObservers(data);
}
public Future<Request> fetch(Uri uri, String hash) {
Request request = new Request(uri, hash);
synchronized (mActiveRequestsMap) {
Callable<Request> fetcher = newRequestCall(request);
if (mActiveRequestsMap.putIfAbsent(request, fetcher) == null) {
if (DEBUG) Log.d(TAG, "issuing new request for: " + uri);
return mExecutor.submit(fetcher);
} else {
if (DEBUG) Log.d(TAG, "Already have a pending request for: " + uri);
}
}
return null;
}
public void shutdown() {
mExecutor.shutdownNow();
}
private Callable<Request> newRequestCall(final Request request) {
return new Callable<Request>() {
public Request call() {
try {
if (DEBUG) Log.d(TAG, "Requesting: " + request.uri);
HttpGet httpGet = new HttpGet(request.uri.toString());
httpGet.addHeader("Accept-Encoding", "gzip");
HttpResponse response = mHttpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream is = getUngzippedContent(entity);
mResourceCache.store(request.hash, is);
if (DEBUG) Log.d(TAG, "Request successful: " + request.uri);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "IOException", e);
} finally {
if (DEBUG) Log.d(TAG, "Request finished: " + request.uri);
mActiveRequestsMap.remove(request);
notifyObservers(request.uri);
}
return request;
}
};
}
/**
* Gets the input stream from a response entity. If the entity is gzipped then this will get a
* stream over the uncompressed data.
*
* @param entity the entity whose content should be read
* @return the input stream to read from
* @throws IOException
*/
public static InputStream getUngzippedContent(HttpEntity entity) throws IOException {
InputStream responseStream = entity.getContent();
if (responseStream == null) {
return responseStream;
}
Header header = entity.getContentEncoding();
if (header == null) {
return responseStream;
}
String contentEncoding = header.getValue();
if (contentEncoding == null) {
return responseStream;
}
if (contentEncoding.contains("gzip")) {
responseStream = new GZIPInputStream(responseStream);
}
return responseStream;
}
/**
* Create a thread-safe client. This client does not do redirecting, to allow us to capture
* correct "error" codes.
*
* @return HttpClient
*/
public static final DefaultHttpClient createHttpClient() {
// Shamelessly cribbed from AndroidHttpClient
HttpParams params = new BasicHttpParams();
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
// Default connection and socket timeout of 10 seconds. Tweak to taste.
HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
HttpConnectionParams.setSoTimeout(params, 10 * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192);
// Sets up the http part of the service.
final SchemeRegistry supportedSchemes = new SchemeRegistry();
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
final SocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", sf, 80));
final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params,
supportedSchemes);
return new DefaultHttpClient(ccm, params);
}
private static class Request {
Uri uri;
String hash;
public Request(Uri requestUri, String requestHash) {
uri = requestUri;
hash = requestHash;
}
@Override
public int hashCode() {
return hash.hashCode();
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.text.TextUtils;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
/**
* @date September 2, 2010.
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TipUtils {
public static final String TIP_STATUS_TODO = "todo";
public static final String TIP_STATUS_DONE = "done";
public static boolean isTodo(Tip tip) {
if (tip != null) {
if (!TextUtils.isEmpty(tip.getStatus())) {
return tip.getStatus().equals(TIP_STATUS_TODO);
}
}
return false;
}
public static boolean isDone(Tip tip) {
if (tip != null) {
if (!TextUtils.isEmpty(tip.getStatus())) {
return tip.getStatus().equals(TIP_STATUS_DONE);
}
}
return false;
}
public static boolean areEqual(FoursquareType tipOrTodo1, FoursquareType tipOrTodo2) {
if (tipOrTodo1 instanceof Tip) {
if (tipOrTodo2 instanceof Todo) {
return false;
}
Tip tip1 = (Tip)tipOrTodo1;
Tip tip2 = (Tip)tipOrTodo2;
if (!tip1.getId().equals(tip2.getId())) {
return false;
}
if (!TextUtils.isEmpty(tip1.getStatus()) && !TextUtils.isEmpty(tip2.getStatus())) {
return tip1.getStatus().equals(tip2.getStatus());
} else if (TextUtils.isEmpty(tip1.getStatus()) && TextUtils.isEmpty(tip2.getStatus())) {
return true;
} else {
return false;
}
} else if (tipOrTodo1 instanceof Todo) {
if (tipOrTodo2 instanceof Tip) {
return false;
}
Todo todo1 = (Todo)tipOrTodo1;
Todo todo2 = (Todo)tipOrTodo2;
if (!todo1.getId().equals(todo2.getId())) {
return false;
}
if (todo1.getTip().getId().equals(todo2.getId())) {
return true;
}
}
return false;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.app.Activity;
import android.os.Build;
/**
* Acts as an interface to the contacts API which has changed between SDK 4 to
* 5.
*
* @date February 14, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public abstract class AddressBookUtils {
public abstract String getAllContactsPhoneNumbers(Activity activity);
public abstract String getAllContactsEmailAddresses(Activity activity);
public abstract AddressBookEmailBuilder getAllContactsEmailAddressesInfo(
Activity activity);
public static AddressBookUtils addressBookUtils() {
int sdk = new Integer(Build.VERSION.SDK).intValue();
if (sdk < 5) {
return new AddressBookUtils3and4();
} else {
return new AddressBookUtils5();
}
}
}
| Java |
// Copyright 2003-2009 Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland
// www.source-code.biz, www.inventec.ch/chdh
//
// This module is multi-licensed and may be used under the terms
// of any of the following licenses:
//
// EPL, Eclipse Public License, http://www.eclipse.org/legal
// LGPL, GNU Lesser General Public License, http://www.gnu.org/licenses/lgpl.html
// AL, Apache License, http://www.apache.org/licenses
// BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php
//
// Please contact the author if you need another license.
// This module is provided "as is", without warranties of any kind.
package com.joelapenna.foursquared.util;
/**
* A Base64 Encoder/Decoder.
* <p>
* This class is used to encode and decode data in Base64 format as described in
* RFC 1521.
* <p>
* Home page: <a href="http://www.source-code.biz">www.source-code.biz</a><br>
* Author: Christian d'Heureuse, Inventec Informatik AG, Zurich, Switzerland<br>
* Multi-licensed: EPL/LGPL/AL/BSD.
* <p>
* Version history:<br>
* 2003-07-22 Christian d'Heureuse (chdh): Module created.<br>
* 2005-08-11 chdh: Lincense changed from GPL to LGPL.<br>
* 2006-11-21 chdh:<br>
* Method encode(String) renamed to encodeString(String).<br>
* Method decode(String) renamed to decodeString(String).<br>
* New method encode(byte[],int) added.<br>
* New method decode(String) added.<br>
* 2009-07-16: Additional licenses (EPL/AL) added.<br>
* 2009-09-16: Additional license (BSD) added.<br>
*/
public class Base64Coder {
// Mapping table from 6-bit nibbles to Base64 characters.
private static char[] map1 = new char[64];
static {
int i = 0;
for (char c = 'A'; c <= 'Z'; c++)
map1[i++] = c;
for (char c = 'a'; c <= 'z'; c++)
map1[i++] = c;
for (char c = '0'; c <= '9'; c++)
map1[i++] = c;
map1[i++] = '+';
map1[i++] = '/';
}
// Mapping table from Base64 characters to 6-bit nibbles.
private static byte[] map2 = new byte[128];
static {
for (int i = 0; i < map2.length; i++)
map2[i] = -1;
for (int i = 0; i < 64; i++)
map2[map1[i]] = (byte) i;
}
/**
* Encodes a string into Base64 format. No blanks or line breaks are
* inserted.
*
* @param s a String to be encoded.
* @return A String with the Base64 encoded data.
*/
public static String encodeString(String s) {
return new String(encode(s.getBytes()));
}
/**
* Encodes a byte array into Base64 format. No blanks or line breaks are
* inserted.
*
* @param in an array containing the data bytes to be encoded.
* @return A character array with the Base64 encoded data.
*/
public static char[] encode(byte[] in) {
return encode(in, in.length);
}
/**
* Encodes a byte array into Base64 format. No blanks or line breaks are
* inserted.
*
* @param in an array containing the data bytes to be encoded.
* @param iLen number of bytes to process in <code>in</code>.
* @return A character array with the Base64 encoded data.
*/
public static char[] encode(byte[] in, int iLen) {
int oDataLen = (iLen * 4 + 2) / 3; // output length without padding
int oLen = ((iLen + 2) / 3) * 4; // output length including padding
char[] out = new char[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++] & 0xff;
int i1 = ip < iLen ? in[ip++] & 0xff : 0;
int i2 = ip < iLen ? in[ip++] & 0xff : 0;
int o0 = i0 >>> 2;
int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
int o3 = i2 & 0x3F;
out[op++] = map1[o0];
out[op++] = map1[o1];
out[op] = op < oDataLen ? map1[o2] : '=';
op++;
out[op] = op < oDataLen ? map1[o3] : '=';
op++;
}
return out;
}
/**
* Decodes a string from Base64 format.
*
* @param s a Base64 String to be decoded.
* @return A String containing the decoded data.
* @throws IllegalArgumentException if the input is not valid Base64 encoded
* data.
*/
public static String decodeString(String s) {
return new String(decode(s));
}
/**
* Decodes a byte array from Base64 format.
*
* @param s a Base64 String to be decoded.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException if the input is not valid Base64 encoded
* data.
*/
public static byte[] decode(String s) {
return decode(s.toCharArray());
}
/**
* Decodes a byte array from Base64 format. No blanks or line breaks are
* allowed within the Base64 encoded data.
*
* @param in a character array containing the Base64 encoded data.
* @return An array containing the decoded data bytes.
* @throws IllegalArgumentException if the input is not valid Base64 encoded
* data.
*/
public static byte[] decode(char[] in) {
int iLen = in.length;
if (iLen % 4 != 0)
throw new IllegalArgumentException(
"Length of Base64 encoded input string is not a multiple of 4.");
while (iLen > 0 && in[iLen - 1] == '=')
iLen--;
int oLen = (iLen * 3) / 4;
byte[] out = new byte[oLen];
int ip = 0;
int op = 0;
while (ip < iLen) {
int i0 = in[ip++];
int i1 = in[ip++];
int i2 = ip < iLen ? in[ip++] : 'A';
int i3 = ip < iLen ? in[ip++] : 'A';
if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
throw new IllegalArgumentException("Illegal character in Base64 encoded data.");
int b0 = map2[i0];
int b1 = map2[i1];
int b2 = map2[i2];
int b3 = map2[i3];
if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
throw new IllegalArgumentException("Illegal character in Base64 encoded data.");
int o0 = (b0 << 2) | (b1 >>> 4);
int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2);
int o2 = ((b2 & 3) << 6) | b3;
out[op++] = (byte) o0;
if (op < oLen) out[op++] = (byte) o1;
if (op < oLen) out[op++] = (byte) o2;
}
return out;
}
// Dummy constructor.
private Base64Coder() {
}
} // end class Base64Coder
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class BaseDiskCache implements DiskCache {
private static final String TAG = "BaseDiskCache";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final String NOMEDIA = ".nomedia";
private static final int MIN_FILE_SIZE_IN_BYTES = 100;
private File mStorageDirectory;
BaseDiskCache(String dirPath, String name) {
// Lets make sure we can actually cache things!
File baseDirectory = new File(Environment.getExternalStorageDirectory(), dirPath);
File storageDirectory = new File(baseDirectory, name);
createDirectory(storageDirectory);
mStorageDirectory = storageDirectory;
// cleanup(); // Remove invalid files that may have shown up.
cleanupSimple();
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#exists(java.lang.String)
*/
@Override
public boolean exists(String key) {
return getFile(key).exists();
}
/**
* This is silly, but our content provider *has* to serve content: URIs as File/FileDescriptors
* using ContentProvider.openAssetFile, this is a limitation of the StreamLoader that is used by
* the WebView. So, we handle this by writing the file to disk, and returning a File pointer to
* it.
*
* @param guid
* @return
*/
public File getFile(String hash) {
return new File(mStorageDirectory.toString() + File.separator + hash);
}
public InputStream getInputStream(String hash) throws IOException {
return (InputStream)new FileInputStream(getFile(hash));
}
/*
* (non-Javadoc)
* @see com.joelapenna.everdroid.evernote.NoteResourceDataBodyCache#storeResource (com
* .evernote.edam.type.Resource)
*/
public void store(String key, InputStream is) {
if (DEBUG) Log.d(TAG, "store: " + key);
is = new BufferedInputStream(is);
try {
OutputStream os = new BufferedOutputStream(new FileOutputStream(getFile(key)));
byte[] b = new byte[2048];
int count;
int total = 0;
while ((count = is.read(b)) > 0) {
os.write(b, 0, count);
total += count;
}
os.close();
if (DEBUG) Log.d(TAG, "store complete: " + key);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "store failed to store: " + key, e);
return;
}
}
public void invalidate(String key) {
getFile(key).delete();
}
public void cleanup() {
// removes files that are too small to be valid. Cheap and cheater way to remove files that
// were corrupted during download.
String[] children = mStorageDirectory.list();
if (children != null) { // children will be null if hte directyr does not exist.
for (int i = 0; i < children.length; i++) {
File child = new File(mStorageDirectory, children[i]);
if (!child.equals(new File(mStorageDirectory, NOMEDIA))
&& child.length() <= MIN_FILE_SIZE_IN_BYTES) {
if (DEBUG) Log.d(TAG, "Deleting: " + child);
child.delete();
}
}
}
}
/**
* Temporary fix until we rework this disk cache. We delete the first 50 youngest files
* if we find the cache has more than 1000 images in it.
*/
public void cleanupSimple() {
final int maxNumFiles = 1000;
final int numFilesToDelete = 50;
String[] children = mStorageDirectory.list();
if (children != null) {
if (DEBUG) Log.d(TAG, "Found disk cache length to be: " + children.length);
if (children.length > maxNumFiles) {
if (DEBUG) Log.d(TAG, "Disk cache found to : " + children);
for (int i = children.length - 1, m = i - numFilesToDelete; i > m; i--) {
File child = new File(mStorageDirectory, children[i]);
if (DEBUG) Log.d(TAG, " deleting: " + child.getName());
child.delete();
}
}
}
}
public void clear() {
// Clear the whole cache. Coolness.
String[] children = mStorageDirectory.list();
if (children != null) { // children will be null if hte directyr does not exist.
for (int i = 0; i < children.length; i++) {
File child = new File(mStorageDirectory, children[i]);
if (!child.equals(new File(mStorageDirectory, NOMEDIA))) {
if (DEBUG) Log.d(TAG, "Deleting: " + child);
child.delete();
}
}
}
mStorageDirectory.delete();
}
private static final void createDirectory(File storageDirectory) {
if (!storageDirectory.exists()) {
Log.d(TAG, "Trying to create storageDirectory: "
+ String.valueOf(storageDirectory.mkdirs()));
Log.d(TAG, "Exists: " + storageDirectory + " "
+ String.valueOf(storageDirectory.exists()));
Log.d(TAG, "State: " + Environment.getExternalStorageState());
Log.d(TAG, "Isdir: " + storageDirectory + " "
+ String.valueOf(storageDirectory.isDirectory()));
Log.d(TAG, "Readable: " + storageDirectory + " "
+ String.valueOf(storageDirectory.canRead()));
Log.d(TAG, "Writable: " + storageDirectory + " "
+ String.valueOf(storageDirectory.canWrite()));
File tmp = storageDirectory.getParentFile();
Log.d(TAG, "Exists: " + tmp + " " + String.valueOf(tmp.exists()));
Log.d(TAG, "Isdir: " + tmp + " " + String.valueOf(tmp.isDirectory()));
Log.d(TAG, "Readable: " + tmp + " " + String.valueOf(tmp.canRead()));
Log.d(TAG, "Writable: " + tmp + " " + String.valueOf(tmp.canWrite()));
tmp = tmp.getParentFile();
Log.d(TAG, "Exists: " + tmp + " " + String.valueOf(tmp.exists()));
Log.d(TAG, "Isdir: " + tmp + " " + String.valueOf(tmp.isDirectory()));
Log.d(TAG, "Readable: " + tmp + " " + String.valueOf(tmp.canRead()));
Log.d(TAG, "Writable: " + tmp + " " + String.valueOf(tmp.canWrite()));
}
File nomediaFile = new File(storageDirectory, NOMEDIA);
if (!nomediaFile.exists()) {
try {
Log.d(TAG, "Created file: " + nomediaFile + " "
+ String.valueOf(nomediaFile.createNewFile()));
} catch (IOException e) {
Log.d(TAG, "Unable to create .nomedia file for some reason.", e);
throw new IllegalStateException("Unable to create nomedia file.");
}
}
// After we best-effort try to create the file-structure we need,
// lets make sure it worked.
if (!(storageDirectory.isDirectory() && nomediaFile.exists())) {
throw new RuntimeException("Unable to create storage directory and nomedia file.");
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import com.google.android.maps.GeoPoint;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;
/**
* @date June 30, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class GeoUtils {
/**
* To be used if you just want a one-shot best last location, iterates over
* all providers and returns the most accurate result.
*/
public static Location getBestLastGeolocation(Context context) {
LocationManager manager = (LocationManager)context.getSystemService(
Context.LOCATION_SERVICE);
List<String> providers = manager.getAllProviders();
Location bestLocation = null;
for (String it : providers) {
Location location = manager.getLastKnownLocation(it);
if (location != null) {
if (bestLocation == null ||
location.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = location;
}
}
}
return bestLocation;
}
public static GeoPoint locationToGeoPoint(Location location) {
if (location != null) {
GeoPoint pt = new GeoPoint(
(int)(location.getLatitude() * 1E6 + 0.5),
(int)(location.getLongitude() * 1E6 + 0.5));
return pt;
} else {
return null;
}
}
public static GeoPoint stringLocationToGeoPoint(String strlat, String strlon) {
try {
double lat = Double.parseDouble(strlat);
double lon = Double.parseDouble(strlon);
GeoPoint pt = new GeoPoint(
(int)(lat * 1E6 + 0.5),
(int)(lon * 1E6 + 0.5));
return pt;
} catch (Exception ex) {
return null;
}
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.os.Parcel;
import android.text.TextUtils;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.Venue;
/**
* @date September 16, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class VenueUtils {
public static void handleTipChange(Venue venue, Tip tip, Todo todo) {
// Update the tip in the tips group, if it exists.
updateTip(venue, tip);
// If it is a to-do, then make sure a to-do exists for it
// in the to-do group.
if (TipUtils.isTodo(tip)) {
addTodo(venue, tip, todo);
} else {
// If it is not a to-do, make sure it does not exist in the
// to-do group.
removeTodo(venue, tip);
}
}
private static void updateTip(Venue venue, Tip tip) {
if (venue.getTips() != null) {
for (Tip it : venue.getTips()) {
if (it.getId().equals(tip.getId())) {
it.setStatus(tip.getStatus());
break;
}
}
}
}
public static void addTodo(Venue venue, Tip tip, Todo todo) {
venue.setHasTodo(true);
if (venue.getTodos() == null) {
venue.setTodos(new Group<Todo>());
}
// If found a to-do linked to the tip ID, then overwrite to-do attributes
// with newer to-do object.
for (Todo it : venue.getTodos()) {
if (it.getTip().getId().equals(tip.getId())) {
it.setId(todo.getId());
it.setCreated(todo.getCreated());
return;
}
}
venue.getTodos().add(todo);
}
public static void addTip(Venue venue, Tip tip) {
if (venue.getTips() == null) {
venue.setTips(new Group<Tip>());
}
for (Tip it : venue.getTips()) {
if (it.getId().equals(tip.getId())) {
return;
}
}
venue.getTips().add(tip);
}
private static void removeTodo(Venue venue, Tip tip) {
for (Todo it : venue.getTodos()) {
if (it.getTip().getId().equals(tip.getId())) {
venue.getTodos().remove(it);
break;
}
}
if (venue.getTodos().size() > 0) {
venue.setHasTodo(true);
} else {
venue.setHasTodo(false);
}
}
public static void replaceTipsAndTodos(Venue venueTarget, Venue venueSource) {
if (venueTarget.getTips() == null) {
venueTarget.setTips(new Group<Tip>());
}
if (venueTarget.getTodos() == null) {
venueTarget.setTodos(new Group<Todo>());
}
if (venueSource.getTips() == null) {
venueSource.setTips(new Group<Tip>());
}
if (venueSource.getTodos() == null) {
venueSource.setTodos(new Group<Todo>());
}
venueTarget.getTips().clear();
venueTarget.getTips().addAll(venueSource.getTips());
venueTarget.getTodos().clear();
venueTarget.getTodos().addAll(venueSource.getTodos());
if (venueTarget.getTodos().size() > 0) {
venueTarget.setHasTodo(true);
} else {
venueTarget.setHasTodo(false);
}
}
public static boolean getSpecialHere(Venue venue) {
if (venue != null && venue.getSpecials() != null && venue.getSpecials().size() > 0) {
Venue specialVenue = venue.getSpecials().get(0).getVenue();
if (specialVenue == null || specialVenue.getId().equals(venue.getId())) {
return true;
}
}
return false;
}
/**
* Creates a copy of the passed venue. This should really be implemented
* as a copy constructor.
*/
public static Venue cloneVenue(Venue venue) {
Parcel p1 = Parcel.obtain();
Parcel p2 = Parcel.obtain();
byte[] bytes = null;
p1.writeValue(venue);
bytes = p1.marshall();
p2.unmarshall(bytes, 0, bytes.length);
p2.setDataPosition(0);
Venue venueNew = (Venue)p2.readValue(Venue.class.getClassLoader());
p1.recycle();
p2.recycle();
return venueNew;
}
public static String toStringVenueShare(Venue venue) {
StringBuilder sb = new StringBuilder();
sb.append(venue.getName()); sb.append("\n");
sb.append(StringFormatters.getVenueLocationFull(venue));
if (!TextUtils.isEmpty(venue.getPhone())) {
sb.append("\n");
sb.append(venue.getPhone());
}
return sb.toString();
}
/**
* Dumps some info about a venue. This can be moved into the Venue class.
*/
public static String toString(Venue venue) {
StringBuilder sb = new StringBuilder();
sb.append(venue.toString()); sb.append(":\n");
sb.append(" id: "); sb.append(venue.getId()); sb.append("\n");
sb.append(" name: "); sb.append(venue.getName()); sb.append("\n");
sb.append(" address: "); sb.append(venue.getAddress()); sb.append("\n");
sb.append(" cross: "); sb.append(venue.getCrossstreet()); sb.append("\n");
sb.append(" hastodo: "); sb.append(venue.getHasTodo()); sb.append("\n");
sb.append(" tips: "); sb.append(venue.getTips() == null ? "(null)" : venue.getTips().size()); sb.append("\n");
sb.append(" todos: "); sb.append(venue.getTodos() == null ? "(null)" : venue.getTodos().size()); sb.append("\n");
sb.append(" specials: "); sb.append(venue.getSpecials() == null ? "(null)" : venue.getSpecials().size()); sb.append("\n");
return sb.toString();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.FoursquaredSettings;
import android.net.Uri;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Observable;
import java.util.Observer;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class RemoteResourceManager extends Observable {
private static final String TAG = "RemoteResourceManager";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private DiskCache mDiskCache;
private RemoteResourceFetcher mRemoteResourceFetcher;
private FetcherObserver mFetcherObserver = new FetcherObserver();
public RemoteResourceManager(String cacheName) {
this(new BaseDiskCache("foursquare", cacheName));
}
public RemoteResourceManager(DiskCache cache) {
mDiskCache = cache;
mRemoteResourceFetcher = new RemoteResourceFetcher(mDiskCache);
mRemoteResourceFetcher.addObserver(mFetcherObserver);
}
public boolean exists(Uri uri) {
return mDiskCache.exists(Uri.encode(uri.toString()));
}
/**
* If IOException is thrown, we don't have the resource available.
*/
public File getFile(Uri uri) {
if (DEBUG) Log.d(TAG, "getInputStream(): " + uri);
return mDiskCache.getFile(Uri.encode(uri.toString()));
}
/**
* If IOException is thrown, we don't have the resource available.
*/
public InputStream getInputStream(Uri uri) throws IOException {
if (DEBUG) Log.d(TAG, "getInputStream(): " + uri);
return mDiskCache.getInputStream(Uri.encode(uri.toString()));
}
/**
* Request a resource be downloaded. Useful to call after a IOException from getInputStream.
*/
public void request(Uri uri) {
if (DEBUG) Log.d(TAG, "request(): " + uri);
mRemoteResourceFetcher.fetch(uri, Uri.encode(uri.toString()));
}
/**
* Explicitly expire an individual item.
*/
public void invalidate(Uri uri) {
mDiskCache.invalidate(Uri.encode(uri.toString()));
}
public void shutdown() {
mRemoteResourceFetcher.shutdown();
mDiskCache.cleanup();
}
public void clear() {
mRemoteResourceFetcher.shutdown();
mDiskCache.clear();
}
public static abstract class ResourceRequestObserver implements Observer {
private Uri mRequestUri;
abstract public void requestReceived(Observable observable, Uri uri);
public ResourceRequestObserver(Uri requestUri) {
mRequestUri = requestUri;
}
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Recieved update: " + data);
Uri dataUri = (Uri)data;
if (dataUri == mRequestUri) {
if (DEBUG) Log.d(TAG, "requestReceived: " + dataUri);
requestReceived(observable, dataUri);
}
}
}
/**
* Relay the observed download to this controlling class.
*/
private class FetcherObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
setChanged();
notifyObservers(data);
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.R;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;
/**
* Acts as an interface to the TabSpec class for setting the content view. The
* level 3 SDK doesn't support setting a View for the content sections of the
* tab, so we can only use the big native tab style. The level 4 SDK and up
* support specifying a custom view for the tab.
*
* @date March 9, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public abstract class TabsUtil {
private static void setTabIndicator(TabSpec spec, String title, Drawable drawable, View view) {
int sdk = new Integer(Build.VERSION.SDK).intValue();
if (sdk < 4) {
TabsUtil3.setTabIndicator(spec, title, drawable);
} else {
TabsUtil4.setTabIndicator(spec, view);
}
}
public static void addTab(TabHost host, String title, int drawable, int index, int layout) {
TabHost.TabSpec spec = host.newTabSpec("tab" + index);
spec.setContent(layout);
View view = prepareTabView(host.getContext(), title, drawable);
TabsUtil.setTabIndicator(spec, title, host.getContext().getResources().getDrawable(drawable), view);
host.addTab(spec);
}
public static void addTab(TabHost host, String title, int drawable, int index, Intent intent) {
TabHost.TabSpec spec = host.newTabSpec("tab" + index);
spec.setContent(intent);
View view = prepareTabView(host.getContext(), title, drawable);
TabsUtil.setTabIndicator(spec, title, host.getContext().getResources().getDrawable(drawable), view);
host.addTab(spec);
}
private static View prepareTabView(Context context, String text, int drawable) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_main_nav, null);
TextView tv = (TextView) view.findViewById(R.id.tvTitle);
tv.setText(text);
ImageView iv = (ImageView) view.findViewById(R.id.ivIcon);
iv.setImageResource(drawable);
return view;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.media.ExifInterface;
import android.text.TextUtils;
/**
* @date July 24, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class ExifUtils
{
private ExifUtils() {
}
public static int getExifRotation(String imgPath) {
try {
ExifInterface exif = new ExifInterface(imgPath);
String rotationAmount = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
if (!TextUtils.isEmpty(rotationAmount)) {
int rotationParam = Integer.parseInt(rotationAmount);
switch (rotationParam) {
case ExifInterface.ORIENTATION_NORMAL:
return 0;
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
default:
return 0;
}
} else {
return 0;
}
} catch (Exception ex) {
return 0;
}
}
} | Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class NullDiskCache implements DiskCache {
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#exists(java.lang.String)
*/
@Override
public boolean exists(String key) {
return false;
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#getFile(java.lang.String)
*/
@Override
public File getFile(String key) {
return null;
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#getInputStream(java.lang.String)
*/
@Override
public InputStream getInputStream(String key) throws IOException {
throw new FileNotFoundException();
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#store(java.lang.String, java.io.InputStream)
*/
@Override
public void store(String key, InputStream is) {
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#cleanup()
*/
@Override
public void cleanup() {
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#invalidate(java.lang.String)
*/
@Override
public void invalidate(String key) {
}
/*
* (non-Javadoc)
* @see com.joelapenna.foursquared.util.DiskCache#clear()
*/
@Override
public void clear() {
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.util.Log;
import java.util.Calendar;
import java.util.Date;
/**
* Initializes a few Date objects to act as boundaries for sorting checkin lists
* by the following time categories:
*
* <ul>
* <li>Within the last three hours.</li>
* <li>Today</li>
* <li>Yesterday</li>
* </ul>
*
* Create an instance of this class, then call one of the three getBoundary() methods
* and compare against a Date object to see if it falls before or after.
*
* @date March 22, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class CheckinTimestampSort {
private static final String TAG = "CheckinTimestampSort";
private static final boolean DEBUG = false;
private static final int IDX_RECENT = 0;
private static final int IDX_TODAY = 1;
private static final int IDX_YESTERDAY = 2;
private Date[] mBoundaries;
public CheckinTimestampSort() {
mBoundaries = getDateObjects();
}
public Date getBoundaryRecent() {
return mBoundaries[IDX_RECENT];
}
public Date getBoundaryToday() {
return mBoundaries[IDX_TODAY];
}
public Date getBoundaryYesterday() {
return mBoundaries[IDX_YESTERDAY];
}
private static Date[] getDateObjects() {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
if (DEBUG) Log.d(TAG, "Now: " + cal.getTime().toGMTString());
// Three hours ago or newer.
cal.add(Calendar.HOUR, -3);
Date dateRecent = cal.getTime();
if (DEBUG) Log.d(TAG, "Recent: " + cal.getTime().toGMTString());
// Today.
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.HOUR);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
Date dateToday = cal.getTime();
if (DEBUG) Log.d(TAG, "Today: " + cal.getTime().toGMTString());
// Yesterday.
cal.add(Calendar.DAY_OF_MONTH, -1);
Date dateYesterday = cal.getTime();
if (DEBUG) Log.d(TAG, "Yesterday: " + cal.getTime().toGMTString());
return new Date[] { dateRecent, dateToday, dateYesterday };
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.error.LocationException;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class NotificationsUtil {
private static final String TAG = "NotificationsUtil";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static void ToastReasonForFailure(Context context, Exception e) {
if (DEBUG) Log.d(TAG, "Toasting for exception: ", e);
if (e == null) {
Toast.makeText(context, "A surprising new problem has occured. Try again!",
Toast.LENGTH_SHORT).show();
} else if (e instanceof SocketTimeoutException) {
Toast.makeText(context, "Foursquare over capacity, server request timed out!", Toast.LENGTH_SHORT).show();
} else if (e instanceof SocketException) {
Toast.makeText(context, "Foursquare server not responding", Toast.LENGTH_SHORT).show();
} else if (e instanceof IOException) {
Toast.makeText(context, "Network unavailable", Toast.LENGTH_SHORT).show();
} else if (e instanceof LocationException) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
} else if (e instanceof FoursquareCredentialsException) {
Toast.makeText(context, "Authorization failed.", Toast.LENGTH_SHORT).show();
} else if (e instanceof FoursquareException) {
// FoursquareError is one of these
String message;
int toastLength = Toast.LENGTH_SHORT;
if (e.getMessage() == null) {
message = "Invalid Request";
} else {
message = e.getMessage();
toastLength = Toast.LENGTH_LONG;
}
Toast.makeText(context, message, toastLength).show();
} else {
Toast.makeText(context, "A surprising new problem has occured. Try again!",
Toast.LENGTH_SHORT).show();
DumpcatcherHelper.sendException(e);
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.content.res.Resources;
import android.text.TextUtils;
import android.text.format.DateUtils;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.R;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Added date formats for today/yesterday/older contexts.
*/
public class StringFormatters {
public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
"EEE, dd MMM yy HH:mm:ss Z");
/** Should look like "9:09 AM". */
public static final SimpleDateFormat DATE_FORMAT_TODAY = new SimpleDateFormat(
"h:mm a");
/** Should look like "Sun 1:56 PM". */
public static final SimpleDateFormat DATE_FORMAT_YESTERDAY = new SimpleDateFormat(
"E h:mm a");
/** Should look like "Sat Mar 20". */
public static final SimpleDateFormat DATE_FORMAT_OLDER = new SimpleDateFormat(
"E MMM d");
public static String getVenueLocationFull(Venue venue) {
StringBuilder sb = new StringBuilder();
sb.append(venue.getAddress());
if (sb.length() > 0) {
sb.append(" ");
}
if (!TextUtils.isEmpty(venue.getCrossstreet())) {
sb.append("(");
sb.append(venue.getCrossstreet());
sb.append(")");
}
return sb.toString();
}
public static String getVenueLocationCrossStreetOrCity(Venue venue) {
if (!TextUtils.isEmpty(venue.getCrossstreet())) {
return "(" + venue.getCrossstreet() + ")";
} else if (!TextUtils.isEmpty(venue.getCity()) && !TextUtils.isEmpty(venue.getState())
&& !TextUtils.isEmpty(venue.getZip())) {
return venue.getCity() + ", " + venue.getState() + " " + venue.getZip();
} else {
return null;
}
}
public static String getCheckinMessageLine1(Checkin checkin, boolean displayAtVenue) {
if (checkin.getDisplay() != null) {
return checkin.getDisplay();
} else {
StringBuilder sb = new StringBuilder();
sb.append(getUserAbbreviatedName(checkin.getUser()));
if (checkin.getVenue() != null && displayAtVenue) {
sb.append(" @ " + checkin.getVenue().getName());
}
return sb.toString();
}
}
public static String getCheckinMessageLine2(Checkin checkin) {
if (TextUtils.isEmpty(checkin.getShout()) == false) {
return checkin.getShout();
} else {
// No shout, show address instead.
if (checkin.getVenue() != null && checkin.getVenue().getAddress() != null) {
String address = checkin.getVenue().getAddress();
if (checkin.getVenue().getCrossstreet() != null
&& checkin.getVenue().getCrossstreet().length() > 0) {
address += " (" + checkin.getVenue().getCrossstreet() + ")";
}
return address;
} else {
return "";
}
}
}
public static String getCheckinMessageLine3(Checkin checkin) {
if (!TextUtils.isEmpty(checkin.getCreated())) {
try {
return getTodayTimeString(checkin.getCreated());
} catch (Exception ex) {
return checkin.getCreated();
}
} else {
return "";
}
}
public static String getUserFullName(User user) {
StringBuffer sb = new StringBuffer();
sb.append(user.getFirstname());
String lastName = user.getLastname();
if (lastName != null && lastName.length() > 0) {
sb.append(" ");
sb.append(lastName);
}
return sb.toString();
}
public static String getUserAbbreviatedName(User user) {
StringBuffer sb = new StringBuffer();
sb.append(user.getFirstname());
String lastName = user.getLastname();
if (lastName != null && lastName.length() > 0) {
sb.append(" ");
sb.append(lastName.substring(0, 1) + ".");
}
return sb.toString();
}
public static CharSequence getRelativeTimeSpanString(String created) {
try {
return DateUtils.getRelativeTimeSpanString(DATE_FORMAT.parse(created).getTime(),
new Date().getTime(), DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_RELATIVE);
} catch (ParseException e) {
return created;
}
}
/**
* Returns a format that will look like: "9:09 AM".
*/
public static String getTodayTimeString(String created) {
try {
return DATE_FORMAT_TODAY.format(DATE_FORMAT.parse(created));
} catch (ParseException e) {
return created;
}
}
/**
* Returns a format that will look like: "Sun 1:56 PM".
*/
public static String getYesterdayTimeString(String created) {
try {
return DATE_FORMAT_YESTERDAY.format(DATE_FORMAT.parse(created));
} catch (ParseException e) {
return created;
}
}
/**
* Returns a format that will look like: "Sat Mar 20".
*/
public static String getOlderTimeString(String created) {
try {
return DATE_FORMAT_OLDER.format(DATE_FORMAT.parse(created));
} catch (ParseException e) {
return created;
}
}
/**
* Reads an inputstream into a string.
*/
public static String inputStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
public static String getTipAge(Resources res, String created) {
Calendar then = Calendar.getInstance();
then.setTime(new Date(created));
Calendar now = Calendar.getInstance();
now.setTime(new Date(System.currentTimeMillis()));
if (now.get(Calendar.YEAR) == then.get(Calendar.YEAR)) {
if (now.get(Calendar.MONTH) == then.get(Calendar.MONTH)) {
int diffDays = now.get(Calendar.DAY_OF_MONTH)- then.get(Calendar.DAY_OF_MONTH);
if (diffDays == 0) {
return res.getString(R.string.tip_age_today);
} else if (diffDays == 1) {
return res.getString(R.string.tip_age_days, "1", "");
} else {
return res.getString(R.string.tip_age_days, String.valueOf(diffDays), "s");
}
} else {
int diffMonths = now.get(Calendar.MONTH) - then.get(Calendar.MONTH);
if (diffMonths == 1) {
return res.getString(R.string.tip_age_months, "1", "");
} else {
return res.getString(R.string.tip_age_months, String.valueOf(diffMonths), "s");
}
}
} else {
int diffYears = now.get(Calendar.YEAR) - then.get(Calendar.YEAR);
if (diffYears == 1) {
return res.getString(R.string.tip_age_years, "1", "");
} else {
return res.getString(R.string.tip_age_years, String.valueOf(diffYears), "s");
}
}
}
public static String createServerDateFormatV1() {
DateFormat df = new SimpleDateFormat("EEE, dd MMM yy HH:mm:ss Z");
return df.format(new Date());
}
}
| Java |
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Handles building an internal list of all email addresses as both a comma
* separated list, and as a linked hash map for use with email invites. The
* internal map is kept for pruning when we get a list of contacts which are
* already foursquare users back from the invite api method. Note that after
* the prune method is called, the internal mEmailsCommaSeparated memeber may
* be out of sync with the contents of the other maps.
*
* @date April 26, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class AddressBookEmailBuilder {
/**
* Keeps all emails as a flat comma separated list for use with the
* API findFriends method.
*/
private StringBuilder mEmailsCommaSeparated;
/**
* Links a single email address to a single contact name.
*/
private LinkedHashMap<String, String> mEmailsToNames;
/**
* Links a single contact name to multiple email addresses.
*/
private HashMap<String, HashSet<String>> mNamesToEmails;
public AddressBookEmailBuilder() {
mEmailsCommaSeparated = new StringBuilder();
mEmailsToNames = new LinkedHashMap<String, String>();
mNamesToEmails = new HashMap<String, HashSet<String>>();
}
public void addContact(String contactName, String contactEmail) {
// Email addresses should be uniquely tied to a single contact name.
mEmailsToNames.put(contactEmail, contactName);
// Reverse link, a single contact can have multiple email addresses.
HashSet<String> emailsForContact = mNamesToEmails.get(contactName);
if (emailsForContact == null) {
emailsForContact = new HashSet<String>();
mNamesToEmails.put(contactName, emailsForContact);
}
emailsForContact.add(contactEmail);
// Keep building the comma separated flat list of email addresses.
if (mEmailsCommaSeparated.length() > 0) {
mEmailsCommaSeparated.append(",");
}
mEmailsCommaSeparated.append(contactEmail);
}
public String getEmailsCommaSeparated() {
return mEmailsCommaSeparated.toString();
}
public void pruneEmailsAndNames(Group<User> group) {
if (group != null) {
for (User it : group) {
// Get the contact name this email address belongs to.
String contactName = mEmailsToNames.get(it.getEmail());
if (contactName != null) {
Set<String> allEmailsForContact = mNamesToEmails.get(contactName);
if (allEmailsForContact != null) {
for (String jt : allEmailsForContact) {
// Get rid of these emails from the master list.
mEmailsToNames.remove(jt);
}
}
}
}
}
}
/** Returns the map as a list of [email, name] pairs. */
public List<ContactSimple> getEmailsAndNamesAsList() {
List<ContactSimple> list = new ArrayList<ContactSimple>();
for (Map.Entry<String, String> it : mEmailsToNames.entrySet()) {
ContactSimple contact = new ContactSimple();
contact.mName = it.getValue();
contact.mEmail = it.getKey();
list.add(contact);
}
return list;
}
public String getNameForEmail(String email) {
return mEmailsToNames.get(email);
}
public String toStringCurrentEmails() {
StringBuilder sb = new StringBuilder(1024);
sb.append("Current email contents:\n");
for (Map.Entry<String, String> it : mEmailsToNames.entrySet()) {
sb.append(it.getValue()); sb.append(" "); sb.append(it.getKey());
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
AddressBookEmailBuilder bld = new AddressBookEmailBuilder();
bld.addContact("john", "john@google.com");
bld.addContact("john", "john@hotmail.com");
bld.addContact("john", "john@yahoo.com");
bld.addContact("jane", "jane@blah.com");
bld.addContact("dave", "dave@amazon.com");
bld.addContact("dave", "dave@earthlink.net");
bld.addContact("sara", "sara@odwalla.org");
bld.addContact("sara", "sara@test.com");
System.out.println("Comma separated list of emails addresses:");
System.out.println(bld.getEmailsCommaSeparated());
Group<User> users = new Group<User>();
User userJohn = new User();
userJohn.setEmail("john@hotmail.com");
users.add(userJohn);
User userSara = new User();
userSara.setEmail("sara@test.com");
users.add(userSara);
bld.pruneEmailsAndNames(users);
System.out.println(bld.toStringCurrentEmails());
}
public static class ContactSimple {
public String mName;
public String mEmail;
}
} | Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public interface DiskCache {
public boolean exists(String key);
public File getFile(String key);
public InputStream getInputStream(String key) throws IOException;
public void store(String key, InputStream is);
public void invalidate(String key);
public void cleanup();
public void clear();
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import java.text.ParseException;
import java.util.Comparator;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Updated getVenueDistanceComparator() to do numeric comparison. (2010-03-23)
*/
public class Comparators {
private static Comparator<Venue> sVenueDistanceComparator = null;
private static Comparator<User> sUserRecencyComparator = null;
private static Comparator<Checkin> sCheckinRecencyComparator = null;
private static Comparator<Checkin> sCheckinDistanceComparator = null;
private static Comparator<Tip> sTipRecencyComparator = null;
public static Comparator<Venue> getVenueDistanceComparator() {
if (sVenueDistanceComparator == null) {
sVenueDistanceComparator = new Comparator<Venue>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Venue object1, Venue object2) {
// TODO: In practice we're pretty much guaranteed to get valid locations
// from foursquare, but.. what if we don't, what's a good fail behavior
// here?
try {
int d1 = Integer.parseInt(object1.getDistance());
int d2 = Integer.parseInt(object2.getDistance());
if (d1 < d2) {
return -1;
} else if (d1 > d2) {
return 1;
} else {
return 0;
}
} catch (NumberFormatException ex) {
return object1.getDistance().compareTo(object2.getDistance());
}
}
};
}
return sVenueDistanceComparator;
}
public static Comparator<Venue> getVenueNameComparator() {
if (sVenueDistanceComparator == null) {
sVenueDistanceComparator = new Comparator<Venue>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Venue object1, Venue object2) {
return object1.getName().toLowerCase().compareTo(
object2.getName().toLowerCase());
}
};
}
return sVenueDistanceComparator;
}
public static Comparator<User> getUserRecencyComparator() {
if (sUserRecencyComparator == null) {
sUserRecencyComparator = new Comparator<User>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(User object1, User object2) {
try {
return StringFormatters.DATE_FORMAT.parse(object2.getCreated()).compareTo(
StringFormatters.DATE_FORMAT.parse(object1.getCreated()));
} catch (ParseException e) {
return 0;
}
}
};
}
return sUserRecencyComparator;
}
public static Comparator<Checkin> getCheckinRecencyComparator() {
if (sCheckinRecencyComparator == null) {
sCheckinRecencyComparator = new Comparator<Checkin>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Checkin object1, Checkin object2) {
try {
return StringFormatters.DATE_FORMAT.parse(object2.getCreated()).compareTo(
StringFormatters.DATE_FORMAT.parse(object1.getCreated()));
} catch (ParseException e) {
return 0;
}
}
};
}
return sCheckinRecencyComparator;
}
public static Comparator<Checkin> getCheckinDistanceComparator() {
if (sCheckinDistanceComparator == null) {
sCheckinDistanceComparator = new Comparator<Checkin>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Checkin object1, Checkin object2) {
try {
int d1 = Integer.parseInt(object1.getDistance());
int d2 = Integer.parseInt(object2.getDistance());
if (d1 > d2) {
return 1;
} else if (d2 > d1) {
return -1;
} else {
return 0;
}
} catch (NumberFormatException ex) {
return 0;
}
}
};
}
return sCheckinDistanceComparator;
}
public static Comparator<Tip> getTipRecencyComparator() {
if (sTipRecencyComparator == null) {
sTipRecencyComparator = new Comparator<Tip>() {
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Tip object1, Tip object2) {
try {
return StringFormatters.DATE_FORMAT.parse(object2.getCreated()).compareTo(
StringFormatters.DATE_FORMAT.parse(object1.getCreated()));
} catch (ParseException e) {
return 0;
}
}
};
}
return sTipRecencyComparator;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import android.util.Log;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class JavaLoggingHandler extends Handler {
private static Map<Level, Integer> sLoglevelMap = new HashMap<Level, Integer>();
static {
sLoglevelMap.put(Level.FINEST, Log.VERBOSE);
sLoglevelMap.put(Level.FINER, Log.DEBUG);
sLoglevelMap.put(Level.FINE, Log.DEBUG);
sLoglevelMap.put(Level.INFO, Log.INFO);
sLoglevelMap.put(Level.WARNING, Log.WARN);
sLoglevelMap.put(Level.SEVERE, Log.ERROR);
}
@Override
public void publish(LogRecord record) {
Integer level = sLoglevelMap.get(record.getLevel());
if (level == null) {
level = Log.VERBOSE;
}
Log.println(level, record.getLoggerName(), record.getMessage());
}
@Override
public void close() {
}
@Override
public void flush() {
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Build;
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
* @date July 24, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class ImageUtils {
private ImageUtils() {
}
public static void resampleImageAndSaveToNewLocation(String pathInput, String pathOutput)
throws Exception
{
Bitmap bmp = resampleImage(pathInput, 640);
OutputStream out = new FileOutputStream(pathOutput);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
}
public static Bitmap resampleImage(String path, int maxDim)
throws Exception {
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bfo);
BitmapFactory.Options optsDownSample = new BitmapFactory.Options();
optsDownSample.inSampleSize = getClosestResampleSize(bfo.outWidth, bfo.outHeight, maxDim);
Bitmap bmpt = BitmapFactory.decodeFile(path, optsDownSample);
Matrix m = new Matrix();
if (bmpt.getWidth() > maxDim || bmpt.getHeight() > maxDim) {
BitmapFactory.Options optsScale = getResampling(bmpt.getWidth(), bmpt.getHeight(), maxDim);
m.postScale((float)optsScale.outWidth / (float)bmpt.getWidth(),
(float)optsScale.outHeight / (float)bmpt.getHeight());
}
int sdk = new Integer(Build.VERSION.SDK).intValue();
if (sdk > 4) {
int rotation = ExifUtils.getExifRotation(path);
if (rotation != 0) {
m.postRotate(rotation);
}
}
return Bitmap.createBitmap(bmpt, 0, 0, bmpt.getWidth(), bmpt.getHeight(), m, true);
}
private static BitmapFactory.Options getResampling(int cx, int cy, int max) {
float scaleVal = 1.0f;
BitmapFactory.Options bfo = new BitmapFactory.Options();
if (cx > cy) {
scaleVal = (float)max / (float)cx;
}
else if (cy > cx) {
scaleVal = (float)max / (float)cy;
}
else {
scaleVal = (float)max / (float)cx;
}
bfo.outWidth = (int)(cx * scaleVal + 0.5f);
bfo.outHeight = (int)(cy * scaleVal + 0.5f);
return bfo;
}
private static int getClosestResampleSize(int cx, int cy, int maxDim) {
int max = Math.max(cx, cy);
int resample = 1;
for (resample = 1; resample < Integer.MAX_VALUE; resample++) {
if (resample * maxDim > max) {
resample--;
break;
}
}
if (resample > 0) {
return resample;
}
return 1;
}
public static BitmapFactory.Options getBitmapDims(String path) throws Exception {
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bfo);
return bfo;
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.graphics.drawable.Drawable;
import android.widget.TabHost.TabSpec;
/**
* Acts as an interface to the TabSpec class for setting the content view.
* The level 3 SDK doesn't support setting a View for the content sections
* of the tab, so we can only use the big native tab style. The level 4
* SDK and up support specifying a custom view for the tab.
*
* @date March 9, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class TabsUtil3 {
private TabsUtil3() {
}
public static void setTabIndicator(TabSpec spec, String title, Drawable drawable) {
// if (drawable != null) {
// spec.setIndicator(title, drawable);
// } else {
spec.setIndicator(title);
// }
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.R;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.widget.Toast;
/**
* Collection of common functions for sending feedback.
*
* @author Alex Volovoy (avolovoy@gmail.com)
*/
public class FeedbackUtils {
private static final String FEEDBACK_EMAIL_ADDRESS = "crashreport-android@foursquare.com";
public static void SendFeedBack(Context context, Foursquared foursquared) {
Intent sendIntent = new Intent(Intent.ACTION_SEND);
final String[] mailto = {
FEEDBACK_EMAIL_ADDRESS
};
final String new_line = "\n";
StringBuilder body = new StringBuilder();
Resources res = context.getResources();
body.append(new_line);
body.append(new_line);
body.append(res.getString(R.string.feedback_more));
body.append(new_line);
body.append(res.getString(R.string.feedback_question_how_to_reproduce));
body.append(new_line);
body.append(new_line);
body.append(res.getString(R.string.feedback_question_expected_output));
body.append(new_line);
body.append(new_line);
body.append(res.getString(R.string.feedback_question_additional_information));
body.append(new_line);
body.append(new_line);
body.append("--------------------------------------");
body.append(new_line);
body.append("ver: ");
body.append(foursquared.getVersion());
body.append(new_line);
body.append("user: ");
body.append(foursquared.getUserId());
body.append(new_line);
body.append("p: ");
body.append(Build.MODEL);
body.append(new_line);
body.append("os: ");
body.append(Build.VERSION.RELEASE);
body.append(new_line);
body.append("build#: ");
body.append(Build.DISPLAY);
body.append(new_line);
body.append(new_line);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.feedback_subject));
sendIntent.putExtra(Intent.EXTRA_EMAIL, mailto);
sendIntent.putExtra(Intent.EXTRA_TEXT, body.toString());
sendIntent.setType("message/rfc822");
try {
context.startActivity(Intent.createChooser(sendIntent, context
.getText(R.string.feedback_subject)));
} catch (ActivityNotFoundException ex) {
Toast.makeText(context, context.getText(R.string.feedback_error), Toast.LENGTH_SHORT)
.show();
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquared.PreferenceActivity;
import com.joelapenna.foursquared.R;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
/**
* Collection of common functions which are called from the menu
*
* @author Alex Volovoy (avolovoy@gmail.com)
*/
public class MenuUtils {
// Common menu items
private static final int MENU_PREFERENCES = -1;
private static final int MENU_GROUP_SYSTEM = 20;
public static void addPreferencesToMenu(Context context, Menu menu) {
Intent intent = new Intent(context, PreferenceActivity.class);
menu.add(MENU_GROUP_SYSTEM, MENU_PREFERENCES, Menu.CATEGORY_SECONDARY,
R.string.preferences_label).setIcon(R.drawable.ic_menu_preferences).setIntent(
intent);
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.app.Activity;
import android.database.Cursor;
import android.provider.Contacts;
import android.provider.Contacts.PhonesColumns;
/**
* Implementation of address book functions for sdk levels 3 and 4.
*
* @date February 14, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class AddressBookUtils3and4 extends AddressBookUtils {
public AddressBookUtils3and4() {
}
@Override
public String getAllContactsPhoneNumbers(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] {
PhonesColumns.NUMBER
};
Cursor c = activity.managedQuery(Contacts.Phones.CONTENT_URI, PROJECTION, null, null,
Contacts.Phones.DEFAULT_SORT_ORDER);
if (c.moveToFirst()) {
sb.append(c.getString(0));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(0));
}
}
c.close();
return sb.toString();
}
@Override
public String getAllContactsEmailAddresses(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] {
Contacts.ContactMethods.DATA
};
Cursor c = activity.managedQuery(
Contacts.ContactMethods.CONTENT_EMAIL_URI,
PROJECTION, null, null,
Contacts.ContactMethods.DEFAULT_SORT_ORDER);
if (c.moveToFirst()) {
sb.append(c.getString(0));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(0));
}
}
c.close();
return sb.toString();
}
@Override
public AddressBookEmailBuilder getAllContactsEmailAddressesInfo(Activity activity) {
String[] PROJECTION = new String[] {
Contacts.PeopleColumns.NAME,
Contacts.ContactMethods.DATA
};
Cursor c = activity.managedQuery(
Contacts.ContactMethods.CONTENT_EMAIL_URI,
PROJECTION, null, null,
Contacts.ContactMethods.DEFAULT_SORT_ORDER);
// We give a list of emails: markww@gmail.com,johndoe@gmail.com,janedoe@gmail.com
// We get back only a list of emails of users that exist on the system (johndoe@gmail.com)
// Iterate over all those returned users, on each iteration, remove from our hashmap.
// Can now use the left over hashmap, which is still in correct order to display invites.
AddressBookEmailBuilder bld = new AddressBookEmailBuilder();
if (c.moveToFirst()) {
bld.addContact(c.getString(0), c.getString(1));
while (c.moveToNext()) {
bld.addContact(c.getString(0), c.getString(1));
}
}
c.close();
return bld;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
/**
* @date September 15, 2010.
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UiUtil {
private static final String TAG = "UiUtil";
public static int sdkVersion() {
return new Integer(Build.VERSION.SDK).intValue();
}
public static void startDialer(Context context, String phoneNumber) {
try {
Intent dial = new Intent();
dial.setAction(Intent.ACTION_DIAL);
dial.setData(Uri.parse("tel:" + phoneNumber));
context.startActivity(dial);
} catch (Exception ex) {
Log.e(TAG, "Error starting phone dialer intent.", ex);
Toast.makeText(context, "Sorry, we couldn't find any app to place a phone call!",
Toast.LENGTH_SHORT).show();
}
}
public static void startSmsIntent(Context context, String phoneNumber) {
try {
Uri uri = Uri.parse("sms:" + phoneNumber);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra("address", phoneNumber);
intent.setType("vnd.android-dir/mms-sms");
context.startActivity(intent);
} catch (Exception ex) {
Log.e(TAG, "Error starting sms intent.", ex);
Toast.makeText(context, "Sorry, we couldn't find any app to send an SMS!",
Toast.LENGTH_SHORT).show();
}
}
public static void startEmailIntent(Context context, String emailAddress) {
try {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("plain/text");
intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {
emailAddress
});
context.startActivity(intent);
} catch (Exception ex) {
Log.e(TAG, "Error starting email intent.", ex);
Toast.makeText(context, "Sorry, we couldn't find any app for sending emails!",
Toast.LENGTH_SHORT).show();
}
}
public static void startWebIntent(Context context, String url) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
} catch (Exception ex) {
Log.e(TAG, "Error starting url intent.", ex);
Toast.makeText(context, "Sorry, we couldn't find any app for viewing this url!",
Toast.LENGTH_SHORT).show();
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared.util;
import android.app.Activity;
import android.database.Cursor;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
/**
* Implementation of address book functions for sdk level 5 and above.
*
* @date February 14, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class AddressBookUtils5 extends AddressBookUtils {
public AddressBookUtils5() {
}
@Override
public String getAllContactsPhoneNumbers(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] { Contacts._ID, Phone.NUMBER };
Cursor c = activity.managedQuery(Phone.CONTENT_URI, PROJECTION, null, null, null);
if (c.moveToFirst()) {
sb.append(c.getString(1));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(1));
}
}
return sb.toString();
}
@Override
public String getAllContactsEmailAddresses(Activity activity) {
StringBuilder sb = new StringBuilder(1024);
String[] PROJECTION = new String[] { Email.DATA };
Cursor c = activity.managedQuery(Email.CONTENT_URI, PROJECTION, null, null, null);
if (c.moveToFirst()) {
sb.append(c.getString(0));
while (c.moveToNext()) {
sb.append(",");
sb.append(c.getString(0));
}
}
return sb.toString();
}
@Override
public AddressBookEmailBuilder getAllContactsEmailAddressesInfo(Activity activity) {
String[] PROJECTION = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, Email.DATA };
Cursor c = activity.managedQuery(Email.CONTENT_URI, PROJECTION, null, null, null);
// We give a list of emails: markww@gmail.com,johndoe@gmail.com,janedoe@gmail.com
// We get back only a list of emails of users that exist on the system (johndoe@gmail.com)
// Iterate over all those returned users, on each iteration, remove from our hashmap.
// Can now use the left over hashmap, which is still in correct order to display invites.
AddressBookEmailBuilder bld = new AddressBookEmailBuilder();
if (c.moveToFirst()) {
bld.addContact(c.getString(1), c.getString(2));
while (c.moveToNext()) {
bld.addContact(c.getString(1), c.getString(2));
}
}
c.close();
return bld;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.googlecode.dumpcatcher.logging.Dumpcatcher;
import com.googlecode.dumpcatcher.logging.DumpcatcherUncaughtExceptionHandler;
import com.googlecode.dumpcatcher.logging.StackFormattingUtil;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.R;
import org.apache.http.HttpResponse;
import android.content.res.Resources;
import android.util.Log;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class DumpcatcherHelper {
private static final String TAG = "DumpcatcherHelper";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final ExecutorService mExecutor = Executors.newFixedThreadPool(2);
private static Dumpcatcher sDumpcatcher;
private static String sClient;
public DumpcatcherHelper(String client, Resources resources) {
sClient = client;
setupDumpcatcher(resources);
}
public static void setupDumpcatcher(Resources resources) {
if (FoursquaredSettings.DUMPCATCHER_TEST) {
if (FoursquaredSettings.DEBUG)
Log.d(TAG, "Loading Dumpcatcher TEST");
sDumpcatcher = new Dumpcatcher( //
resources.getString(R.string.test_dumpcatcher_product_key), //
resources.getString(R.string.test_dumpcatcher_secret), //
resources.getString(R.string.test_dumpcatcher_url), sClient, 5);
} else {
if (FoursquaredSettings.DEBUG)
Log.d(TAG, "Loading Dumpcatcher Live");
sDumpcatcher = new Dumpcatcher( //
resources.getString(R.string.dumpcatcher_product_key), //
resources.getString(R.string.dumpcatcher_secret), //
resources.getString(R.string.dumpcatcher_url), sClient, 5);
}
UncaughtExceptionHandler handler = new DefaultUnhandledExceptionHandler(sDumpcatcher);
// This can hang the app starving android of its ability to properly
// kill threads... maybe.
Thread.setDefaultUncaughtExceptionHandler(handler);
Thread.currentThread().setUncaughtExceptionHandler(handler);
}
public static void sendCrash(final String shortMessage, final String longMessage,
final String level, final String tag) {
mExecutor.execute(new Runnable() {
@Override
public void run() {
try {
HttpResponse response = sDumpcatcher.sendCrash(shortMessage, longMessage,
level, "usage");
response.getEntity().consumeContent();
} catch (Exception e) {
if (DEBUG)
Log.d(TAG, "Unable to sendCrash");
}
}
});
}
public static void sendException(Throwable e) {
sendCrash(//
StackFormattingUtil.getStackMessageString(e), //
StackFormattingUtil.getStackTraceString(e), //
String.valueOf(Level.INFO.intValue()), //
"exception");
}
public static void sendUsage(final String usage) {
sendCrash(usage, null, null, "usage");
}
private static final class DefaultUnhandledExceptionHandler extends
DumpcatcherUncaughtExceptionHandler {
private static final UncaughtExceptionHandler mOriginalExceptionHandler = Thread
.getDefaultUncaughtExceptionHandler();
DefaultUnhandledExceptionHandler(Dumpcatcher dumpcatcher) {
super(dumpcatcher);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
super.uncaughtException(t, e);
mOriginalExceptionHandler.uncaughtException(t, e);
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.util;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.R;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import java.io.IOException;
import java.util.Observable;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class UserUtils {
public static void ensureUserPhoto(final Context context, final User user, final boolean DEBUG,
final String TAG) {
Activity activity = ((Activity) context);
final ImageView photo = (ImageView) activity.findViewById(R.id.photo);
if (user.getPhoto() == null) {
photo.setImageResource(R.drawable.blank_boy);
return;
}
final Uri photoUri = Uri.parse(user.getPhoto());
if (photoUri != null) {
RemoteResourceManager userPhotosManager = ((Foursquared) activity.getApplication())
.getRemoteResourceManager();
try {
Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager
.getInputStream(photoUri));
photo.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "photo not already retrieved, requesting: " + photoUri);
userPhotosManager.addObserver(new RemoteResourceManager.ResourceRequestObserver(
photoUri) {
@Override
public void requestReceived(Observable observable, Uri uri) {
observable.deleteObserver(this);
updateUserPhoto(context, photo, uri, user, DEBUG, TAG);
}
});
userPhotosManager.request(photoUri);
}
}
}
private static void updateUserPhoto(Context context, final ImageView photo, final Uri uri,
final User user, final boolean DEBUG, final String TAG) {
final Activity activity = ((Activity) context);
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
if (DEBUG) Log.d(TAG, "Loading user photo: " + uri);
RemoteResourceManager userPhotosManager = ((Foursquared) activity
.getApplication()).getRemoteResourceManager();
Bitmap bitmap = BitmapFactory.decodeStream(userPhotosManager
.getInputStream(uri));
photo.setImageBitmap(bitmap);
if (DEBUG) Log.d(TAG, "Loaded user photo: " + uri);
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "Unable to load user photo: " + uri);
if (Foursquare.MALE.equals(user.getGender())) {
photo.setImageResource(R.drawable.blank_boy);
} else {
photo.setImageResource(R.drawable.blank_girl);
}
} catch (Exception e) {
Log.d(TAG, "Ummm............", e);
}
}
});
}
public static boolean isFriend(User user) {
if (user == null) {
return false;
} else if (TextUtils.isEmpty(user.getFriendstatus())) {
return false;
} else if (user.getFriendstatus().equals("friend")) {
return true;
} else {
return false;
}
}
public static boolean isFollower(User user) {
if (user == null) {
return false;
} else if (TextUtils.isEmpty(user.getFriendstatus())) {
return false;
} else if (user.getFriendstatus().equals("pendingyou")) {
return true;
} else {
return false;
}
}
public static boolean isFriendStatusPendingYou(User user) {
return user != null && user.getFriendstatus() != null &&
user.getFriendstatus().equals("pendingyou");
}
public static boolean isFriendStatusPendingThem(User user) {
return user != null && user.getFriendstatus() != null &&
user.getFriendstatus().equals("pendingthem");
}
public static boolean isFriendStatusFollowingThem(User user) {
return user != null && user.getFriendstatus() != null &&
user.getFriendstatus().equals("followingthem");
}
public static int getDrawableForMeTabByGender(String gender) {
if (gender != null && gender.equals("female")) {
return R.drawable.tab_main_nav_me_girl_selector;
} else {
return R.drawable.tab_main_nav_me_boy_selector;
}
}
public static int getDrawableForMeMenuItemByGender(String gender) {
if (gender == null) {
return R.drawable.ic_menu_myinfo_boy;
} else if (gender.equals("female")) {
return R.drawable.ic_menu_myinfo_girl;
} else {
return R.drawable.ic_menu_myinfo_boy;
}
}
public static boolean getCanHaveFollowers(User user) {
if (user.getTypes() != null && user.getTypes().size() > 0) {
if (user.getTypes().contains("canHaveFollowers")) {
return true;
}
}
return false;
}
public static int getDrawableByGenderForUserThumbnail(User user) {
String gender = user.getGender();
if (gender != null && gender.equals("female")) {
return R.drawable.blank_girl;
} else {
return R.drawable.blank_boy;
}
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Badge;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Mayor;
import com.joelapenna.foursquare.types.Score;
import com.joelapenna.foursquare.types.Special;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.util.Base64Coder;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.widget.BadgeWithIconListAdapter;
import com.joelapenna.foursquared.widget.ScoreListAdapter;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.SpecialListAdapter;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* Renders the result of a checkin using a CheckinResult object. This is called
* from CheckinExecuteActivity. It would be nicer to put this in another activity,
* but right now the CheckinResult is quite large and would require a good amount
* of work to add serializers for all its inner classes. This wouldn't be a huge
* problem, but maintaining it as the classes evolve could more trouble than it's
* worth.
*
* The only way the user can dismiss this dialog is by hitting the 'back' key.
* CheckingExecuteActivity depends on this so it knows when to finish() itself.
*
* @date March 3, 2010.
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*
*/
public class CheckinResultDialog extends Dialog
{
private static final String TAG = "CheckinResultDialog";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private CheckinResult mCheckinResult;
private Handler mHandler;
private RemoteResourceManagerObserver mObserverMayorPhoto;
private Foursquared mApplication;
private String mExtrasDecoded;
private WebViewDialog mDlgWebViewExtras;
public CheckinResultDialog(Context context, CheckinResult result, Foursquared application) {
super(context, R.style.ThemeCustomDlgBase_ThemeCustomDlg);
mCheckinResult = result;
mApplication = application;
mHandler = new Handler();
mObserverMayorPhoto = null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkin_result_dialog);
setTitle(getContext().getResources().getString(R.string.checkin_title_result));
TextView tvMessage = (TextView)findViewById(R.id.textViewCheckinMessage);
if (mCheckinResult != null) {
tvMessage.setText(mCheckinResult.getMessage());
SeparatedListAdapter adapter = new SeparatedListAdapter(getContext());
// Add any badges the user unlocked as a result of this checkin.
addBadges(mCheckinResult.getBadges(), adapter, mApplication.getRemoteResourceManager());
// Add whatever points they got as a result of this checkin.
addScores(mCheckinResult.getScoring(), adapter, mApplication.getRemoteResourceManager());
// Add any specials that are nearby.
addSpecials(mCheckinResult.getSpecials(), adapter);
// Add a button below the mayor section which will launch a new webview if
// we have additional content from the server. This is base64 encoded and
// is supposed to be just dumped into a webview.
addExtras(mCheckinResult.getMarkup());
// List items construction complete.
ListView listview = (ListView)findViewById(R.id.listViewCheckinBadgesAndScores);
listview.setAdapter(adapter);
listview.setOnItemClickListener(mOnItemClickListener);
// Show mayor info if any.
addMayor(mCheckinResult.getMayor(), mApplication.getRemoteResourceManager());
} else {
// This shouldn't be possible but we've gotten a few crash reports showing that
// mCheckinResult is null on entry of this method.
Log.e(TAG, "Checkin result object was null on dialog creation.");
tvMessage.setText("Checked-in!");
}
}
@Override
protected void onStop() {
super.onStop();
if (mDlgWebViewExtras != null && mDlgWebViewExtras.isShowing()) {
mDlgWebViewExtras.dismiss();
}
if (mObserverMayorPhoto != null) {
mApplication.getRemoteResourceManager().deleteObserver(mObserverMayorPhoto);
}
}
private void addBadges(Group<Badge> badges, SeparatedListAdapter adapterMain, RemoteResourceManager rrm) {
if (badges == null || badges.size() < 1) {
return;
}
BadgeWithIconListAdapter adapter = new BadgeWithIconListAdapter(
getContext(), rrm, R.layout.badge_list_item);
adapter.setGroup(badges);
adapterMain.addSection(getContext().getResources().getString(R.string.checkin_result_dialog_badges),
adapter);
}
private void addScores(Group<Score> scores,
SeparatedListAdapter adapterMain,
RemoteResourceManager rrm) {
if (scores == null || scores.size() < 1) {
return;
}
// We make our own local score group because we'll inject the total as
// a new dummy score element.
Group<Score> scoresWithTotal = new Group<Score>();
// Total up the scoring.
int total = 0;
for (Score score : scores) {
total += Integer.parseInt(score.getPoints());
scoresWithTotal.add(score);
}
// Add a dummy score element to the group which is just the total.
Score scoreTotal = new Score();
scoreTotal.setIcon("");
scoreTotal.setMessage(getContext().getResources().getString(
R.string.checkin_result_dialog_score_total));
scoreTotal.setPoints(String.valueOf(total));
scoresWithTotal.add(scoreTotal);
// Give it all to the adapter now.
ScoreListAdapter adapter = new ScoreListAdapter(getContext(), rrm);
adapter.setGroup(scoresWithTotal);
adapterMain.addSection(getContext().getResources().getString(R.string.checkin_score), adapter);
}
private void addMayor(Mayor mayor, RemoteResourceManager rrm) {
LinearLayout llMayor = (LinearLayout)findViewById(R.id.llCheckinMayorInfo);
if (mayor == null) {
llMayor.setVisibility(View.GONE);
return;
} else {
llMayor.setVisibility(View.VISIBLE);
}
// Set the mayor message.
TextView tvMayorMessage = (TextView)findViewById(R.id.textViewCheckinMayorMessage);
tvMayorMessage.setText(mayor.getMessage());
// A few cases here for the image to display.
ImageView ivMayor = (ImageView)findViewById(R.id.imageViewCheckinMayor);
if (mCheckinResult.getMayor().getUser() == null) {
// I am still the mayor.
// Just show the crown icon.
ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown));
}
else if (mCheckinResult.getMayor().getType().equals("nochange")) {
// Someone else is mayor.
// Show that user's photo from the network. If not already on disk,
// we need to start a fetch for it.
Uri photoUri = populateMayorImageFromNetwork();
if (photoUri != null) {
mApplication.getRemoteResourceManager().request(photoUri);
mObserverMayorPhoto = new RemoteResourceManagerObserver();
rrm.addObserver(mObserverMayorPhoto);
}
addClickHandlerForMayorImage(ivMayor, mayor.getUser().getId());
}
else if (mCheckinResult.getMayor().getType().equals("new")) {
// I just became the new mayor as a result of this checkin.
// Just show the crown icon.
ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown));
}
else if (mCheckinResult.getMayor().getType().equals("stolen")) {
// I stole mayorship from someone else as a result of this checkin.
// Just show the crown icon.
ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown));
}
}
private void addSpecials(Group<Special> specials,
SeparatedListAdapter adapterMain) {
if (specials == null || specials.size() < 1) {
return;
}
// For now, get rid of specials not tied to the current venue. If the special is
// tied to this venue, then there would be no <venue> block associated with the
// special. If there is a <venue> block associated with the special, it means it
// belongs to another venue and we won't show it.
Group<Special> localSpecials = new Group<Special>();
for (Special it : specials) {
if (it.getVenue() == null) {
localSpecials.add(it);
}
}
if (localSpecials.size() < 1) {
return;
}
SpecialListAdapter adapter = new SpecialListAdapter(getContext());
adapter.setGroup(localSpecials);
adapterMain.addSection(
getContext().getResources().getString(R.string.checkin_specials), adapter);
}
private void addExtras(String extras) {
LinearLayout llExtras = (LinearLayout)findViewById(R.id.llCheckinExtras);
if (TextUtils.isEmpty(extras)) {
llExtras.setVisibility(View.GONE);
return;
} else {
llExtras.setVisibility(View.VISIBLE);
}
// The server sent us additional content, it is base64 encoded, so decode it now.
mExtrasDecoded = Base64Coder.decodeString(extras);
// TODO: Replace with generic extras method.
// Now when the user clicks this 'button' pop up yet another dialog dedicated
// to showing just the webview and the decoded content. This is not ideal but
// having problems putting a webview directly inline with the rest of the
// checkin content, we can improve this later.
llExtras.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDlgWebViewExtras = new WebViewDialog(getContext(), "SXSW Stats", mExtrasDecoded);
mDlgWebViewExtras.show();
}
});
}
private void addClickHandlerForMayorImage(View view, final String userId) {
// Show a user detail activity when the user clicks on the mayor's image.
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, userId);
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
v.getContext().startActivity(intent);
}
});
}
/**
* If we have to download the user's photo from the net (wasn't already in cache)
* will return the uri to launch.
*/
private Uri populateMayorImageFromNetwork() {
User user = mCheckinResult.getMayor().getUser();
ImageView ivMayor = (ImageView)findViewById(R.id.imageViewCheckinMayor);
if (user != null) {
Uri photoUri = Uri.parse(user.getPhoto());
try {
Bitmap bitmap = BitmapFactory.decodeStream(
mApplication.getRemoteResourceManager().getInputStream(photoUri));
ivMayor.setImageBitmap(bitmap);
return null;
} catch (IOException e) {
// User's image wasn't already in the cache, have to start a request for it.
if (Foursquare.MALE.equals(user.getGender())) {
ivMayor.setImageResource(R.drawable.blank_boy);
} else {
ivMayor.setImageResource(R.drawable.blank_girl);
}
return photoUri;
}
}
return null;
}
/**
* Called if the remote resource manager downloads the mayor's photo.
* If the photo is already on disk, this observer will never be used.
*/
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Fetcher got: " + data);
mHandler.post(new Runnable() {
@Override
public void run() {
populateMayorImageFromNetwork();
}
});
}
}
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Object obj = adapter.getItemAtPosition(position);
if (obj != null) {
if (obj instanceof Special) {
// When the user clicks on a special, if the venue is different than
// the venue the user checked in at (already being viewed) then show
// a new venue activity for that special.
Venue venue = ((Special)obj).getVenue();
if (venue != null) {
Intent intent = new Intent(getContext(), VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
getContext().startActivity(intent);
}
}
}
}
};
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Presents the user with a list of different methods for adding foursquare
* friends.
*
* @date February 11, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class AddFriendsActivity extends Activity {
private static final String TAG = "AddFriendsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
setContentView(R.layout.add_friends_activity);
Button btnAddFriendsByAddressBook = (Button) findViewById(R.id.findFriendsByAddressBook);
btnAddFriendsByAddressBook.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_ADDRESSBOOK);
startActivity(intent);
}
});
Button btnAddFriendsByFacebook = (Button) findViewById(R.id.findFriendsByFacebook);
btnAddFriendsByFacebook.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_FACEBOOK);
startActivity(intent);
}
});
Button btnAddFriendsByTwitter = (Button) findViewById(R.id.findFriendsByTwitter);
btnAddFriendsByTwitter.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_TWITTERNAME);
startActivity(intent);
}
});
Button btnAddFriendsByName = (Button) findViewById(R.id.findFriendsByNameOrPhoneNumber);
btnAddFriendsByName.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_NAME_OR_PHONE);
startActivity(intent);
}
});
Button btnInviteFriends = (Button) findViewById(R.id.findFriendsInvite);
btnInviteFriends.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AddFriendsActivity.this,
AddFriendsByUserInputActivity.class);
intent.putExtra(AddFriendsByUserInputActivity.INPUT_TYPE,
AddFriendsByUserInputActivity.INPUT_TYPE_ADDRESSBOOK_INVITE);
startActivity(intent);
}
});
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;
/**
* Can be called to execute a shout. Should be presented with the transparent
* dialog theme to appear only as a progress bar. When execution is complete, a
* toast will be shown with a success or error message.
*
* For the location paramters of the checkin method, this activity will grab the
* global last-known best location.
*
* The activity will setResult(RESULT_OK) if the shout worked, and will
* setResult(RESULT_CANCELED) if it did not work.
*
* @date March 10, 2010
* @author Mark Wyszomierski (markww@gmail.com).
*/
public class ShoutExecuteActivity extends Activity {
public static final String TAG = "ShoutExecuteActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_SHOUT = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_SHOUT";
public static final String INTENT_EXTRA_TELL_FRIENDS = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_TELL_FRIENDS";
public static final String INTENT_EXTRA_TELL_FOLLOWERS = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_TELL_FOLLOWERS";
public static final String INTENT_EXTRA_TELL_TWITTER = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_TELL_TWITTER";
public static final String INTENT_EXTRA_TELL_FACEBOOK = Foursquared.PACKAGE_NAME
+ ".ShoutExecuteActivity.INTENT_EXTRA_TELL_FACEBOOK";
private StateHolder mStateHolder;
private ProgressDialog mDlgProgress;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.checkin_execute_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
// We start the checkin immediately on creation.
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
} else {
mStateHolder = new StateHolder();
Foursquared foursquared = (Foursquared) getApplication();
Location location = foursquared.getLastKnownLocation();
mStateHolder.startTask(
this,
location,
getIntent().getExtras().getString(INTENT_EXTRA_SHOUT),
getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FRIENDS, false),
getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FOLLOWERS, false),
getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_TWITTER, false),
getIntent().getExtras().getBoolean(INTENT_EXTRA_TELL_FACEBOOK, false)
);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
@Override
public void onResume() {
super.onResume();
if (mStateHolder.getIsRunning()) {
startProgressBar(getResources().getString(R.string.shout_action_label),
getResources().getString(R.string.shout_execute_activity_progress_bar_message));
}
}
@Override
public void onPause() {
super.onPause();
stopProgressBar();
if (isFinishing()) {
mStateHolder.cancelTasks();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
private void startProgressBar(String title, String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, title, message);
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
private void onShoutComplete(CheckinResult result, Exception ex) {
mStateHolder.setIsRunning(false);
stopProgressBar();
if (result != null) {
Toast.makeText(this, getResources().getString(R.string.shout_exceute_activity_result),
Toast.LENGTH_LONG).show();
setResult(Activity.RESULT_OK);
} else {
NotificationsUtil.ToastReasonForFailure(this, ex);
setResult(Activity.RESULT_CANCELED);
}
finish();
}
private static class ShoutTask extends AsyncTask<Void, Void, CheckinResult> {
private ShoutExecuteActivity mActivity;
private Location mLocation;
private String mShout;
private boolean mTellFriends;
private boolean mTellFollowers;
private boolean mTellTwitter;
private boolean mTellFacebook;
private Exception mReason;
public ShoutTask(ShoutExecuteActivity activity,
Location location,
String shout,
boolean tellFriends,
boolean tellFollowers,
boolean tellTwitter,
boolean tellFacebook) {
mActivity = activity;
mLocation = location;
mShout = shout;
mTellFriends = tellFriends;
mTellFollowers = tellFollowers;
mTellTwitter = tellTwitter;
mTellFacebook = tellFacebook;
}
public void setActivity(ShoutExecuteActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar(mActivity.getResources().getString(
R.string.shout_action_label), mActivity.getResources().getString(
R.string.shout_execute_activity_progress_bar_message));
}
@Override
protected CheckinResult doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
CheckinResult result =
foursquare.checkin(
null,
null,
LocationUtils.createFoursquareLocation(mLocation),
mShout,
!mTellFriends, // (isPrivate)
mTellFollowers,
mTellTwitter,
mTellFacebook);
return result;
} catch (Exception e) {
if (DEBUG) Log.d(TAG, "ShoutTask: Exception checking in.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(CheckinResult result) {
if (DEBUG) Log.d(TAG, "ShoutTask: onPostExecute()");
if (mActivity != null) {
mActivity.onShoutComplete(result, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onShoutComplete(null, new Exception(
"Shout cancelled."));
}
}
}
private static class StateHolder {
private ShoutTask mTask;
private boolean mIsRunning;
public StateHolder() {
mIsRunning = false;
}
public void startTask(ShoutExecuteActivity activity,
Location location,
String shout,
boolean tellFriends,
boolean tellFollowers,
boolean tellTwitter,
boolean tellFacebook) {
mIsRunning = true;
mTask = new ShoutTask(activity, location, shout, tellFriends, tellFollowers,
tellTwitter, tellFacebook);
mTask.execute();
}
public void setActivity(ShoutExecuteActivity activity) {
if (mTask != null) {
mTask.setActivity(activity);
}
}
public boolean getIsRunning() {
return mIsRunning;
}
public void setIsRunning(boolean isRunning) {
mIsRunning = isRunning;
}
public void cancelTasks() {
if (mTask != null && mIsRunning) {
mTask.setActivity(null);
mTask.cancel(true);
}
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.