Android Open Source - MythTrack Item 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

/**
 * ItemHelper simplifies the management of the "Items" table in the database.
 *//ww  w.  ja v a  2s  .c o  m
 * @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 - ItemHelper                                                                             //
////////////////////////////////////////////////////////////////////////////////////////////////////
public class ItemHelper
{
  // CONSTANTS /////////////////////////////////////////////////////////////////////////////////////

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

  // Additional relevant constants in MythTrackContract.Items 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 ItemHelper(Context context)
  {
    // Get handle to the context and resources.
    this.context = context;
    resources = context.getResources();
  }

  /**
   * Loads the attributes for an inventory item from the database into an Item object.
   * @param inventoryID The inventory ID of the requested item.
   * @return The Item that was retrieved.
   */
  public Item getInventoryItem(long inventoryID)
  {
    long itemID;

    // Get the item ID for the inventory ID.
    if(inventoryID == 0)
    {
      itemID = 0;
    }
    else
    {
      Uri inventoryURI = Uri.withAppendedPath(MythTrackContract.Inventories.CONTENT_URI,
        Long.toString(inventoryID));
      Cursor inventoryCursor = context.getContentResolver().query(inventoryURI,
        MythTrackContract.Inventories.PROJECTION_ITEM_LOAD, null, null, null);
      int itemIDColumn
        = inventoryCursor.getColumnIndex(MythTrackContract.Inventories.COLUMN_ITEM_ID);
      if(inventoryCursor.getCount() == 0)
      {
        itemID = 0;
      }
      else
      {
        inventoryCursor.moveToFirst();
        itemID = inventoryCursor.getLong(itemIDColumn);
      }
      inventoryCursor.close();
    }

    // Use getItem to get the Item object.
    return getItem(itemID);
  }

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

    // Initialize the item.
    item.setID(0);
    item.setName(resources.getString(R.string.itemhelper_no_item));
    item.setType(0);
    item.setRarity(0);
    item.setCasting(0);
    item.setRange(0);
    item.setBuyCost(0);
    item.setSellValue(0);
    item.setHitDiceModifier(0);
    item.setFateDiceModifier(0);
    item.setOffensiveModifier(0);
    item.setDefensiveModifier(0);
    item.setMovementPointsModifier(0);
    item.setCautiousMovementModifier(0);
    item.setCourageModifier(0);
    item.setMinThreat(0);
    item.setMaxThreat(10);
    item.setVitalityModifier(0);
    item.setFaithModifier(0);
    item.setAmmoCapacity(0);
    item.setVersesCapability(0);
    item.setRageModifier(0);
    item.setDurabilityBase(0);
    item.setDurabilityCurrent(0);
    item.setEssenceBase(0);
    item.setEssenceCurrent(0);
    item.setPartsCapacity(0);
    item.setPotionID(0);
    item.setImmunities(0);
    item.setNonCombatActionModifier(0);

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

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

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

    // ID
    int idColumn = targetItem.getColumnIndex(MythTrackContract.Items._ID);
    long id = targetItem.getLong(idColumn);
    item.setID(id);

    // Name
    int nameColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_NAME);
    String name = targetItem.getString(nameColumn);
    item.setName(name);

    // Type
    int typeColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_TYPE);
    int type = targetItem.getInt(typeColumn);
    item.setType(type);

    // Rarity
    int rarityColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_RARITY);
    int rarity = targetItem.getInt(rarityColumn);
    item.setRarity(rarity);

    // Casting
    int castingColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_CASTING);
    int casting = targetItem.getInt(castingColumn);
    item.setCasting(casting);

    // Range
    int rangeColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_RANGE);
    int range = targetItem.getInt(rangeColumn);
    item.setRange(range);
    
    // Buy Cost
    int buyColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_BUY);
    int buy = targetItem.getInt(buyColumn);
    item.setBuyCost(buy);

    // Sell Value
    int sellColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_SELL);
    int sell = targetItem.getInt(sellColumn);
    item.setSellValue(sell);

    // Hit Dice Modifier
    int hitDiceColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_HIT_DICE);
    int hitDice = targetItem.getInt(hitDiceColumn);
    item.setHitDiceModifier(hitDice);

    // Fate Dice Modifier
    int fateDiceColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_FATE_DICE);
    int fateDice = targetItem.getInt(fateDiceColumn);
    item.setFateDiceModifier(fateDice);

    // Offensive Target Number Modifier
    int offenseColumn =
      targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_OFFENSE);
    int offense = targetItem.getInt(offenseColumn);
    item.setOffensiveModifier(offense);

    // Defensive Target Number Modifier
    int defenseColumn =
      targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_DEFENSE);
    int defense = targetItem.getInt(defenseColumn);
    item.setDefensiveModifier(defense);

    // Movement Points Modifier
    int movementPointsColumn 
      = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_MOVEMENT_POINTS);
    int movementPoints = targetItem.getInt(movementPointsColumn);
    item.setMovementPointsModifier(movementPoints);

    // Cautious Movement Modifier
    int cautiousMovementColumn
      = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_CAUTIOUS_MOVEMENT);
    int cautiousMovement = targetItem.getInt(cautiousMovementColumn);
    item.setCautiousMovementModifier(cautiousMovement);

    // Non-Combat Action
    int nonCombatActionColumn
      = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_NON_COMBAT_ACTION);
    int nonCombatAction = targetItem.getInt(nonCombatActionColumn);
    item.setNonCombatActionModifier(nonCombatAction);

    // Courage Modifier
    int courageColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_COURAGE);
    int courage = targetItem.getInt(courageColumn);
    item.setCourageModifier(courage);

    // Minimum Threat Modifier
    int minThreatColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_MIN_THREAT);
    int minThreat = targetItem.getInt(minThreatColumn);
    item.setMinThreat(minThreat);

    // Maximum Threat Modifier
    int maxThreatColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_MAX_THREAT);
    int maxThreat = targetItem.getInt(maxThreatColumn);
    item.setMaxThreat(maxThreat);
    
    // Vitality Modifier
    int vitalityColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_VITALITY);
    int vitality = targetItem.getInt(vitalityColumn);
    item.setVitalityModifier(vitality);

    // Faith Modifier
    int faithColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_FAITH);
    int faith = targetItem.getInt(faithColumn);
    item.setFaithModifier(faith);

    // Ammo Capacity
    int ammoColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_AMMO);
    int ammo = targetItem.getInt(ammoColumn);
    item.setAmmoCapacity(ammo);

    // Verses Capability
    int versesColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_VERSES);
    int verses = targetItem.getInt(versesColumn);
    item.setVersesCapability(verses);

    // Rage Modifier
    int rageColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_RAGE);
    int rage = targetItem.getInt(rageColumn);
    item.setRageModifier(rage);

    // Essence
    int essenceColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_ESSENCE);
    int essence = targetItem.getInt(essenceColumn);
    item.setEssenceBase(essence);
    item.setEssenceCurrent(essence);
    
    // Durability
    int durabilityColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_DURABILITY);
    int durability = targetItem.getInt(durabilityColumn);
    item.setDurabilityBase(durability);
    item.setDurabilityCurrent(durability);

    // Parts Capacity
    int partsColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_PARTS);
    int parts = targetItem.getInt(partsColumn);
    item.setPartsCapacity(parts);

    // Potion ID
    int potionIDColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_POTION);
    int potionID = targetItem.getInt(potionIDColumn);
    item.setPotionID(potionID);

    // Immunities
    int immunitiesColumn = targetItem.getColumnIndex(MythTrackContract.Items.COLUMN_IMMUNITIES);
    int immunities = targetItem.getInt(immunitiesColumn);
    item.setImmunities(immunities);

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

    return item;
  }


  /**
   * Process the JSON entry for a single item and create a new item in the database.
   * @param reader The JSON reader that is processing the source JSON file.
   * @return True if the item was added successfully.
   */
  public boolean processItemEntry(JsonReader reader)
  {
    String name = null;
    int source = 0;
    int type = 0;
    int rarity = 0;
    int casting = 0;
    int range = 0;
    int buy = 0;
    int sell = 0;
    int hitDice = 0;
    int fateDice = 0;
    int offense = 0;
    int defense = 0;
    int movementPoints = 0;
    int cautiousMovement = 0;
    int nonCombatAction = 0;
    int courage = 0;
    int minThreat = 0;
    int maxThreat = 10;
    int vitality = 0;
    int faith = 0;
    int ammo = 0;
    int verses = 0;
    int rage = 0;
    int essence = 0;
    int durability = 0;
    int parts = 0;
    int potionID = 0;
    int immunities = 0;

    try
    {
      // Begin processing the item entry.
      reader.beginObject();
      // Process each name/value pair.
      while(reader.hasNext())
      {
        String jsonName = reader.nextName();
        if(jsonName.equals(MythTrackContract.Items.COLUMN_NAME))
        {
          name = reader.nextString();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_SOURCE))
        {
          source = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_TYPE))
        {
          type = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_RARITY))
        {
          rarity = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_CASTING))
        {
          casting = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_RANGE))
        {
          range = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_BUY))
        {
          buy = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_SELL))
        {
          sell = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_HIT_DICE))
        {
          hitDice = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_FATE_DICE))
        {
          fateDice = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_OFFENSE))
        {
          offense = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_DEFENSE))
        {
          defense = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_MOVEMENT_POINTS))
        {
          movementPoints = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_CAUTIOUS_MOVEMENT))
        {
          cautiousMovement = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_NON_COMBAT_ACTION))
        {
          nonCombatAction = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_COURAGE))
        {
          courage = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_MIN_THREAT))
        {
          minThreat = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_MAX_THREAT))
        {
          maxThreat = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_VITALITY))
        {
          vitality = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_FAITH))
        {
          faith = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_AMMO))
        {
          ammo = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_VERSES))
        {
          verses = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_RAGE))
        {
          rage = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_ESSENCE))
        {
          essence = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_DURABILITY))
        {
          durability = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_PARTS))
        {
          parts = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_POTION))
        {
          potionID = reader.nextInt();
        }
        else if(jsonName.equals(MythTrackContract.Items.COLUMN_IMMUNITIES))
        {
          immunities = reader.nextInt();
        }
        else
        {
          reader.skipValue();
        }
      }
      // Complete item entry processing.
      reader.endObject();
    }
    catch(IOException exception)
    {
      Log.e(TAG, "I/O error while processing an item entry");
      return false;
    }

    // Check that the item is somewhat valid.
    if(name != null && source != 0 && type != 0 && rarity != 0)
    {
      // Build a database entry.
      ContentValues newItem = new ContentValues();
      newItem.put(MythTrackContract.Items.COLUMN_NAME, name);
      newItem.put(MythTrackContract.Items.COLUMN_SOURCE, source);
      newItem.put(MythTrackContract.Items.COLUMN_TYPE, type);
      newItem.put(MythTrackContract.Items.COLUMN_RARITY, rarity);
      newItem.put(MythTrackContract.Items.COLUMN_CASTING, casting);
      newItem.put(MythTrackContract.Items.COLUMN_RANGE, range);
      newItem.put(MythTrackContract.Items.COLUMN_BUY, buy);
      newItem.put(MythTrackContract.Items.COLUMN_SELL, sell);
      newItem.put(MythTrackContract.Items.COLUMN_HIT_DICE, hitDice);
      newItem.put(MythTrackContract.Items.COLUMN_FATE_DICE, fateDice);
      newItem.put(MythTrackContract.Items.COLUMN_OFFENSE, offense);
      newItem.put(MythTrackContract.Items.COLUMN_DEFENSE, defense);
      newItem.put(MythTrackContract.Items.COLUMN_MOVEMENT_POINTS, movementPoints);
      newItem.put(MythTrackContract.Items.COLUMN_CAUTIOUS_MOVEMENT, cautiousMovement);
      newItem.put(MythTrackContract.Items.COLUMN_NON_COMBAT_ACTION, nonCombatAction);
      newItem.put(MythTrackContract.Items.COLUMN_COURAGE, courage);
      newItem.put(MythTrackContract.Items.COLUMN_MIN_THREAT, minThreat);
      newItem.put(MythTrackContract.Items.COLUMN_MAX_THREAT, maxThreat);
      newItem.put(MythTrackContract.Items.COLUMN_VITALITY, vitality);
      newItem.put(MythTrackContract.Items.COLUMN_FAITH, faith);
      newItem.put(MythTrackContract.Items.COLUMN_AMMO, ammo);
      newItem.put(MythTrackContract.Items.COLUMN_VERSES, verses);
      newItem.put(MythTrackContract.Items.COLUMN_RAGE, rage);
      newItem.put(MythTrackContract.Items.COLUMN_ESSENCE, essence);
      newItem.put(MythTrackContract.Items.COLUMN_DURABILITY, durability);
      newItem.put(MythTrackContract.Items.COLUMN_PARTS, parts);
      newItem.put(MythTrackContract.Items.COLUMN_POTION, potionID);
      newItem.put(MythTrackContract.Items.COLUMN_IMMUNITIES, immunities);

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

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

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

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

        // Update the item.
        Uri itemURI = Uri.withAppendedPath(MythTrackContract.Items.CONTENT_URI,
          Long.toString(itemID));
        context.getContentResolver().update(itemURI, newItem, null, null);
        return true;
      }
    }

    return false;
  }


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

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

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

    return itemsAdded;
  }


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


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

    InputStreamReader itemJSONStreamReader = new InputStreamReader(itemJSONStream);
    return new JsonReader(itemJSONStreamReader);
  }

}




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