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

/**
 * HeroList is a fragment that displays a list of heroes stored in the database and launches
 * other fragments/activities to manipulate them.
 *//from w w w. java 2  s.co  m
 * @author Nolan Jurgens
 */

package nolanjurgens.mythtrack.app;

// IMPORTS /////////////////////////////////////////////////////////////////////////////////////////
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
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 - HeroList                                                                               //
////////////////////////////////////////////////////////////////////////////////////////////////////
public class HeroList extends ListFragment
  implements LoaderManager.LoaderCallbacks<Cursor>
{
  // FIELDS ////////////////////////////////////////////////////////////////////////////////////////

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

  // 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 heroID The ID of the hero that was clicked.
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long heroID)
    {
      // Save the position of the selected item.
      selectedItem = position;

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

      // Set the hero's name as the title.
      String heroName =
        cursor.getString(cursor.getColumnIndex(MythTrackContract.Heroes.COLUMN_NAME));
      actionMode.setTitle(heroName);
    }
  };


  /** 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 heroID The ID of the hero that was clicked.
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long heroID)
    {
      Intent heroTrackerIntent = new Intent(getActivity(), HeroTrackerActivity.class);
      heroTrackerIntent.putExtra("hero_id", heroID);
      startActivity(heroTrackerIntent);
    }
  };


  /** 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 heroID The ID of the hero that was clicked.
     * @return True if the long click was handled.
     */
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long heroID)
    {

      // 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.hero_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 hero.
      Cursor cursor = adapter.getCursor();
      cursor.moveToPosition(selectedItem);

      // Set the hero's name as the title.
      String heroName =
        cursor.getString(cursor.getColumnIndex(MythTrackContract.Heroes.COLUMN_NAME));
      mode.setTitle(heroName);

      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_hero:
        {
          // Get the cursor entry for the selected hero.
          Cursor cursor = adapter.getCursor();
          cursor.moveToPosition(selectedItem);

          // Get the information for the selected hero.
          long heroID = cursor.getLong(cursor.getColumnIndex(MythTrackContract.Heroes._ID));
          String heroName =
            cursor.getString(cursor.getColumnIndex(MythTrackContract.Heroes.COLUMN_NAME));
          int heroClassID =
            cursor.getInt(cursor.getColumnIndex(MythTrackContract.Heroes.COLUMN_CLASS_ID));
          String heroClass;
          switch(heroClassID)
          {
            case MythTrackContract.Heroes.ACOLYTE:
            {
              heroClass = getString(R.string.acolyte);
              break;
            }
            case MythTrackContract.Heroes.APPRENTICE:
            {
              heroClass = getString(R.string.apprentice);
              break;
            }
            case MythTrackContract.Heroes.ARCHER:
            {
              heroClass = getString(R.string.archer);
              break;
            }
            case MythTrackContract.Heroes.BRIGAND:
            {
              heroClass = getString(R.string.brigand);
              break;
            }
            case MythTrackContract.Heroes.DRUID:
            {
              heroClass = getString(R.string.druid);
              break;
            }
            case MythTrackContract.Heroes.SKALD:
            {
              heroClass = getString(R.string.skald);
              break;
            }
            case MythTrackContract.Heroes.SOLDIER:
            {
              heroClass = getString(R.string.soldier);
              break;
            }
            case MythTrackContract.Heroes.SPRIGGAN:
            {
              heroClass = getString(R.string.spriggan);
              break;
            }
            case MythTrackContract.Heroes.TRICKSTER:
            {
              heroClass = getString(R.string.trickster);
              break;
            }
            default:
            {
              heroClass = getString(R.string.invalid_class);
              break;
            }
          }


          // Put the information into a bundle.
          Bundle heroInformation = new Bundle();
          heroInformation.putLong("id", heroID);
          heroInformation.putString("name", heroName);
          heroInformation.putString("class", heroClass);

          // Create the fragment and pass the bundle as an argument.
          DialogFragment deleteHeroDialog = new DeleteHeroDialog();
          deleteHeroDialog.setArguments(heroInformation);

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

          // 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;
    }
  };


  /**
   * Create a new hero.
   * @param heroName The hero's name.
   * @param heroClass The hero's class.
   * @return The new hero's ID.
   */
  public long createHero(String heroName, int heroClass)
  {
    // Create the hero.
    Uri heroURI = heroes.addHero(heroName, heroClass);

    // Start the hero off at full vitality.
    long heroID = Long.parseLong(heroURI.getLastPathSegment());
    Hero newHero = new Hero(getActivity());
    heroes.loadHero(newHero, heroID);
    int baseVitality = newHero.getBaseVitality();
    int vitalityModifier = newHero.getVitalityModifier();
    newHero.setVitality(baseVitality + vitalityModifier);
    heroes.saveHeroStats(newHero);

    return heroID;
  }

  /**
   * Delete the hero at the given position.
   * @param heroID ID of the hero to delete.
   * @return True if hero was deleted.
   */
  public boolean deleteHero(long heroID)
  {
    return heroes.deleteHero(heroID);
  }


  /**
   * 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 hero list and set the fragment to display it.
    adapter =
      new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_activated_1, null,
        new String[]{MythTrackContract.Heroes.COLUMN_NAME}, new int[]{android.R.id.text1}, 0);

    // Add class information to the hero entries.
    adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder()
    {
      /**
       * Add the hero's class icon and class label to their list entry.
       * @param view The view being processed.
       * @param cursor The hero 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.Heroes.COLUMN_NAME);
        int classIDColumn = cursor.getColumnIndex(MythTrackContract.Heroes.COLUMN_CLASS_ID);

        // Process the name column.
        if(columnIndex == nameColumn)
        {
          TextView textView = (TextView) view;
          String text;
          int classIcon = 0;

          // Add the hero class information.
          switch(cursor.getInt(classIDColumn))
          {
            case MythTrackContract.Heroes.ACOLYTE:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.acolyte);
              classIcon = R.drawable.ic_class_acolyte;
              break;
            }
            case MythTrackContract.Heroes.APPRENTICE:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.apprentice);
              classIcon = R.drawable.ic_class_apprentice;
              break;
            }
            case MythTrackContract.Heroes.ARCHER:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.archer);
              classIcon = R.drawable.ic_class_archer;
              break;
            }
            case MythTrackContract.Heroes.BRIGAND:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.brigand);
              classIcon = R.drawable.ic_class_brigand;
              break;
            }
            case MythTrackContract.Heroes.DRUID:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.druid);
              classIcon = R.drawable.ic_class_spriggan;
              break;
            }
            case MythTrackContract.Heroes.SKALD:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.skald);
              classIcon = R.drawable.ic_class_skald;
              break;
            }
            case MythTrackContract.Heroes.SOLDIER:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.soldier);
              classIcon = R.drawable.ic_class_soldier;
              break;
            }
            case MythTrackContract.Heroes.SPRIGGAN:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.spriggan);
              classIcon = R.drawable.ic_class_spriggan;
              break;
            }
            case MythTrackContract.Heroes.TRICKSTER:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.trickster);
              classIcon = R.drawable.ic_class_trickster;
              break;
            }
            default:
            {
              text = cursor.getString(nameColumn) + " - " + getString(R.string.invalid_class);
            }
          }

          textView.setText(text);
          if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
          {
            textView.setCompoundDrawablesRelativeWithIntrinsicBounds(classIcon, 0, 0, 0);
          }
          else
          {
            textView.setCompoundDrawablesWithIntrinsicBounds(classIcon, 0, 0, 0);
          }

          return true;
        }
        return false;
      }
    });

    // Set the list to use the adapter.
    setListAdapter(adapter);
    int heroListID = getFragmentManager().findFragmentByTag("HeroListFragment").getId();
    getLoaderManager().initLoader(heroListID, null, this);

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


  /**
   * 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 Heroes table helper.
    heroes = new HeroHelper(getActivity());
  }


  /**
   * 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)
  {
    inflater.inflate(R.menu.hero_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)
  {
    return new CursorLoader(getActivity(), MythTrackContract.Heroes.CONTENT_URI,
      MythTrackContract.Heroes.PROJECTION_LIST, null, null,
      MythTrackContract.Heroes.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)
  {
    return inflater.inflate(R.layout.fragment_hero_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_create_hero:
      {
        DialogFragment createHeroDialog = new CreateHeroDialog();
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        createHeroDialog.show(fragmentTransaction, "CreateHeroDialog");
        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