Tecnologia do Blogger.
RSS

[androidbrasil-dev] Re: Parceria com Designer

Só pra que fique claro, eu pretendo sim pagar pelos serviços viu. Só não quero pagar um valor exorbitante para uma empresa que talvez não faça algo tão bom pra mobile.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Re: [androidbrasil-dev] Material Design para versões abaixo da 5.0

Acabei de ver. Valeu !!

2015-02-02 12:00 GMT-02:00 Rudson Lima <rudsonlive@gmail.com>:

https://developer.android.com/training/material/compatibility.html


Em seg, 2 de fev de 2015 10:58, Gink Labrev <gink.labrev@gmail.com> escreveu:
Pessoal,

Segundo o site oficial, o Material Design está disponível para 5.0 somente:

 To use material design in your Android apps, follow the guidelines defined in the material design specification and use the new components and functionality available in Android 5.0 (API level 21) and above.

Mas minha app de Gmail está no formato de Material Design e é 4.4.2.
Estou pensando em utilizar, mas não quero limitar a app somente a Lollipop. Há retrocompatibilidade garantida, a julgar pela app do Gmail ?

[]'s

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Re: [androidbrasil-dev] Re: NullPointer no método onCreate de um Service

package br.com.trackmob.electrolux.helpers.core;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.os.Vibrator;
import android.text.format.Time;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.splunk.mint.Mint;

import org.json.JSONException;
import org.json.JSONObject;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;

import br.com.trackmob.electrolux.TrackmobApplication;
import br.com.trackmob.electrolux.activities.StartWorkdayActivity;
import br.com.trackmob.electrolux.camera.PhotoManager;
import br.com.trackmob.electrolux.collections.CheckByDayHash;
import br.com.trackmob.electrolux.constants.TrackmobConstants;
import br.com.trackmob.electrolux.helpers.api.ApiClient;
import br.com.trackmob.electrolux.helpers.battery.BatteryHelper;
import br.com.trackmob.electrolux.helpers.database.OSDatabaseHelper;
import br.com.trackmob.electrolux.helpers.network.IBasicNetworkChange;
import br.com.trackmob.electrolux.helpers.network.NetworkHelper;
import br.com.trackmob.electrolux.helpers.sms.IAuthenticateSms;
import br.com.trackmob.electrolux.helpers.sms.SmsHelper;
import br.com.trackmob.electrolux.model.ApiQueue;
import br.com.trackmob.electrolux.model.Check;
import br.com.trackmob.electrolux.model.CheckStatus;
import br.com.trackmob.electrolux.model.Customer;
import br.com.trackmob.electrolux.model.Photo;
import br.com.trackmob.electrolux.model.User;
import br.com.trackmob.electrolux.model.Workday;
import br.com.trackmob.tm_core.database.config.Config.Configs;
import br.com.trackmob.tm_core.database.config.ConfigHelper;
import br.com.trackmob.tm_core.database.config.ConfigNotFoundException;
import br.com.trackmob.tm_core.locations.GeoHelper;
import br.com.trackmob.tm_core.locations.IAfterSaveGeocoord;
import br.com.trackmob.tm_core.locations.database.Address;
import br.com.trackmob.tm_core.locations.database.Geocoord;
import br.com.trackmob.tm_core.logs.TMLog;
import br.com.trackmob.tm_core.utils.DateUtils;

/**
* Created by Diego on 12/10/13.
*/
public class CoreService extends Service implements ICoreService, IAuthenticateSms, IAfterSaveGeocoord, IBasicNetworkChange {
private final static String START_WORKDAY_ACTION = "START_WORKDAY_ACTION";
private final static String STOP_WORKDAY_ACTION = "STOP_WORKDAY_ACTION";
private static boolean IS_RUNNING = false;
// vibrator
private static Vibrator vibrator = null;
private static Boolean initialized = false;
AlarmManager alarmMgr;
private IBinder binder = new CoreBinder(this);
// database helper
private OSDatabaseHelper dbHelper = null;
// configuration helper
private ConfigHelper configHelper = null;
// geolocation helper
private GeoHelper geoHelper = null;
// sms helper
private SmsHelper smsHelper = null;
// network helper
private NetworkHelper networkHelper = null;
// photo manager
private PhotoManager photoManager = null;
// battery helper
private BatteryHelper batteryHelper = null;
// active user
private User deviceOwner = null;
// active workday
private Workday activeWorkday = null;
// active check in
private Check activeCheckIn = null;
// next check in queue - utilizado na tela de iniciar atendimento (DashboardActivty)
private Check nextCheckIn = null;
// authenticated flag
private boolean authenticated = false;
private Timer timer;
private PendingIntent startWorkdayIntent;
private PendingIntent stopWorkdayIntent;
private ApiClient apiClient;

public static boolean isRunning() {
return CoreService.IS_RUNNING;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
TMLog.method(this, "onStartCommand");
CoreService.IS_RUNNING = true;
return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
TMLog.method(this, "onBind");
return binder;
}

@Override
public boolean onUnbind(Intent intent) {
TMLog.method(this, "onUnbind");
return false;
}

@Override
public void onCreate() {
super.onCreate();
TMLog.method(this, "onCreate");

// HttpHelper.setSyncServerUrl("http://172.16.200.144/sync_server/sync");
// HttpHelper.setDashboardUrl("http://172.16.200.144/sync_server/auth");
// SmsHelper.VALIDATE_NUMBER_URL = "http://172.16.200.144/sync_server/auth/get_code";
// OSDatabaseHelper.OS_API_URL = "http://172.16.200.144:3000/checks/from_day";

initializeService();

}

private void initializeService() {
TMLog.i(this, "Initializing service.");

// initiate network helper
if (networkHelper == null)
networkHelper = new NetworkHelper(this, this);
// initiate database helper
if (dbHelper == null)
dbHelper = new OSDatabaseHelper(this);
// initiate configuration helper
if (configHelper == null)
configHelper = new ConfigHelper(dbHelper);
// initiate photo manager
if (photoManager == null)
photoManager = new PhotoManager(this, dbHelper);
// initiate battery helper
if (batteryHelper == null) {
batteryHelper = BatteryHelper.getInstance(this);
}

// find device owner
deviceOwner = findDeviceOwner();
// find active workday
activeWorkday = findActiveWorkday();
// find active check in
activeCheckIn = findActiveCheckIn();

boolean isFirstLocation = activeWorkday == null || activeWorkday.geocoord == null;

// initiate geolocation helper
if (geoHelper == null)
geoHelper = new GeoHelper(this, dbHelper, this, isFirstLocation);
// initiate vibrator
if (vibrator == null)
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

// check if application is already authenticated
authenticated = configHelper.checkIfExists(Configs.AUTHENTICATED);
// start to watch SMSs trying to find a sms to authenticated
if (!authenticated && smsHelper == null) {
// TWW: 27800
List<String> numbersToWatches = Arrays.asList("27800");
smsHelper = new SmsHelper(this, this, numbersToWatches);
} else if (authenticated) {
setGlobalDeviceHash();

// start timer to check if is between 8am and 6pm
setWorkdayAlarms();

// Try to sync anything pendent
dbHelper.syncAll();
}

// if workday is initiated start to track device
if (activeWorkday.isInitiated())
this.start();

apiClient = ApiClient.getInstance(this);

initialized = true;

TMLog.i(this, "Service initializes.");
}

private void setGlobalDeviceHash() {
try {
// Recover device hash from database
String sDeviceHash = configHelper.getStringValue(Configs.DEVICE_HASH);
// Set global variable of device hash
TrackmobApplication.setDeviceHash(sDeviceHash);
// Configure BugSense with global device hash
Mint.setUserIdentifier(TrackmobApplication.getDeviceHash());
} catch (ConfigNotFoundException e) {
TMLog.e(this, e);
}
}

private void setWorkdayAlarms() {
alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

registerStartWorkdayReceiver();
registerStopWorkdayReceiver();

startWorkdayAlarm(false);
stopWorkdayAlarm();
}

private void registerStartWorkdayReceiver() {
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
TMLog.i("WorkdayReceiver", "onReceive to start workday.");
if (TrackmobConstants.START_WORKDAY_ALARM_INACTIVE || wasWorkdayInitiatedToday()) {
cancelStartWorkdayAlarm();
return;
}
// start to track location
CoreService.this.start();
// vibrate
vibrate();
// start workday activity
Intent i = new Intent(context, StartWorkdayActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
};

IntentFilter iFilter = new IntentFilter();
iFilter.addAction(START_WORKDAY_ACTION);

registerReceiver(receiver, iFilter);

startWorkdayIntent = PendingIntent.getBroadcast(this, 0, new Intent(START_WORKDAY_ACTION), 0);
}

private void registerStopWorkdayReceiver() {
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
TMLog.i("WorkdayReceiver", "onReceive to stop workday.");
// stop to track location
geoHelper.stop();
}
};

IntentFilter iFilter = new IntentFilter();
iFilter.addAction(STOP_WORKDAY_ACTION);

registerReceiver(receiver, iFilter);
stopWorkdayIntent = PendingIntent.getBroadcast(this, 0, new Intent(STOP_WORKDAY_ACTION), 0);
}

private void startWorkdayAlarm(boolean nextDay) {
alarmMgr.cancel(startWorkdayIntent);

Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());

// Verificar se é dia de semana; se não for, não executar;
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

// force next day if workday has been initiated
if (!nextDay && wasWorkdayInitiatedToday())
nextDay = true;

// se for sexta e nextDay, marcar para segunda
if (dayOfWeek == Calendar.FRIDAY && nextDay) {
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.WEEK_OF_MONTH, c.get(Calendar.WEEK_OF_MONTH) + 1);
// se for sábado ou domingo, marcar para segunda
} else if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY) {
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.set(Calendar.WEEK_OF_MONTH, c.get(Calendar.WEEK_OF_MONTH) + 1);
// se for dia seguinte, marcar para o próximo dia (+1)
} else if (nextDay) {
c.set(Calendar.DAY_OF_WEEK, dayOfWeek + 1);
}

c.set(Calendar.HOUR_OF_DAY, 8);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);

// repeating alarm
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 20 * 1000, startWorkdayIntent);
}

private void cancelStartWorkdayAlarm() {
if (startWorkdayIntent == null)
return;

alarmMgr.cancel(startWorkdayIntent);
startWorkdayAlarm(true);
}

private void stopWorkdayAlarm() {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());

c.set(Calendar.HOUR_OF_DAY, 18);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), 1000 * 60 * 60 * 24, stopWorkdayIntent);
}

/*
* (non-Javadoc)
*
* @see android.app.Service#onDestroy()
*/
@Override
public void onDestroy() {
super.onDestroy();
TMLog.method(this, "onDestroy");

// release database helper
OpenHelperManager.releaseHelper();

CoreService.IS_RUNNING = false;

BatteryHelper.stop(this);
}

private void pause() {
geoHelper.stop();
}

private void start() {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());

int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
int hour = c.get(Calendar.HOUR_OF_DAY);
boolean isWorkHour = hour >= 8 && hour < 18;

// forçar parada de localizações se for fim de semana ou fora do horário comercial
if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY || !isWorkHour) {
geoHelper.stop();
}
// iniciar captura de localizações se for dia de semana e dentro do horário "comercial"
else {
geoHelper.start();
}
}

private Workday findActiveWorkday() {
Time now = new Time();
now.setToNow();

Dao<Workday, Integer> dao = dbHelper.getDao(Workday.class);
QueryBuilder<Workday, Integer> qBuilder = dao.queryBuilder();

Workday w = null;
try {
w = qBuilder
.where()
.raw(String.format("DATE(date_start) = '%s'",
now.format("%Y-%m-%d"))).and().isNull("date_end")
.queryForFirst();
} catch (SQLException e) {
TMLog.sqlE(this, e);
} catch (IndexOutOfBoundsException e) {
TMLog.e(this, e);
} catch (NullPointerException e) {
TMLog.e(this, e);
}

return w != null ? w : new Workday(getDeviceOwner());

}

private Boolean wasWorkdayInitiatedToday() {
Time now = new Time();
now.setToNow();

Dao<Workday, Integer> dao = dbHelper.getDao(Workday.class);
QueryBuilder<Workday, Integer> qBuilder = dao.queryBuilder();

try {
Workday w = qBuilder
.where()
.raw(String.format("DATE(date_start) = '%s'", now.format("%Y-%m-%d")))
.queryForFirst();

return w != null;
} catch (SQLException e) {
TMLog.sqlE(this, e);
} catch (IndexOutOfBoundsException e) {
TMLog.e(this, e);
} catch (NullPointerException e) {
TMLog.e(this, e);
}

return false;

}

@Override
public ConfigHelper getConfigHelper() {
return this.configHelper;
}

@Override
public GeoHelper getGeoHelper() {
return this.geoHelper;
}

@Override
public Workday getActiveWorkday() {
return this.activeWorkday;
}

@Override
public void initiateActiveWorkday(Date date_start, Integer km_start) {
this.activeWorkday.initiate(date_start, km_start);

dbHelper.unsafeCreate(Workday.class, this.activeWorkday);

// parar alarm de início de jornada
this.cancelStartWorkdayAlarm();

// Iniciar serviço de geolocalização após começar jornada de trabalho
this.start();

geoHelper.start();

vibrate();
}

@Override
public void finalizeActiveWorkday(Date date_end, Integer km_end) {
this.activeWorkday.finalize(date_end, km_end);
dbHelper.unsafeCreate(Workday.class, this.activeWorkday);
this.activeWorkday = new Workday(getDeviceOwner());

// Pausar serviço de geolocalização após finalizar jornada de
// trabalho
this.pause();

vibrate();
}

@Override
public List<CheckStatus> getCheckStatuses() {
Dao<CheckStatus, Integer> dao = dbHelper.getDao(CheckStatus.class);

try {
return dao.queryForAll();
} catch (SQLException e) {
TMLog.sqlE(this, e);
}

return new ArrayList<CheckStatus>();
}

@Override
public Check getActiveCheckIn() {
if (activeCheckIn == null)
activeCheckIn = findActiveCheckIn();

return this.activeCheckIn;
}

@Override
public void doCheckIn(Date in, Geocoord geocoord) {
if (geocoord == null)
geocoord = getGeoHelper().getBestGeocoord();

if (geocoord != null) {
if (geocoord.address != null)
dbHelper.createOrUpdate(Address.class, geocoord.address);

dbHelper.createOrUpdate(Geocoord.class, geocoord);
}

this.activeCheckIn = this.nextCheckIn;
this.nextCheckIn = null;

if (this.activeCheckIn != null) {
// zerar a data de check-out
this.activeCheckIn.out = null;
this.activeCheckIn.in = in;
this.activeCheckIn.lastDeviceGeocoord = geocoord;
} else {
// this.activeCheckIn = new Check(this.deviceOwner, date, null, geocoord);
Mint.logException(new NullPointerException("CoreService's activeCheckIn is null."));
TMLog.i(this, "activeCheckIn is NULL!!! STOP EVERYTHING!!!");
return;
}

dbHelper.createOrUpdate(Check.class, this.activeCheckIn);
apiClient.queueRequest(ApiQueue.RequestMethod.CHECK_IN, this.activeCheckIn);

vibrate();
}

@Override
public void doCheckOut(Date out, CheckStatus checkStatus, String observation, String name, String ddd, String number) {
Customer customer = new Customer(name, ddd, number);

dbHelper.createOrUpdate(Customer.class, customer);

this.activeCheckIn.doCheckOut(out, checkStatus, observation, customer);

this.activeCheckIn.sync();
dbHelper.createOrUpdate(Check.class, this.activeCheckIn);
apiClient.queueRequest(ApiQueue.RequestMethod.CHECK_OUT, this.activeCheckIn);

this.activeCheckIn = null;

vibrate();
}

@Override
public boolean hasActiveCheckIn() {
return activeCheckIn != null && activeCheckIn.isInitialized() && !activeCheckIn.isFinalized();
}

@Override
public void activeCheckIn(Check check) {
this.activeCheckIn = check;
}

@Override
public List<Check> getChecksFromDay(Date day) {
return getChecks(day, null, Arrays.asList(new String[]{"registrado"}));
}

private List<Check> getChecks(Date day, List<String> inStatus, List<String> notInStatus) {
List<Check> list = null;

Dao<Check, Integer> dao = dbHelper.getDao(Check.class);
QueryBuilder<Check, Integer> qBuilder = dao.queryBuilder();

Dao<CheckStatus, Integer> daoStatus = dbHelper.getDao(CheckStatus.class);
QueryBuilder<CheckStatus, Integer> qsBuilder = daoStatus.queryBuilder();

try {
Where<CheckStatus, Integer> where = qsBuilder.where();

if (inStatus != null && inStatus.size() > 0)
where.in("title", inStatus);

if (notInStatus != null && notInStatus.size() > 0)
where.not().in("title", notInStatus);

List<CheckStatus> checkStatuses = qsBuilder.query();

qBuilder
.where()
.eq("day", day)
.and()
.in("check_status", checkStatuses);

qBuilder.orderBy("order", true);

list = qBuilder.query();
} catch (SQLException e) {
TMLog.e(this, e);
}

return list != null ? list : new ArrayList<Check>();
}

@Override
public List<Check> getChecksToOrder(Date day) {
return getChecks(day, Arrays.asList(new String[]{"ordenado", "registrado"}), null);
}

@Override
@Deprecated
public void syncAllChecks(List<Check> list) {
for (Check check : list) {
if (dbHelper.checkIfWasCanceledByManager(check))
check.checkStatus.id = CheckStatus.getIdByTitle("por_gestor");
}
dbHelper.createOrUpdate(Check.class, list);
dbHelper.sync(list);
}

@Override
public void syncOrders(List<Check> list) {
for (Check check : list)
check.sync();

dbHelper.createOrUpdate(Check.class, list);
apiClient.queueRequest(ApiQueue.RequestMethod.ORDER, list);
}

@Override
public void doCheckOut(Date out, String justification) {
try {
this.activeCheckIn.doCheckOut(out, justification);

// force sync_status = SYNCED
this.activeCheckIn.sync();
dbHelper.createOrUpdate(Check.class, this.activeCheckIn);

apiClient.queueRequest(ApiQueue.RequestMethod.CHECK_OUT, this.activeCheckIn);

if (photoManager != null)
photoManager.uploadPendingPhotos();

// clean active check in
this.activeCheckIn = null;
} catch (NullPointerException e) {
Mint.logException(e);
}

vibrate();
}

@Override
public void doCheckOut(Date out) {
this.doCheckOut(out, null);
}

@Override
public CheckByDayHash countChecksByDay() {
CheckByDayHash collection = new CheckByDayHash();

Dao<Check, Integer> dao = dbHelper.getDao(Check.class);
QueryBuilder<Check, Integer> qBuilder = dao.queryBuilder();

Dao<CheckStatus, Integer> daoStatus = dbHelper.getDao(CheckStatus.class);
QueryBuilder<CheckStatus, Integer> qsBuilder = daoStatus.queryBuilder();

try {
List<CheckStatus> checkStatuses = qsBuilder
.where()
.eq("title", "ordenado")
.or()
.eq("title", "registrado")
.query();

qBuilder
.where()
.in("check_status", checkStatuses);

qBuilder
.orderBy("check_status", true)
.orderBy("day", true);

List<Check> checks = qBuilder.query();
List<Check> checksWithoutDuplicates = new ArrayList<Check>();

for (Check check : checks) {
Check sameOsNumber = checkForOsSameDay(check.customer, check.day);
if (sameOsNumber == null || sameOsNumber.id.equals(check.id))
checksWithoutDuplicates.add(check);
}

collection.feed(checksWithoutDuplicates);
} catch (SQLException e) {
TMLog.e(this, e);
}

return collection;
}

private Check checkForOsSameDay(Customer customer, Date day) {
if (customer == null) {
return null;
}

// get customers with same os number
List<Customer> sameOsNumber = getCustomersForOsNumber(customer.os_number);
// if none exist, return false
if (sameOsNumber.size() == 0)
return null;

Dao<Check, Integer> dao = this.dbHelper.getDao(Check.class);
QueryBuilder<Check, Integer> qBuilder = dao.queryBuilder();
Where<Check, Integer> where = qBuilder.where();

try {
Check check = dao.queryForFirst(
where
.in("customer_id", sameOsNumber)
.and()
.eq("day", day)
.prepare()
);

return check;
} catch (SQLException e) {
TMLog.e(this, e);
}

return null;
}

private List<Customer> getCustomersForOsNumber(String osNumber) {
List<Customer> customers = new ArrayList<Customer>();

Dao<Customer, Integer> dao = this.dbHelper.getDao(Customer.class);
QueryBuilder<Customer, Integer> qBuilder = dao.queryBuilder();

try {
qBuilder.where().eq("os_number", osNumber);
customers = dao.query(qBuilder.prepare());
} catch (SQLException e) {
TMLog.sqlE(this, e);
}

return customers;
}

@Override
public void forceOSSync() {
dbHelper.getOSFromServer();
}

@Override
public boolean hasChecksToOrderForToday() {
Date today = DateUtils.getToday();

List<Check> toOrder = getChecks(today, Arrays.asList(new String[]{"registrado"}), null);

return toOrder.size() > 0;
}

@Override
public Integer setCheckStatus(String statusTitle) {
if (activeCheckIn == null)
return null;

Integer statusId = CheckStatus.getIdByTitle(statusTitle);
Dao<CheckStatus, Integer> dao = dbHelper.getDao(CheckStatus.class);

try {
this.activeCheckIn.checkStatus = dao.queryForId(statusId);
dbHelper.createOrUpdate(Check.class, this.activeCheckIn);

return this.activeCheckIn.checkStatus.id;
} catch (SQLException e) {
TMLog.sqlE(this, e);
}

return null;
}

private User findDeviceOwner() {
User u = null;

try {
List<User> list = dbHelper.getDao(User.class).queryForEq("device_owner", true);
if (list != null && list.isEmpty()) {
TMLog.w(this, "device_owner not found");
return null;
} else {
u = list.get(0);
}
} catch (SQLException e) {
TMLog.sqlE(this, e);
} catch (IndexOutOfBoundsException e) {
TMLog.e(this, e);
}

return u;
}

private Boolean saveDeviceOwner(JSONObject jsonAuth) {
try {
// recover user from json
JSONObject jsonUser = jsonAuth.getJSONObject("User");
// recover user name
String name = jsonUser.getString("name");
// recover user email
String email = jsonUser.getString("email");
// recover sync id
Integer syncId = jsonUser.getInt("id");
// create user instance
User user = new User(name, email, true);
// associate sync id
user.sync_id = syncId;
user.sync();
// create user
Dao<User, Integer> dao = dbHelper.getDao(User.class);
dao.createOrUpdate(user);
this.deviceOwner = user;

return true;
} catch (NullPointerException e) {
TMLog.e(this, e);
} catch (JSONException e) {
TMLog.e(this, e);
} catch (SQLException e) {
TMLog.sqlE(this, e);
}

return false;
}

private Boolean saveCompanyName(JSONObject jsonAuth) {
try {
configHelper.saveConfig(Configs.COMPANY_NAME, jsonAuth
.getJSONObject("Company").getString("name"));

return true;
} catch (NullPointerException e) {
TMLog.e(this, e);
} catch (JSONException e) {
TMLog.e(this, e);
}

return false;
}

@Override
public User getDeviceOwner() {
if (deviceOwner == null)
return findDeviceOwner();
else
return deviceOwner;
}

@Override
public Check getNextCheckIn() {
return this.nextCheckIn;
}

@Override
public void setNextCheckIn(Check nextCheckIn) {
this.nextCheckIn = nextCheckIn;
}

@Override
public Boolean isNextCheckInActivated() {
return this.nextCheckIn != null && this.activeCheckIn != null ? this.nextCheckIn.id.equals(this.activeCheckIn.id) : false;
}

@Override
public boolean isAuthenticated() {
return this.authenticated;
}

@Override
public boolean workdayInitiated() {
return activeWorkday.isInitiated();
}

@Override
public boolean hasDeviceEmail() {
return configHelper.checkIfExists(Configs.DEVICE_EMAIL);
}

@Override
public void activeCheckHasPhotos() {
this.activeCheckIn.hasPhotos = true;
dbHelper.createOrUpdate(Check.class, this.activeCheckIn);
}

private Check findActiveCheckIn() {
Time now = new Time();
now.setToNow();

// Procurar por check in feito hoje que esteja sem data de check out
Dao<Check, Integer> dao = dbHelper.getDao(Check.class);
QueryBuilder<Check, Integer> qBuilder = dao.queryBuilder();

try {
qBuilder.where()
.raw(String.format("DATE(`in`) = '%s'", now.format("%Y-%m-%d")))
.and()
.isNull("out");

Check check = dao.queryForFirst(qBuilder.prepare());

return check;
} catch (SQLException e) {
TMLog.sqlE(this, e);
Mint.logException(e);
} catch (NullPointerException e) {
TMLog.e(this, e);
Mint.logException(e);
} catch (IndexOutOfBoundsException e) {
TMLog.e(this, e);
} catch (Exception e) {
TMLog.e(this, e);
Mint.logException(e);
}

return null;
}

public void vibrate() {
vibrator.vibrate(new long[]{0, 100, 200, 100, 50, 200}, -1);
}

@Override
public Boolean authenticate(JSONObject jsonAuth) {
if (!authenticated) {
// Save company name
Boolean ok = saveCompanyName(jsonAuth);
// Save device owner
Boolean ok1 = saveDeviceOwner(jsonAuth);
// unregister sms receiver

if (ok && ok1) {
// Authenticate application
configHelper.saveConfig(Configs.AUTHENTICATED, true);
authenticated = true;

setWorkdayAlarms();

return true;
}

return false;
}

return true;
}

@Override
public String getHashFromSms(String smsBody) {
// hash will be whatever between preHash and hashLimit
String preHash = "Codigo para autenticacao: ";
String hashLimit = ".";

if (smsBody.indexOf(preHash) == -1) {
return null;
}

String hash = smsBody.substring(
smsBody.indexOf(preHash) + preHash.length(),
smsBody.indexOf(hashLimit,
smsBody.indexOf(preHash) + preHash.length()));

return hash;
}

@Override
public void saveHash(String hash) {
if (hash != null && hash.length() > 0)
configHelper.saveConfig(Configs.DEVICE_HASH, hash);
}

@Override
public void newGeocoord(Geocoord geocoord) {
if (this.activeWorkday.geocoord == null || this.activeWorkday.geocoord.lat == null || this.activeWorkday.geocoord.lng == null) {
this.activeWorkday.geocoord = geocoord;
this.activeWorkday.unsync();
dbHelper.unsafeCreate(Workday.class, this.activeWorkday);
}
}

@Override
public void gotNetworkConnection() {
dbHelper.syncAll();
photoManager.uploadPendingPhotos();
}

@Override
public Photo getPhoto() {
return photoManager.findPhotoByCheckSyncId(this.getActiveCheckIn().sync_id);
}

@Override
public Photo newPhoto() {
return newPhoto(getActiveCheckIn());
}

@Override
public List<Photo> getPhotos() {
return photoManager.listPhotosFromCheckIn(this.getActiveCheckIn().sync_id);
}

@Override
public void savePhoto(Photo photo) {
dbHelper.createOrUpdate(Photo.class, photo);
}

@Override
public boolean deletePhoto(Photo photo) {
try {
return dbHelper.getDao(Photo.class).delete(photo) == 1;
} catch (SQLException e) {
TMLog.sqlE(this, e);
Mint.logException(e);
return false;
}
}

private Photo newPhoto(Check checkIn) {
return photoManager.newPhoto(checkIn.id, checkIn.sync_id);
}

@Override
public void validateNumber(String ddd, String number) {
ddd = ddd.replace("(", "").replace(")", "");
smsHelper.validateNumber(ddd, number);
}

@Override
public void validateHash(String hash) {
if (hash != null && hash.length() > 0 && !authenticated)
smsHelper.postHash(hash);
}

@Override
public void syncAll() {
this.dbHelper.syncAll();
}

}

Ah eu simplifiquei o código para enviar para vocês, o initializeService é o trecho de código das inicializações após o onCreate().
Segue o código em anexo.

Pra mim simplesmente não tem explicação, pq ele funciona ok com o debugger, e quando vou colocando prints para ver se dá algum nullpointer, ele funciona normal.
Simplesmente sem sentido...

P.S.: O código não é meu, só estou dando manutenção...

private void initializeService() {
        TMLog.i(this, "Initializing service.");

        // initiate network helper
        if (networkHelper == null)
            networkHelper = new NetworkHelper(this, this);
        // initiate database helper
        if (dbHelper == null)
            dbHelper = new OSDatabaseHelper(this);
        // initiate configuration helper
        if (configHelper == null)
            configHelper = new ConfigHelper(dbHelper);
        // initiate photo manager
        if (photoManager == null)
            photoManager = new PhotoManager(this, dbHelper);
        // initiate battery helper
        if (batteryHelper == null)
            batteryHelper = BatteryHelper.getInstance(this);

        // find device owner
        deviceOwner = findDeviceOwner();
        // find active workday
        activeWorkday = findActiveWorkday();
        // find active check in
        activeCheckIn = findActiveCheckIn();

        boolean isFirstLocation = activeWorkday == null || activeWorkday.geocoord == null;

        // initiate geolocation helper
        if (geoHelper == null)
            geoHelper = new GeoHelper(this, dbHelper, this, isFirstLocation);
        // initiate vibrator
        if (vibrator == null)
            vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        // check if application is already authenticated
        authenticated = configHelper.checkIfExists(Configs.AUTHENTICATED);
        // start to watch SMSs trying to find a sms to authenticated
        if (!authenticated && smsHelper == null) {
            // TWW: 27800
            List<String> numbersToWatches = Arrays.asList("27800");
            smsHelper = new SmsHelper(this, this, numbersToWatches);
        } else if (authenticated) {
            setGlobalDeviceHash();

            // start timer to check if is between 8am and 6pm
            setWorkdayAlarms();

            // Try to sync anything pendent
            dbHelper.syncAll();
        }

        // if workday is initiated start to track device
        if (activeWorkday.isInitiated())
            this.start();

        apiClient = ApiClient.getInstance(this);

        initialized = true;

        TMLog.i(this, "Service initializes.");
    }


Bruno Vercelino da Hora
--
"Mas Deus prova o seu próprio amor para conosco pelo fato de ter Cristo morrido por nós, sendo nós ainda pecadores." - Romanos 5:8
"Mas em nada tenho a minha vida como preciosa para mim, contando que complete a minha carreira e o ministério que recebi do Senhor Jesus, para dar testemunho do evangelho da graça de Deus." - Atos 20:24

2015-02-02 11:51 GMT-02:00 Geovani **Leia a documentação oficial** de Souza <geovanisouza92@gmail.com>:
Bruno, o erro não ocorre no onCreate, mas no CoreService.initializeService, linha 155. O que há nessa linha?

--
You received this message because you are subscribed to a topic in the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/androidbrasil-dev/jOq2c3-Cb3M/unsubscribe.
To unsubscribe from this group and all its topics, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Re: [androidbrasil-dev] Material Design para versões abaixo da 5.0

https://developer.android.com/training/material/compatibility.html


Em seg, 2 de fev de 2015 10:58, Gink Labrev <gink.labrev@gmail.com> escreveu:
Pessoal,

Segundo o site oficial, o Material Design está disponível para 5.0 somente:

 To use material design in your Android apps, follow the guidelines defined in the material design specification and use the new components and functionality available in Android 5.0 (API level 21) and above.

Mas minha app de Gmail está no formato de Material Design e é 4.4.2.
Estou pensando em utilizar, mas não quero limitar a app somente a Lollipop. Há retrocompatibilidade garantida, a julgar pela app do Gmail ?

[]'s

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

[androidbrasil-dev] Material Design para versões abaixo da 5.0

Pessoal,

Segundo o site oficial, o Material Design está disponível para 5.0 somente:

 To use material design in your Android apps, follow the guidelines defined in the material design specification and use the new components and functionality available in Android 5.0 (API level 21) and above.

Mas minha app de Gmail está no formato de Material Design e é 4.4.2.
Estou pensando em utilizar, mas não quero limitar a app somente a Lollipop. Há retrocompatibilidade garantida, a julgar pela app do Gmail ?

[]'s

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

Re: [androidbrasil-dev] Re: NullPointer no método onCreate de um Service

Bruno, o erro não ocorre no onCreate, mas no CoreService.initializeService, linha 155. O que há nessa linha?

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

[androidbrasil-dev] Re: [MEU APP] Monitora, Brasil!

Olá pessoal, segue o link do repositório https://github.com/geraugu/MonitoraBrasil_android

Essa versão é o resultado da migração do eclipse para o android studio. Algumas funcionalidades estão dando pau. Preciso de um tempo para mexer nisso, mas estou meio enrolado no trampo. Quem quiser colaborar fique a vontade. 

Seria muito bom juntarmos força para o desenvolvimento de uma ferramenta que pode ser referência na política do Brasil. Pelo menos tentar fazer algo para mudar essa zona parlamentar que está hoje. Bora colocar esses políticos no devido lugar, que é nos representar.

Valeu.

Em quarta-feira, 28 de janeiro de 2015 15:53:53 UTC-2, Geraldo Augusto escreveu:
E aí pessoal, blz? Não conhecia esse grupo, muito bom!

Sobre o app, desenvolvi para monitorar os deputados e senadores. Pego as infos do webservice da camara e senado. 
Muita coisa precisa ser melhorada, mas tem muita informação. Logo disponibilizarei o código no github, quem quiser ajudar será muito bemvindo.

Tenho um backlog com várias funcionalidades para implementar e melhorias a serem feitas, o problema é fazer sozinho e falta de tempo.
Quem se interessar é só falar!
Seguem os links

Valeu


--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS