com.jea.gisandroidapplication.controller.activity.MapActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.jea.gisandroidapplication.controller.activity.MapActivity.java

Source

package com.jea.gisandroidapplication.controller.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.esri.android.runtime.ArcGISRuntime;
import com.jea.gisandroidapplication.R;
import com.jea.gisandroidapplication.controller.fragment.BasemapDialogFragment;
import com.jea.gisandroidapplication.controller.fragment.ElectricItemDialogFragment;
import com.jea.gisandroidapplication.controller.fragment.MapFragment;
import com.jea.gisandroidapplication.controller.fragment.ResultFragment;
import com.jea.gisandroidapplication.controller.fragment.ResultListFragment;
import com.jea.gisandroidapplication.model.Result;
import com.jea.gisandroidapplication.services.FMSDataService;
import com.jea.gisandroidapplication.util.NavDrawerHelper;
import com.jea.gisandroidapplication.util.PopulateHelper;
import com.jea.gisandroidapplication.view.AnimatedExpandableListView;
import com.jea.gisandroidapplication.view.ChildItem;
import com.jea.gisandroidapplication.view.ExpandedListAdapter;

import java.util.ArrayList;

/**
 * @author Andy Leekung
 * @version 1.0
 * @since 5/22/2015
 */
public class MapActivity extends AppCompatActivity {

    // Tags
    private static final String TAG = "MapActivity";
    private static final String DIALOG_BASEMAP_TAG = "ChangeBasemap";
    private static final String DIALOG_ELECTRIC_ITEM_TAG = "FindElectricItem";

    // Child Activities
    public static final int SETTINGS_REQUEST = 0;
    public static final int FIND_REQUEST = 1;
    public static final int STREET_VIEW_REQUEST = 2;
    public static final int GOOGLE_ERROR_DIALOG_REQUEST = 3;
    public static final int LAYER_MANAGER_REQUEST = 4;

    // Fragment manager
    private FragmentManager mFm;

    // Map Fragment
    private MapFragment mMapFragment;

    private TextView mCurrentToolText;

    private SharedPreferences sharedPref;

    // Navigation Drawer Views
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerLayout mDrawerLayout;
    private RelativeLayout mNavigationDrawer;
    private AnimatedExpandableListView mDrawerList;
    private ExpandedListAdapter mAdapter;

    // Results layout
    private FrameLayout mResultsLayout;

    // Floating Action Button
    private FloatingActionButton mFabCurrentLocation;

    // Radio button resource ID from BasemapDialogFragment of the current
    // basemap
    private int mBasemapId;

    // Preferences
    private boolean mLocationPref;

    // Results showing
    private boolean mResultsShowing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // License for ArcGIS Runtime SDK
        ArcGISRuntime.setClientId("ri4VSTqPIEA8du7X");
        setContentView(R.layout.activity_map);

        // Add a toggle switch in the Action Bar
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        // Get preferences
        sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        mLocationPref = sharedPref.getBoolean(getResources().getString(R.string.pref_location_key), true);

        // Handle fragments
        mFm = getSupportFragmentManager();

        mMapFragment = (MapFragment) mFm.findFragmentById(R.id.container_map_fragment);

        if (mMapFragment == null) {
            // Create a new MapFragment
            mMapFragment = MapFragment.newInstance();
            mBasemapId = 0;
            mFm.beginTransaction().add(R.id.container_map_fragment, mMapFragment).commit();

        }

        // Get references to navigation drawer components
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mNavigationDrawer = (RelativeLayout) findViewById(R.id.navigation_drawer);
        mDrawerList = (AnimatedExpandableListView) findViewById(R.id.navigation_drawer_list);
        mCurrentToolText = (TextView) findViewById(R.id.text_current_tool);

        // Get references to results layout
        mResultsLayout = (FrameLayout) findViewById(R.id.frame_result);

        // Set up navigation drawer
        initDrawer();

        // Get data from web services
        PopulateHelper.get(getApplicationContext());

        // Handle FAB
        mFabCurrentLocation = (FloatingActionButton) findViewById(R.id.fab_current_location);
        mFabCurrentLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMapFragment.zoomToCurrentLocation();
            }
        });
        toggleLocFabVisibility();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Activate Navigation Drawer
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        // Handle menu item selection.
        switch (item.getItemId()) {
        case R.id.menu_settings:
            Intent i = new Intent(MapActivity.this, SettingsActivity.class);
            startActivityForResult(i, SETTINGS_REQUEST);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check which request we're responding to
        if (requestCode == SETTINGS_REQUEST) {
            // Preferences changed
            // Check for change
            if (mLocationPref != sharedPref.getBoolean(SettingsActivity.KEY_PREF_LOCATION, true)) {
                mLocationPref = sharedPref.getBoolean(SettingsActivity.KEY_PREF_LOCATION, true);
                // Turn off location for fragment
                mMapFragment.toggleLocation();
                // Hide location FAB
                toggleLocFabVisibility();
            }
        } else if (requestCode == FIND_REQUEST) {
            if (resultCode == RESULT_OK) {
                // Close navigation drawer
                closeDrawer();
                // Get results from data intent
                ArrayList<Result> results = data.getParcelableArrayListExtra(FindActivity.EXTRA_RESULTS);
                // Display results
                displayResults(results);
            }
        } else if (requestCode == STREET_VIEW_REQUEST) {
            // Required?
        } else if (requestCode == GOOGLE_ERROR_DIALOG_REQUEST) {
            // ?
        } else if (requestCode == LAYER_MANAGER_REQUEST) {
            if (resultCode == RESULT_OK) {
                boolean isAdd = data.getBooleanExtra(LayerManagerActivity.EXTRA_LAYER_ISADD, true);
                String layerName = data.getStringExtra(LayerManagerActivity.EXTRA_LAYER_NAME);
                if (isAdd) {
                    mMapFragment.addExtraLayer(layerName);
                } else {
                    // Remove
                    mMapFragment.removeLayer(layerName);
                }

            }
        }

    }

    @Override
    public void onBackPressed() {
        // Close drawer then results then activity
        if (mDrawerLayout.isDrawerOpen(mNavigationDrawer)) {
            closeDrawer();
        } else if (mResultsShowing) {
            toggleResults(false);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Executes actions for all the child clicks
     * @param c ChildItem clicked
     * @return Child Item clicked
     */
    private boolean childClickOptions(ChildItem c) {
        // Get the resource id for the string of the title
        int childResId = c.getTitle();
        switch (childResId) {
        /********************** Map Tools Children **********************/
        case R.string.identify:
            mMapFragment.changeCurrentTool(R.string.identify);
            return true;
        case R.string.bookmarks:
            identifyClick(c);
            return true;
        case R.string.layer_manager:
            startLayerManagerActivity();
            return true;
        case R.string.delete_graphics:
            mMapFragment.removeGraphics();
            Toast.makeText(this, R.string.graphics_deleted, Toast.LENGTH_SHORT).show();
            return true;
        case R.string.change_basemap:
            BasemapDialogFragment dialogBasemap = BasemapDialogFragment.newInstance(mBasemapId);
            dialogBasemap.show(mFm, DIALOG_BASEMAP_TAG);
            return true;
        /********************** Utilities Children **********************/
        case R.string.google_street_view:
            mMapFragment.changeCurrentTool(R.string.google_street_view);
            return true;
        case R.string.google_maps_nav:
            mMapFragment.changeCurrentTool(R.string.google_maps_nav);
            return true;
        case R.string.sketcher:
            mMapFragment.changeCurrentTool(R.string.sketcher);
            return true;
        case R.string.measure:
            mMapFragment.changeCurrentTool(R.string.measure);
            return true;
        /******************* Electric Tools Children ********************/
        case R.string.show_electric_layer:
            mMapFragment.toggleElectricLayer();
            return true;
        case R.string.outages:
            new FMSDataService.GetOutagesTask(this).execute();
            return true;
        case R.string.find_electric_item:
            ElectricItemDialogFragment dialogElectricItem = ElectricItemDialogFragment.newInstance();
            dialogElectricItem.show(mFm, DIALOG_ELECTRIC_ITEM_TAG);
            return true;
        /********************* Water Tools Children *********************/
        case R.string.show_water_layer:
            mMapFragment.toggleWaterLayer();
            return true;
        case R.string.find_water_plant:
            startFindActivity(R.string.water_plant);
            return true;
        /********************* Sewer Tools Children *********************/
        case R.string.show_sewer_layer:
            mMapFragment.toggleSewerLayer();
            return true;
        case R.string.find_sewer_plant:
            startFindActivity(R.string.sewer_plant);
            return true;
        case R.string.find_pump_station:
            startFindActivity(R.string.pump_station);
            return true;
        /********************** Customers Children **********************/
        case R.string.show_customers:
            mMapFragment.togglePremiseLayer();
            return true;
        case R.string.find_customer:
            startFindActivity(R.string.customer);
            return true;
        case R.string.find_address:
            startFindActivity(R.string.address);
            return true;
        /******************* Advanced Tools Children ********************/
        case R.string.spatial_query:
            identifyClick(c);
            return true;
        case R.string.attribute_query:
            identifyClick(c);
            return true;
        case R.string.buffer_query:
            identifyClick(c);
            return true;
        case R.string.advanced_identify:
            identifyClick(c);
            return true;
        default:
            identifyClick(c);
            return true;
        }
    }

    /**
     * Testing method to see which child is clicked
     * @param c Child clicked
     */
    private void identifyClick(ChildItem c) {
        Toast.makeText(MapActivity.this, c.getChildHolder().getTextView().getText() + " was " + "clicked",
                Toast.LENGTH_SHORT).show();
    }

    /**
     * Handles and sets up the navigation drawer
     */
    private void initDrawer() {
        // Adds Group Items into the navigation drawer
        mAdapter = new ExpandedListAdapter(this);
        mAdapter.setData(NavDrawerHelper.getDrawerItems());
        mDrawerList.setAdapter(mAdapter);

        // In order to show animations, we need to use a custom click handler
        // for our ExpandableListView.
        mDrawerList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                // We call collapseGroupWithAnimation(int) and
                // expandGroupWithAnimation(int) to animate group
                // expansion/collapse.
                if (mDrawerList.isGroupExpanded(groupPosition)) {
                    mDrawerList.collapseGroupWithAnimation(groupPosition);
                } else {
                    mDrawerList.expandGroupWithAnimation(groupPosition);
                }
                return true;
            }
        });

        // Handles the selection of the children
        mDrawerList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition,
                    long id) {
                ChildItem c = mAdapter.getChild(groupPosition, childPosition);
                // Handle all the different child clicks
                return childClickOptions(c);
            }
        });

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open,
                R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle(R.string.nav_drawer_title);
                // Change Options Menu? Calls onPrepareOptionsMenu()
                invalidateOptionsMenu();
            }

            @Override
            //Called when a drawer has settled in a completely closed state.
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                //Set title of the activity
                getSupportActionBar().setTitle(R.string.app_name);
                invalidateOptionsMenu();
            }
        };

        mDrawerToggle.setDrawerIndicatorEnabled(true);
        mDrawerLayout.setDrawerListener(mDrawerToggle);

    }

    /**
     * Closes the navigation drawer
     */
    public void closeDrawer() {
        mDrawerLayout.closeDrawers();
    }

    /**
     * Toggles the visibility of the results fragment
     * @param showResults If the results should be displayed
     */
    private void toggleResults(boolean showResults) {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mResultsLayout.getLayoutParams();
        layoutParams.weight = showResults ? 4 : 0;
        mResultsShowing = showResults;
        mResultsLayout.setLayoutParams(layoutParams);
    }

    /**
     * Displays results fragment with multiple results
     * @param results List of results
     */
    public void displayResults(ArrayList<Result> results) {
        // Display single result fragment if array list only contains 1 result
        if (results.size() == 0) {
            Toast.makeText(MapActivity.this, getResources().getString(R.string.no_results), Toast.LENGTH_SHORT)
                    .show();
        } else if (results.size() == 1) {
            displayResults(results.get(0));
        } else {
            // Display results
            toggleResults(true);
            // Create ResultListFragment and commit it
            Fragment resultsFragment = ResultListFragment.newInstance(results);
            Fragment fragment = mFm.findFragmentById(R.id.container_result_fragment);
            if (fragment != null) {
                mFm.beginTransaction().replace(R.id.container_result_fragment, resultsFragment)
                        .commitAllowingStateLoss();
            } else {
                mFm.beginTransaction().add(R.id.container_result_fragment, resultsFragment)
                        .commitAllowingStateLoss();
            }
            // Highlight graphics in MapFragment
            mMapFragment.highlightGraphics(results);
        }
    }

    /**
     * Displays results fragment with single result
     * @param result Single result
     */
    public void displayResults(Result result) {
        if (result != null) {
            // Display results
            toggleResults(true);
            // Create fragment and commit it
            Fragment resultFragment = ResultFragment.newInstance(result);
            Fragment fragment = mFm.findFragmentById(R.id.container_result_fragment);
            if (fragment != null) {
                mFm.beginTransaction().replace(R.id.container_result_fragment, resultFragment)
                        .commitAllowingStateLoss();
            } else {
                mFm.beginTransaction().add(R.id.container_result_fragment, resultFragment)
                        .commitAllowingStateLoss();
            }
            // Highlight graphic in MapFragment
            mMapFragment.highlightGraphics(result);
        } else {
            Toast.makeText(MapActivity.this, getResources().getString(R.string.no_results), Toast.LENGTH_SHORT)
                    .show();
        }

    }

    /**
     * Handles the visibility of the FAB which is dependent on the location
     * preference
     */
    private void toggleLocFabVisibility() {
        mFabCurrentLocation.setVisibility(mLocationPref ? View.VISIBLE : View.INVISIBLE);
    }

    /**
     * Starts the find activity for a certain item
     * @param findItemId Resource Id for the item to find
     */
    public void startFindActivity(int findItemId) {
        Intent i = new Intent(MapActivity.this, FindActivity.class);
        i.putExtra(FindActivity.EXTRA_ITEM, findItemId);
        startActivityForResult(i, FIND_REQUEST);
    }

    /**
     * Starts the Street View Activity
     * @param lon Longitutde of the Click
     * @param lat Latitute of the Click
     */
    public void startStreetViewActivity(double lon, double lat) {
        Intent i = new Intent(MapActivity.this, StreetViewActivity.class);
        i.putExtra(StreetViewActivity.EXTRA_LAT, lat);
        i.putExtra(StreetViewActivity.EXTRA_LONG, lon);
        startActivityForResult(i, STREET_VIEW_REQUEST);
    }

    public void startLayerManagerActivity() {
        Intent i = new Intent(MapActivity.this, LayerManagerActivity.class);
        startActivityForResult(i, LAYER_MANAGER_REQUEST);
    }

    /**
     * Starts Google Navigation
     * @param x Longitutde of the Click
     * @param y Latitute of the Click
     */
    public void startGoolgeNav(double x, double y) {
        Uri gmmIntentUri = Uri.parse("google.navigation:q=" + y + "," + x);
        Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
        mapIntent.setPackage("com.google.android.apps.maps");
        startActivity(mapIntent);
    }

    /**
     * Changes the current tool text in the naviagation view header
     * @param currentTool Resource Id of the current tool string
     */
    public void setCurrentToolText(int currentTool) {
        mCurrentToolText.setText(currentTool);
    }

    /**
     * Resource Id of the basemap chosen
     * @return Resource Id of the basemap
     */
    public int getBasemapId() {
        return mBasemapId;
    }

    /**
     * Set the basemap
     * @param basemapId Resource Id for basemap
     */
    public void setBasemapId(int basemapId) {
        mBasemapId = basemapId;
    }

    /**
     * Return the map fragment in the activity
     * @return MapFragment
     */
    public MapFragment getMapFragment() {
        return mMapFragment;
    }

    /**
     * Return the location preference
     * @return Location preference
     */
    public boolean isLocationPref() {
        return mLocationPref;
    }

}