Android Open Source - MythTrack Title Helper






From Project

Back to project page MythTrack.

License

The source code is released under:

MIT License

If you think the Android project MythTrack listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/**
 * TitleHelper simplifies the management of the "Titles" table in the database.
 */*w  w  w . j  a  v  a  2 s  .  c om*/
 * @author Nolan Jurgens
 */

package nolanjurgens.mythtrack.app;

// IMPORTS /////////////////////////////////////////////////////////////////////////////////////////
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.util.JsonReader;
import android.util.Log;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import nolanjurgens.mythtrack.R;
import nolanjurgens.mythtrack.provider.MythTrackContract;

////////////////////////////////////////////////////////////////////////////////////////////////////
// CLASS - TitleHelper                                                                             //
////////////////////////////////////////////////////////////////////////////////////////////////////
public class TitleHelper
{
  // CONSTANTS /////////////////////////////////////////////////////////////////////////////////////

  /** A tag used to mark console output. */
  private static final String TAG = "TitleHelper";

  // Additional relevant constants in MythTrackContract.Titles class.

  // FIELDS ////////////////////////////////////////////////////////////////////////////////////////

  /** The parent context.*/
  private Context context;
  /** Object for accessing Android resources.*/
  private Resources resources;

  // METHODS ///////////////////////////////////////////////////////////////////////////////////////

  /**
   * Constructor
   * @param context The parent activity/context.
   */
  public TitleHelper(Context context)
  {
    // Get handle to the context and resources.
    this.context = context;
    resources = context.getResources();
  }

  // TODO - EARNED TITLES
  /**
   * Loads the attributes for an inventory title from the database into an Title object.
   * @param inventoryID The inventory ID of the requested title.
   * @return The Title that was retrieved.
   */
  /*
  public Title getInventoryTitle(long inventoryID)
  {
    long titleID;

    // Get the title ID for the inventory ID.
    if(inventoryID == 0)
    {
      titleID = 0;
    }
    else
    {
      Uri inventoryURI = Uri.withAppendedPath(MythTrackContract.Inventories.CONTENT_URI,
        Long.toString(inventoryID));
      Cursor inventoryCursor = context.getContentResolver().query(inventoryURI,
        MythTrackContract.Inventories.PROJECTION_TITLE_LOAD, null, null, null);
      int titleIDColumn
        = inventoryCursor.getColumnIndex(MythTrackContract.Inventories.COLUMN_TITLE_ID);
      if(inventoryCursor.getCount() == 0)
      {
        titleID = 0;
      }
      else
      {
        inventoryCursor.moveToFirst();
        titleID = inventoryCursor.getLong(titleIDColumn);
      }
      inventoryCursor.close();
    }

    // Use getTitle to get the Title object.
    return getTitle(titleID);
  }
  */

  /**
   * Loads the attributes for an title from the database into an Title object.
   * @param titleID The ID of the row to load into the title.
   * @return The Title that was retrieved.
   */
  public Title getTitle(long titleID)
  {
    Title title = new Title();

    // Initialize the title.
    title.setID(0);
    title.setName(resources.getString(R.string.titlehelper_no_title));
    title.setDescription(resources.getString(R.string.titlehelper_no_description));
    title.setNonCombatActionModifier(0);
    title.setMovementPointsModifier(0);
    title.setVitalityModifier(0);
    title.setImmunities(0);
    

    // If the requested ID is zero, then title is an empty placeholder.
    if(titleID == 0)
    {
      return title;
    }

    // Get a cursor with all columns for the target title.
    Uri titleURI = Uri.withAppendedPath(MythTrackContract.Titles.CONTENT_URI,
      Long.toString(titleID));
    Cursor targetTitle = context.getContentResolver().query(titleURI,
      MythTrackContract.Titles.PROJECTION_LOAD, null, null, null);
    // The cursor should have exactly one title/row.
    if(targetTitle.getCount() == 1)
    {
      // Load that row.
      targetTitle.moveToFirst();
    }
    // If there's more than one or none, there's a problem. Return an empty title.
    else
    {
      targetTitle.close();
      return title;
    }

    // Load the values from the database into the title object.

    // ID
    int idColumn = targetTitle.getColumnIndex(MythTrackContract.Titles._ID);
    long id = targetTitle.getLong(idColumn);
    title.setID(id);

    // Name
    int nameColumn = targetTitle.getColumnIndex(MythTrackContract.Titles.COLUMN_NAME);
    String name = targetTitle.getString(nameColumn);
    title.setName(name);

    // Description
    int descriptionColumn = targetTitle.getColumnIndex(MythTrackContract.Titles.COLUMN_DESCRIPTION);
    String description = targetTitle.getString(descriptionColumn);
    title.setDescription(description);

    // Movement Points Modifier
    int movementPointsColumn 
      = targetTitle.getColumnIndex(MythTrackContract.Titles.COLUMN_MOVEMENT_POINTS);
    int movementPoints = targetTitle.getInt(movementPointsColumn);
    title.setMovementPointsModifier(movementPoints);

    // Non-Combat Action
    int nonCombatActionColumn
      = targetTitle.getColumnIndex(MythTrackContract.Titles.COLUMN_NON_COMBAT_ACTION);
    int nonCombatAction = targetTitle.getInt(nonCombatActionColumn);
    title.setNonCombatActionModifier(nonCombatAction);

    // Vitality Modifier
    int vitalityColumn = targetTitle.getColumnIndex(MythTrackContract.Titles.COLUMN_VITALITY);
    int vitality = targetTitle.getInt(vitalityColumn);
    title.setVitalityModifier(vitality);

    // Immunities
    int immunitiesColumn = targetTitle.getColumnIndex(MythTrackContract.Titles.COLUMN_IMMUNITIES);
    int immunities = targetTitle.getInt(immunitiesColumn);
    title.setImmunities(immunities);

    // Close the cursor.
    targetTitle.close();

    return title;
  }


  /**
   * Process the JSON entry for a single title and create a new title in the database.
   * @param reader The JSON reader that is processing the source JSON file.
   * @return True if the title was added successfully.
   */
  public boolean processTitleEntry(JsonReader reader)
  {
    String name = null;
    String description = null;
    int movementPoints = 0;
    int nonCombatAction = 0;
    int vitality = 0;
    int immunities = 0;

    try
    {
      // Begin processing the title entry.
      reader.beginObject();
      // Process each name/value pair.
      while(reader.hasNext())
      {
        String jsonName = reader.nextName();
        if(jsonName.equals(MythTrackContract.Titles.COLUMN_NAME))
        {
          name = reader.nextString();
        }
        else if(jsonName.equals(MythTrackContract.Titles.COLUMN_DESCRIPTION))
        {
          description = reader.nextString();
        }
        else if(jsonName.equals(MythTrackContract.Titles.COLUMN_MOVEMENT_POINTS))
        {
          movementPoints = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Titles.COLUMN_NON_COMBAT_ACTION))
        {
          nonCombatAction = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Titles.COLUMN_VITALITY))
        {
          vitality = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Titles.COLUMN_IMMUNITIES))
        {
          immunities = reader.nextInt();
        }
        else
        {
          reader.skipValue();
        }
      }
      // Complete title entry processing.
      reader.endObject();
    }
    catch(IOException exception)
    {
      Log.e(TAG, "I/O error while processing an title entry");
      return false;
    }

    // Check that the title is somewhat valid.
    if(name != null && description != null)
    {
      // Build a database entry.
      ContentValues newTitle = new ContentValues();
      newTitle.put(MythTrackContract.Titles.COLUMN_NAME, name);
      newTitle.put(MythTrackContract.Titles.COLUMN_DESCRIPTION, description);
      newTitle.put(MythTrackContract.Titles.COLUMN_MOVEMENT_POINTS, movementPoints);
      newTitle.put(MythTrackContract.Titles.COLUMN_NON_COMBAT_ACTION, nonCombatAction);
      newTitle.put(MythTrackContract.Titles.COLUMN_VITALITY, vitality);
      newTitle.put(MythTrackContract.Titles.COLUMN_IMMUNITIES, immunities);

      // Look for existing titles with the same name.
      String selection = MythTrackContract.Titles.COLUMN_NAME + " = \"" + name + "\"";
      Cursor updateTitle = context.getContentResolver().query(MythTrackContract.Titles.CONTENT_URI,
        MythTrackContract.Titles.PROJECTION_UPDATE_CHECK, selection, null, null);

      // The title doesn't exist, so add a new entry.
      if(updateTitle.getCount() == 0)
      {
        // Close the cursor.
        updateTitle.close();

        // Write the entry to the database.
        context.getContentResolver().insert(MythTrackContract.Titles.CONTENT_URI, newTitle);
        return true;
      }
      // The title exists, so update it instead of adding a new entry;
      else
      {
        // Get the title ID.
        updateTitle.moveToFirst();
        int idColumn = updateTitle.getColumnIndex(MythTrackContract.Titles._ID);
        long titleID = updateTitle.getLong(idColumn);

        // Close the cursor.
        updateTitle.close();

        // Update the title.
        Uri titleURI = Uri.withAppendedPath(MythTrackContract.Titles.CONTENT_URI,
          Long.toString(titleID));
        context.getContentResolver().update(titleURI, newTitle, null, null);
        return true;
      }
    }

    return false;
  }


  /**
   * Process a JSON file with a list of title entries.
   * @param reader The JSON reader that is processing the source JSON file.
   * @return The number of titles successfully processed.
   */
  public int processTitleList(JsonReader reader)
  {
    // Counts how many titles were updated/added.
    int titlesAdded = 0;

    try
    {
      // Start processing the title list.
      reader.beginArray();
      while(reader.hasNext())
      {
        // Process an title entry.
        if(processTitleEntry(reader))
        {
          // Increment the counter if the title was added to the database.
          titlesAdded++;
        }
      }

      // All titles have been processed. Close the reader.
      reader.endArray();
      reader.close();
    }
    catch(IOException exception)
    {
      Log.e(TAG, "An I/O error occurred while processing the titles list");
      return titlesAdded;
    }

    return titlesAdded;
  }


  /**
   * Creates a JSON reader for an titles JSON resource.
   * @param resourceID The ID of the JSON resource.
   * @return JsonReader for the titles JSON resource.
   */
  public JsonReader openTitlesResourceJSON(int resourceID)
  {
    InputStream titleJSONStream = resources.openRawResource(resourceID);
    InputStreamReader titleJSONStreamReader = new InputStreamReader(titleJSONStream);
    return new JsonReader(titleJSONStreamReader);
  }


  /**
   * Creates a JSON reader for an titles JSON file.
   * @param filePath The file path to the JSON file.
   * @return JsonReader for the titles JSON file.
   */
  public JsonReader openTitlesJSON(String filePath)
  {
    InputStream titleJSONStream;
    try
    {
      titleJSONStream = new FileInputStream(filePath);
    }
    catch(FileNotFoundException exception)
    {
      Log.e(TAG, "Could not find file " + filePath);
      return null;
    }

    InputStreamReader titleJSONStreamReader = new InputStreamReader(titleJSONStream);
    return new JsonReader(titleJSONStreamReader);
  }

}




Java Source Code List

nolanjurgens.mythtrack.app.BuyItemDialog.java
nolanjurgens.mythtrack.app.CreateHeroDialog.java
nolanjurgens.mythtrack.app.DeleteHeroDialog.java
nolanjurgens.mythtrack.app.EquipmentInfoDialog.java
nolanjurgens.mythtrack.app.HeroDisplayFragment.java
nolanjurgens.mythtrack.app.HeroHelper.java
nolanjurgens.mythtrack.app.HeroList.java
nolanjurgens.mythtrack.app.HeroTrackerActivity.java
nolanjurgens.mythtrack.app.Hero.java
nolanjurgens.mythtrack.app.InventoryList.java
nolanjurgens.mythtrack.app.ItemHelper.java
nolanjurgens.mythtrack.app.ItemList.java
nolanjurgens.mythtrack.app.Item.java
nolanjurgens.mythtrack.app.MainActivity.java
nolanjurgens.mythtrack.app.RemoveItemDialog.java
nolanjurgens.mythtrack.app.SettingsActivity.java
nolanjurgens.mythtrack.app.SettingsFragment.java
nolanjurgens.mythtrack.app.StatInfoDialog.java
nolanjurgens.mythtrack.app.StatPickerDialog.java
nolanjurgens.mythtrack.app.TitleHelper.java
nolanjurgens.mythtrack.app.Title.java
nolanjurgens.mythtrack.provider.MythTrackBackup.java
nolanjurgens.mythtrack.provider.MythTrackContract.java
nolanjurgens.mythtrack.provider.MythTrackDatabase.java