use of com.nolanlawson.keepscore.db.Game in project KeepScore by nolanlawson.
the class MainActivity method loadBackupInBackground.
private LoadGamesBackupResult loadBackupInBackground(Uri uri, Format format, Runnable onProgress) {
// use the start date as a unique identifier; it's a
// millisecond-timestamp, so it should work
GamesBackup gamesBackup;
try {
String xmlData = SdcardHelper.open(uri, format, getContentResolver());
gamesBackup = GamesBackupSerializer.deserialize(xmlData);
} catch (Exception e) {
log.e(e, "unexpected");
return null;
}
List<Game> loadedGames = new ArrayList<Game>();
int numFound = 0, numDuplicates = 0;
GameDBHelper dbHelper = null;
try {
dbHelper = new GameDBHelper(this);
for (Game game : gamesBackup.getGames()) {
numFound++;
if (dbHelper.existsByDateStarted(game.getDateStarted())) {
numDuplicates++;
} else {
// don't update 'dateSaved'
dbHelper.saveGame(game, false);
// value - keep original
loadedGames.add(game);
}
onProgress.run();
}
} finally {
if (dbHelper != null) {
dbHelper.close();
}
}
// this is just for the summary message we show the user
LoadGamesBackupResult result = new LoadGamesBackupResult();
result.setLoadedGames(loadedGames);
result.setNumDuplicates(numDuplicates);
result.setNumFound(numFound);
// Pre-version 3, we don't have the filename in the deserialized XML
String filenameToDisplay = gamesBackup.getFilename() != null ? gamesBackup.getFilename() : uri.getLastPathSegment();
result.setFilename(filenameToDisplay);
return result;
}
use of com.nolanlawson.keepscore.db.Game in project KeepScore by nolanlawson.
the class MainActivity method onReceiveLoadGamesBackupResult.
private void onReceiveLoadGamesBackupResult(LoadGamesBackupResult result) {
if (result == null) {
// failed to load the backup for some reason
ToastHelper.showLong(this, R.string.toast_error_with_backup);
return;
}
// load the new games into the existing adapter
for (Game game : result.getLoadedGames()) {
onNewGameCreated(game);
}
// create a nice summary message
String message = String.format(getString(R.string.text_load_backup), result.getFilename(), result.getNumFound(), result.getLoadedGames().size(), result.getNumDuplicates());
new AlertDialog.Builder(this).setCancelable(true).setTitle(R.string.title_success).setMessage(message).setPositiveButton(android.R.string.ok, null).show();
}
use of com.nolanlawson.keepscore.db.Game in project KeepScore by nolanlawson.
the class GameActivity method createNewGame.
private void createNewGame() {
String[] playerNames = getIntent().getStringArrayExtra(EXTRA_PLAYER_NAMES);
String[] playerColors = getIntent().getStringArrayExtra(EXTRA_PLAYER_COLORS);
game = new Game();
playerScores = new ArrayList<PlayerScore>();
game.setDateStarted(System.currentTimeMillis());
game.setPlayerScores(playerScores);
for (int i = 0; i < playerNames.length; i++) {
PlayerScore playerScore = new PlayerScore();
playerScore.setName(playerNames[i]);
playerScore.setPlayerColor(PlayerColor.deserialize(playerColors[i]));
playerScore.setPlayerNumber(i);
playerScore.setHistory(new ArrayList<Delta>());
playerScore.setScore(PreferenceHelper.getIntPreference(R.string.CONSTANT_pref_initial_score, R.string.CONSTANT_pref_initial_score_default, GameActivity.this));
playerScores.add(playerScore);
}
log.d("created new game: %s", game);
log.d("created new playerScores: %s", playerScores);
}
use of com.nolanlawson.keepscore.db.Game in project KeepScore by nolanlawson.
the class MainActivity method saveBackup.
private void saveBackup(final Format format, final Location location, final List<Integer> gameIds, final Callback<String> onSuccessWithFilename) {
if (!SdcardHelper.isAvailable()) {
ToastHelper.showLong(this, R.string.toast_no_sdcard);
return;
}
final String filename = SdcardHelper.createBackupFilename(format);
final ProgressDialog progressDialog = showProgressDialog(R.string.text_saving, gameIds.size());
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... params) {
List<Game> games = new ArrayList<Game>();
GameDBHelper dbHelper = null;
try {
dbHelper = new GameDBHelper(MainActivity.this);
for (Integer gameId : gameIds) {
Game game = dbHelper.findGameById(gameId);
games.add(game);
publishProgress((Void) null);
}
} finally {
if (dbHelper != null) {
dbHelper.close();
}
}
GamesBackup gamesBackup = new GamesBackup();
gamesBackup.setVersion(GamesBackupSerializer.CURRENT_VERSION);
gamesBackup.setDateSaved(System.currentTimeMillis());
gamesBackup.setAutomatic(false);
gamesBackup.setGameCount(games.size());
gamesBackup.setGames(games);
gamesBackup.setFilename(filename);
String xmlData = GamesBackupSerializer.serialize(gamesBackup);
return SdcardHelper.save(filename, format, location, xmlData);
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result) {
onSuccessWithFilename.onCallback(filename);
} else {
ToastHelper.showLong(MainActivity.this, R.string.toast_save_backup_failed);
}
progressDialog.dismiss();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
progressDialog.incrementProgressBy(1);
}
}.execute((Void) null);
}
use of com.nolanlawson.keepscore.db.Game in project KeepScore by nolanlawson.
the class SdcardHelper method saveSpreadsheet.
/**
* Write CSV file with games on the X axis and players (and basic game data) on the Y axis.
*
* @param filename
* @param games
* @return
*/
public static void saveSpreadsheet(String filename, List<Game> games, final Context context) {
// get all the unique player names so we can put them on the X axis
SortedSet<String> playerNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
// special value for players whose names weren't specified
for (Game game : games) {
for (PlayerScore playerScore : game.getPlayerScores()) {
playerNames.add(playerScore.toDisplayName(context).toString());
}
}
// sort by start date descending
List<Game> sortedGames = new ArrayList<Game>(games);
Collections.sort(sortedGames, new Comparator<Game>() {
@Override
public int compare(Game lhs, Game rhs) {
return Long.valueOf(rhs.getDateStarted()).compareTo(lhs.getDateStarted());
}
});
File file = new File(getDirectory(Location.Spreadsheets), filename);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
// write the column names
List<String> columnNames = new ArrayList<String>(Arrays.asList(context.getResources().getStringArray(R.array.share_spreadsheet_column_names)));
columnNames.addAll(playerNames);
writer.write(CSVUtil.convertToLine(columnNames));
// write each game as a line in the CSV
for (Game game : sortedGames) {
List<String> entries = new ArrayList<String>();
// date started
entries.add(CSV_DATE_FORMAT.format(new Date(game.getDateStarted())));
// date saved
entries.add(CSV_DATE_FORMAT.format(new Date(game.getDateSaved())));
// play time, using duration format HH:MM:SS
long duration = (game.getDateSaved() - game.getDateStarted()) / 1000;
entries.add(String.format("%02d:%02d:%02d", duration / 3600, (duration % 3600) / 60, duration % 60));
// num players
entries.add(Integer.toString(game.getPlayerScores().size()));
// num rounds
entries.add(Integer.toString(CollectionUtil.max(game.getPlayerScores(), Functions.PLAYER_SCORE_TO_HISTORY_SIZE)));
// game name
entries.add(game.getName());
Function<PlayerScore, String> playerScoreToName = new Function<PlayerScore, String>() {
@Override
public String apply(PlayerScore obj) {
return obj.toDisplayName(context).toString();
}
};
// player(s) with max
entries.add(TextUtils.join(", ", CollectionUtil.transform(CollectionUtil.maxWithTies(game.getPlayerScores(), Functions.PLAYER_SCORE_TO_SCORE), playerScoreToName)));
// player(s) with min
entries.add(TextUtils.join(", ", CollectionUtil.transform(CollectionUtil.minWithTies(game.getPlayerScores(), Functions.PLAYER_SCORE_TO_SCORE), playerScoreToName)));
// rest of columns are just all the player names, so add blank for irrelevant players
// or the score for the actual players
Map<String, Long> playerScoreLookup = new HashMap<String, Long>();
for (PlayerScore playerScore : game.getPlayerScores()) {
playerScoreLookup.put(playerScore.toDisplayName(context).toString(), playerScore.getScore());
}
for (String playerName : playerNames) {
Long score = playerScoreLookup.get(playerName);
entries.add(score != null ? Long.toString(score) : null);
}
writer.write(CSVUtil.convertToLine(entries));
}
} catch (IOException e) {
log.e(e, "unexpected error");
throw new RuntimeException(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
log.e(e, "unexpected error");
throw new RuntimeException(e);
}
}
}
}
Aggregations