Android Open Source - MythTrack Inventory List






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

/**
 * InventoryList is a fragment that displays a list of items in the hero's inventory and allows
 * the user to equip, use, sell, or remove them as applicable.
 */*from w w  w  .  ja va 2 s .co  m*/
 * @author Nolan Jurgens
 */

package nolanjurgens.mythtrack.app;

// IMPORTS /////////////////////////////////////////////////////////////////////////////////////////
import android.app.ActionBar;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

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

////////////////////////////////////////////////////////////////////////////////////////////////////
// CLASS - InventoryList                                                                          //
////////////////////////////////////////////////////////////////////////////////////////////////////
public class InventoryList extends ListFragment
  implements LoaderManager.LoaderCallbacks<Cursor>
{
  // FIELDS ////////////////////////////////////////////////////////////////////////////////////////

  /**  Object used to control a Contextual Action Bar*/
  protected ActionMode actionMode;
  /** An adapter used to display the inventory list.*/
  private SimpleCursorAdapter adapter;
  /** Helper for accessing/modifying the "Items" table.*/
  private ItemHelper items;
  /** Tracks which item in the list is selected.*/
  private int selectedItem = -1;

  // INTERFACES ////////////////////////////////////////////////////////////////////////////////////

  /** Interface for a listener for when an item is equipped.*/
  OnItemEquippedListener itemEquippedCallback;
  public interface OnItemEquippedListener
  {
    public void onItemEquipped(long inventoryID, int type);
  }

  /** Interface for a listener for when a potion is used.*/
  OnPotionUsedListener potionUsedCallback;
  public interface OnPotionUsedListener
  {
    public void onPotionUsed(long inventoryID, int potionType, String potionName);
  }

  // LISTENERS /////////////////////////////////////////////////////////////////////////////////////

  /** Contextual action mode click listener.*/
  AdapterView.OnItemClickListener contextualActionModeClickListener
    = new AdapterView.OnItemClickListener()
  {
    /**
     * Handle clicks in contextual action mode.
     * @param adapterView The hero list.
     * @param view The item that was clicked.
     * @param position The position of the clicked item in the list.
     * @param inventoryID The inventory ID of the item that was clicked.
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position,
      long inventoryID)
    {
      // Save the position of the selected item.
      selectedItem = position;

      // Get the cursor entry for the selected item.
      Cursor cursor = adapter.getCursor();
      cursor.moveToPosition(selectedItem);

      // Set the item's name as the title.
      String itemName =
        cursor.getString(cursor.getColumnIndex(MythTrackContract.Items.COLUMN_NAME));
      actionMode.setTitle(itemName);
    }
  };


  /** Default item click listener.*/
  AdapterView.OnItemClickListener defaultClickListener = new AdapterView.OnItemClickListener()
  {
    /**
     * Default handling of list item clicks.
     * @param adapterView The hero list.
     * @param view The item that was clicked.
     * @param position The position of the clicked item in the list.
     * @param inventoryID The inventory ID of the item that was clicked.
     * @ True if the click was handled.
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position,
      long inventoryID)
    {
      // Get the cursor entry for the selected item.
      Cursor cursor = adapter.getCursor();
      cursor.moveToPosition(position);

      int itemType = cursor.getInt(cursor.getColumnIndex(MythTrackContract.Items.COLUMN_TYPE));

      if(itemType == MythTrackContract.Items.POTION)
      {
        String potionName
          = cursor.getString(cursor.getColumnIndex(MythTrackContract.Items.COLUMN_NAME));
        int potionType
          = cursor.getInt(cursor.getColumnIndex(MythTrackContract.Items.COLUMN_POTION));
        potionUsedCallback.onPotionUsed(inventoryID, potionType, potionName);
      }
      else
      {
        itemEquippedCallback.onItemEquipped(inventoryID, itemType);
      }
    }
  };


  /** Listener that brings up the contextual action bar on long click.*/
  AdapterView.OnItemLongClickListener defaultLongClickListener
    =  new AdapterView.OnItemLongClickListener()
  {
    /**
     * Brings up the contextual action bar on long clicks.
     * @param adapterView The hero list.
     * @param view The item that was clicked.
     * @param position The position of the clicked item in the list.
     * @param inventoryID The inventory ID of the item that was clicked.
     * @return True if the long click was handled.
     */
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position,
      long inventoryID)
    {

      // Save the position of the selected item.
      selectedItem = position;
      getListView().setItemChecked(selectedItem, true);

      // Check if action mode is already active.
      if(actionMode != null)
      {
        return false;
      }

      // Enter contextual action mode.
      actionMode = getActivity().startActionMode(actionModeCallback);
      view.setSelected(true);

      return true;
    }
  };

  // CONTEXTUAL ACTION MODE ////////////////////////////////////////////////////////////////////////

  /**
   * Defines the methods to handle a contextual action mode callback.
   */
  private ActionMode.Callback actionModeCallback = new ActionMode.Callback()
  {
    /**
     * Create the contextual action bar.
     * @param mode The contextual action mode object.
     * @param menu The contextual menu items.
     * @return Return true to create or false to abort.
     */
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu)
    {
      MenuInflater inflater = mode.getMenuInflater();
      inflater.inflate(R.menu.inventory_list_context, menu);

      return true;
    }


    /**
     * Called each time the contextual action bar is shown.
     * @param mode The contextual action mode object.
     * @param menu The contextual menu items.
     * @return Return true if the menu or action mode was updated or false if they weren't.
     */
    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu)
    {
      // Disable long clicks while in contextual action mode.
      getListView().setOnItemLongClickListener(null);
      // Make single clicks change the selection.
      getListView().setOnItemClickListener(contextualActionModeClickListener);

      // Get the cursor entry for the selected item.
      Cursor cursor = adapter.getCursor();
      cursor.moveToPosition(selectedItem);

      // Set the item's name as the title.
      String itemName =
        cursor.getString(cursor.getColumnIndex(MythTrackContract.Items.COLUMN_NAME));
      mode.setTitle(itemName);

      return true;
    }


    /**
     * Handle the selected contextual action item.
     * @param mode The contextual action mode object.
     * @param item The item that was selected.
     * @return Returns true to signal item was processed or false if it should be passed on.
     */
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item)
    {
      switch(item.getItemId())
      {
        case R.id.action_delete_item:
        {
          // Get the cursor entry for the selected item.
          Cursor cursor = adapter.getCursor();
          cursor.moveToPosition(selectedItem);

          // Build information bundle for dialog.
          long inventoryID
            = cursor.getLong(cursor.getColumnIndex(MythTrackContract.Inventories._ID));
          Item inventoryItem = items.getInventoryItem(inventoryID);
          Bundle arguments = new Bundle();
          arguments.putLong("inventory_id", inventoryID);
          arguments.putBoolean("selling", false);
          arguments.putString("item_name", inventoryItem.getName());
          arguments.putInt("item_value", 0);

          // Create dialog and pass arguments.
          DialogFragment removeItemDialog = new RemoveItemDialog();
          removeItemDialog.setArguments(arguments);

          // Show the dialog.
          FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
          removeItemDialog.show(fragmentTransaction, "RemoveItemDialog");

          // Leave the action mode.
          mode.finish();
          return true;
        }
        case R.id.action_sell_item:
        {
          // Get the cursor entry for the selected item.
          Cursor cursor = adapter.getCursor();
          cursor.moveToPosition(selectedItem);

          // Build information bundle for dialog.
          long inventoryID
            = cursor.getLong(cursor.getColumnIndex(MythTrackContract.Inventories._ID));
          Item inventoryItem = items.getInventoryItem(inventoryID);
          Bundle arguments = new Bundle();
          arguments.putLong("inventory_id", inventoryID);
          arguments.putBoolean("selling", true);
          arguments.putString("item_name", inventoryItem.getName());
          arguments.putInt("item_value", inventoryItem.getSellValue());

          // Create dialog and pass arguments.
          DialogFragment removeItemDialog = new RemoveItemDialog();
          removeItemDialog.setArguments(arguments);

          // Show the dialog.
          FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
          removeItemDialog.show(fragmentTransaction, "RemoveItemDialog");

          // Leave the action mode.
          mode.finish();
          return true;
        }
        default:
        {
          return false;
        }
      }
    }


    /**
     * Called when contextual action mode is exited.
     * @param mode The contextual action mode object.
     */
    @Override
    public void onDestroyActionMode(ActionMode mode)
    {
      // Switch back to default click listeners.
      getListView().setOnItemClickListener(defaultClickListener);
      getListView().setOnItemLongClickListener(defaultLongClickListener);

      // Deselect the item.
      getListView().setItemChecked(selectedItem, false);
      selectedItem = -1;

      // Clear the action mode object.
      actionMode = null;
    }
  };

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

  /**
   * Called after the parent activity is created and the fragment is about to be activated.
   * @param savedInstanceState Saved instance information.
   */
  @Override
  public void onActivityCreated(Bundle savedInstanceState)
  {
    super.onActivityCreated(savedInstanceState);

    // Generate the inventory list and set the fragment to display it.
    adapter =  new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_activated_1,
      null, new String[]{MythTrackContract.Items.COLUMN_NAME},
      new int[]{android.R.id.text1}, 0);

    // Just display the item name without modification for now.
    adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder()
    {
      /**
       * Display the item name. Modifications to inventory entries would go here.
       * @param view The view being processed.
       * @param cursor The inventory list cursor.
       * @param columnIndex The column in the cursor which is being processed.
       * @return True if the data was bound into the view.
       */
      public boolean setViewValue(View view, Cursor cursor, int columnIndex)
      {
        // Get the column indices.
        int nameColumn = cursor.getColumnIndex(MythTrackContract.Items.COLUMN_NAME);
        int castingColumn = cursor.getColumnIndex(MythTrackContract.Items.COLUMN_CASTING);

        // Process the name column.
        if(columnIndex == nameColumn)
        {
          TextView textView = (TextView) view;

          textView.setText(cursor.getString(nameColumn));
          return true;
        }
        return false;
      }
      });

    // Set the list to use the adapter.
    setListAdapter(adapter);
    getLoaderManager().initLoader(R.id.herotracker_fragment_container, null, this);

    // Set up the click listeners.
    getListView().setOnItemClickListener(defaultClickListener);
    getListView().setOnItemLongClickListener(defaultLongClickListener);
  }


  /**
   * Called when the fragment is attached to the activity.
   * @param activity The host activity.
   */
  @Override
  public void onAttach(Activity activity)
  {
    super.onAttach(activity);

    // Make sure the host activity implements the interfaces.
    try
    {
      itemEquippedCallback = (OnItemEquippedListener) activity;
    }
    catch(ClassCastException exception)
    {
      throw new ClassCastException(activity.toString() + " must implement onItemEquipped");
    }
    try
    {
      potionUsedCallback = (OnPotionUsedListener) activity;
    }
    catch(ClassCastException exception)
    {
      throw new ClassCastException(activity.toString() + " must implement onPotionUsed");
    }
  }


  /**
   * Called when the fragment is first created.
   * @param savedInstanceState Saved instance information.
   */
  @Override
  public void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    // Indicate that the fragment will add action bar items.
    setHasOptionsMenu(true);

    // Initialize the hero table helper.
    Context context = getActivity();
    items = new ItemHelper(context);
  }


  /**
   * Add fragment specific items to the action bar menu.
   *
   * @param menu     The menu items are being added to.
   * @param inflater The menu inflater used to create the new items from a menu resource file.
   */
  @Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
  {
    if(getArguments().getInt("type") == MythTrackContract.Items.POTION)
    {
      inflater.inflate(R.menu.inventory_list_potions, menu);
    }
    else
    {
      inflater.inflate(R.menu.inventory_list, menu);
    }

    super.onCreateOptionsMenu(menu, inflater);
  }


  /**
   * Called when the loader is created.
   * @param loaderID ID of the loader.
   * @param bundle A bundle of additional arguments.
   * @return The created loader.
   */
  @Override
  public Loader<Cursor> onCreateLoader(int loaderID, Bundle bundle)
  {
    int itemType = getArguments().getInt("type");
    long heroID = getArguments().getLong("hero_id");

    // Selection clause matches the ID of the loaded hero and the type of the chosen category.
    String selection;
    if(itemType == MythTrackContract.Items.PRIMARY || itemType == MythTrackContract.Items.SECONDARY)
    {
      // Primary/Secondary should also show two-handed weapons.
      selection = MythTrackContract.Inventories.COLUMN_HERO_ID + " = " + heroID + " AND ("
        + MythTrackContract.Items.COLUMN_TYPE + " = " + itemType + " OR "
        + MythTrackContract.Items.COLUMN_TYPE + " = " + MythTrackContract.Items.TWO_HANDED + ")";
    }
    else
    {
      selection = MythTrackContract.Inventories.COLUMN_HERO_ID + " = " + heroID + " AND "
        + MythTrackContract.Items.COLUMN_TYPE + " = " + itemType;
    }

    return new CursorLoader(getActivity(), MythTrackContract.Inventories.CONTENT_URI,
      MythTrackContract.Inventories.PROJECTION_LIST, selection, null,
      MythTrackContract.Inventories.SORT_ORDER_NAME);
  }


  /**
   * Called when the fragment is about to be drawn for the first time.
   * @param inflater The layout inflater.
   * @param container The parent fragment container.
   * @param savedInstanceState Saved instance information.
   * @return The created view.
   */
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
    // Set the subtitle
    ActionBar actionBar = getActivity().getActionBar();
    if(actionBar != null)
    {
      getActivity().getActionBar().setSubtitle(R.string.inventorylist_subtitle);
    }

    return inflater.inflate(R.layout.fragment_inventory_list, container, false);
  }


  /**
   * Called when the loader finishes loading the cursor.
   * @param cursorLoader The cursor loader.
   * @param cursor The cursor being loaded.
   */
  @Override
  public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor)
  {
    // Swap in the newly loaded cursor.
    adapter.swapCursor(cursor);
  }


  /**
   * Called when the cursor data is being released.
   * @param cursorLoader The cursor loader.
   */
  @Override
  public void onLoaderReset(Loader<Cursor> cursorLoader)
  {
    // Release the cursor that's about to be closed.
    adapter.swapCursor(null);
  }


  /**
   * Handle a selected action button.
   *
   * @param item The item that was selected.
   *
   * @return Returns true to signal item was processed or false if it should be passed on.
   */
  @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
    switch(item.getItemId())
    {
      case R.id.action_add_item:
      {
        long heroID = getArguments().getLong("hero_id");
        int itemType = getArguments().getInt("type");

        ItemList itemList = new ItemList();
        Bundle bundle = new Bundle();
        bundle.putLong("hero_id", heroID);
        bundle.putInt("type", itemType);
        itemList.setArguments(bundle);

        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.herotracker_fragment_container, itemList, "Item List");
        transaction.addToBackStack(null);
        transaction.commit();
        return true;
      }
      case R.id.action_unequip_item:
      {
        int itemType = getArguments().getInt("type");
        itemEquippedCallback.onItemEquipped(0, itemType);
        return true;
      }
      default:
      {
        return super.onOptionsItemSelected(item);
      }
    }
  }


  /**
   * Called when the fragment is being removed or replaced.
   */
  @Override
  public void onPause()
  {
    super.onPause();

    // Close the contextual action bar if one is open.
    if(actionMode != null)
    {
      actionMode.finish();
    }
  }

}




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