Search in sources :

Example 1 with Game

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;
}
Also used : Game(com.nolanlawson.keepscore.db.Game) GameDBHelper(com.nolanlawson.keepscore.db.GameDBHelper) ArrayList(java.util.ArrayList) LoadGamesBackupResult(com.nolanlawson.keepscore.data.LoadGamesBackupResult) GamesBackup(com.nolanlawson.keepscore.serialization.GamesBackup)

Example 2 with Game

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();
}
Also used : AlertDialog(android.app.AlertDialog) Game(com.nolanlawson.keepscore.db.Game)

Example 3 with Game

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);
}
Also used : Game(com.nolanlawson.keepscore.db.Game) Delta(com.nolanlawson.keepscore.db.Delta) PlayerScore(com.nolanlawson.keepscore.db.PlayerScore)

Example 4 with Game

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);
}
Also used : Game(com.nolanlawson.keepscore.db.Game) GameDBHelper(com.nolanlawson.keepscore.db.GameDBHelper) List(java.util.List) ArrayList(java.util.ArrayList) ProgressDialog(android.app.ProgressDialog) GamesBackup(com.nolanlawson.keepscore.serialization.GamesBackup)

Example 5 with Game

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);
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Date(java.util.Date) BufferedWriter(java.io.BufferedWriter) Function(com.nolanlawson.keepscore.util.CollectionUtil.Function) Game(com.nolanlawson.keepscore.db.Game) TreeSet(java.util.TreeSet) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) PlayerScore(com.nolanlawson.keepscore.db.PlayerScore)

Aggregations

Game (com.nolanlawson.keepscore.db.Game)11 GameDBHelper (com.nolanlawson.keepscore.db.GameDBHelper)5 PlayerScore (com.nolanlawson.keepscore.db.PlayerScore)5 GamesBackup (com.nolanlawson.keepscore.serialization.GamesBackup)4 ArrayList (java.util.ArrayList)4 IOException (java.io.IOException)3 ProgressDialog (android.app.ProgressDialog)2 Delta (com.nolanlawson.keepscore.db.Delta)2 List (java.util.List)2 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)2 AlertDialog (android.app.AlertDialog)1 LoadGamesBackupResult (com.nolanlawson.keepscore.data.LoadGamesBackupResult)1 Function (com.nolanlawson.keepscore.util.CollectionUtil.Function)1 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 StringWriter (java.io.StringWriter)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1