Back to project page MythTrack.
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.
/** * MainActivity serves as the entry point for the app. */*from w w w .j ava 2s . c o m*/ * @author Nolan Jurgens */ package nolanjurgens.mythtrack.app; // IMPORTS ///////////////////////////////////////////////////////////////////////////////////////// import android.app.Activity; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.JsonReader; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; import nolanjurgens.mythtrack.R; import nolanjurgens.mythtrack.provider.MythTrackContract; //////////////////////////////////////////////////////////////////////////////////////////////////// // CLASS - MainActivity // //////////////////////////////////////////////////////////////////////////////////////////////////// public class MainActivity extends Activity implements CreateHeroDialog.OnHeroCreatedListener, DeleteHeroDialog.OnDeleteHeroConfirmationListener { // CONSTANTS ///////////////////////////////////////////////////////////////////////////////////// /** Item JSON selection intent request code.*/ private static final int SELECT_ITEM_JSON = 1; // FIELDS //////////////////////////////////////////////////////////////////////////////////////// /** Helper for accessing/modifying the "Items" table.*/ private ItemHelper items; /** Helper for accessing/modifying the "Titles" table.*/ private TitleHelper titles; // ASYNCTASKS //////////////////////////////////////////////////////////////////////////////////// // Imports the base game items and titles if the item database table is empty. private class checkForEmptyItemTable extends AsyncTask<Void, Void, Boolean> { /** * Determine if the items table is empty. * @param parameters Not used. * @return True if the table is empty. */ @Override protected Boolean doInBackground(Void... parameters) { // Get a cursor to the item table String[] projection = {MythTrackContract.Items._ID}; Cursor allItems = getContentResolver().query(MythTrackContract.Items.CONTENT_URI, projection, null, null, null); // Count how many items exist already. int existingItems = allItems.getCount(); allItems.close(); return(existingItems == 0); } /** * Imports the base game items and titles if the item table is empty. * @param isEmpty Boolean for if the table is empty. */ @Override protected void onPostExecute(Boolean isEmpty) { // Don't import the base set if the table isn't empty. if(!isEmpty) { return; } // Import the base game items. JsonReader reader = items.openItemsResourceJSON(R.raw.items_base_game); int baseItemsAdded = items.processItemList(reader); // Import the titles. reader = titles.openTitlesResourceJSON(R.raw.titles); titles.processTitleList(reader); // Display a confirmation message. Context context = getApplicationContext(); Resources resources = context.getResources(); String formatMessage = resources.getString(R.string.itemhelper_items_added); String message = String.format(formatMessage, baseItemsAdded); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } // Create a new hero. private class createHero extends AsyncTask<String, Void, Long> { /** * Create a new hero. * @param values The hero's name, followed by the class ID. * @return The new hero's ID. */ @Override protected Long doInBackground(String... values) { if(values.length != 2) { return 0l; } // Get a handle to the hero list. HeroList heroList = (HeroList) getFragmentManager().findFragmentByTag("HeroListFragment"); String heroName = values[0]; int classID = Integer.parseInt(values[1]); return heroList.createHero(heroName, classID); } } // Delete a hero. private class deleteHero extends AsyncTask<Long, Void, Boolean> { /** * Delete the hero with the given ID. * @param heroID The ID of the hero to delete. * @return True if the hero was deleted. */ @Override protected Boolean doInBackground(Long... heroID) { // Get a handle to the hero list. HeroList heroList = (HeroList) getFragmentManager().findFragmentByTag("HeroListFragment"); // Delete the hero. return heroList.deleteHero(heroID[0]); } } // Loads items from a JSON file into the database. private class importItemsTask extends AsyncTask<String, Void, Integer> { /** * Determine if the items table is empty. * @param filePath File path to the JSON file. * @return True if the table is empty. */ @Override protected Integer doInBackground(String... filePath) { JsonReader reader = items.openItemsJSON(filePath[0]); return items.processItemList(reader); } /** * Display how many items were added. * @param itemsAdded The number of items added. */ @Override protected void onPostExecute(Integer itemsAdded) { Context context = getApplicationContext(); Resources resources = context.getResources(); if(itemsAdded == 1) { String formatMessage = resources.getString(R.string.itemhelper_item_added); String message = String.format(formatMessage, itemsAdded); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } else { String formatMessage = resources.getString(R.string.itemhelper_items_added); String message = String.format(formatMessage, itemsAdded); Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } } } // METHODS /////////////////////////////////////////////////////////////////////////////////////// /** * Called when an activity for result returns its result. * @param requestCode The code indicating what kind of result was requested. * @param resultCode The code indicating the status of the request. * @param data The resulting data. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // If an item JSON loaded. if(resultCode == RESULT_OK && requestCode == SELECT_ITEM_JSON) { String jsonFilePath = data.getData().getPath(); // Check if the database is empty. new importItemsTask().execute(jsonFilePath); } } /** * Called when the activity is launched. * @param savedInstanceState Saved instance information. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set default preferences. PreferenceManager.setDefaultValues(this, R.xml.preferences, false); // Set the user interface. setContentView(R.layout.activity_main); // Don't add fragments if resuming from a previous state. if(savedInstanceState != null) { return; } // Add the hero list. FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.add(R.id.main_fragment_container, new HeroList(), "HeroListFragment"); transaction.commit(); // Initialize the Items table helper. items = new ItemHelper(this); // Initialize the Titles table helper. titles = new TitleHelper(this); // Check for an empty Items table. new checkForEmptyItemTable().execute(); } /** * Add items to the action bar. * @param menu The menu that will be populated. * @return Boolean value for if the menu should be shown. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the resource to create the menu. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } /** * Have the HeroList fragment delete the item from the list. * @param heroID ID of the hero to delete. */ @Override public void onDeleteHeroConfirmed(long heroID) { new deleteHero().execute(heroID); } /** * Callback to trigger hero creation with the given values. * @param heroName The hero's name. * @param heroClass The value indicating the hero's class. */ @Override public void onHeroCreated(String heroName, int heroClass) { new createHero().execute(heroName, Integer.toString(heroClass)); } /** * Handle a selected action button. * @param item The item that was selected. * @return Returns true to signal item was processed. */ @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { /*case R.id.action_import_items: { // Open a file browser for user to choose JSON. Intent jsonChooserIntent = new Intent(); jsonChooserIntent.setAction(Intent.ACTION_GET_CONTENT); // FIXME - Google Drive and Downloads cause app crash. jsonChooserIntent.setType("text/plain"); startActivityForResult(jsonChooserIntent, SELECT_ITEM_JSON); return true; }*/ case R.id.action_settings: { Intent settingsIntent = new Intent(this, SettingsActivity.class); startActivity(settingsIntent); } default: { return super.onOptionsItemSelected(item); } } } }