com.loloof64.android.chess_position_manager.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.loloof64.android.chess_position_manager.MainActivity.java

Source

/**
 * This file is part of ChessPositionManagerAndroid.
    
 ChessPositionManagerAndroid is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
    
 ChessPositionManagerAndroid is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
    
 You should have received a copy of the GNU General Public License
 along with ChessPositionManagerAndroid.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.loloof64.android.chess_position_manager;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.loloof64.android.chess_position_manager.file_explorer.ConfirmRemoveElementsDialogFragment;
import com.loloof64.android.chess_position_manager.file_explorer.DirectoryManager;
import com.loloof64.android.chess_position_manager.file_explorer.ExternalStorageUnavailableException;
import com.loloof64.android.chess_position_manager.file_explorer.FilesListArrayAdapter;
import com.loloof64.android.chess_position_manager.file_explorer.ListFileElement;
import com.loloof64.android.chess_position_manager.file_explorer.NewDirectoryDialogFragment;
import com.loloof64.android.chess_position_manager.file_explorer.NewPositionDialogFragment;
import com.loloof64.android.chess_position_manager.file_explorer.RemovingFilesErrorDialogFragment;
import com.loloof64.android.chess_position_manager.file_explorer.file_clipboard.ExistingFileDialogFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends ActionBarActivity implements
        NewDirectoryDialogFragment.NewDirectoryDialogListener, NewPositionDialogFragment.NewPositionDialogListener,
        ConfirmRemoveElementsDialogFragment.ConfirmRemoveElementsListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        refreshList();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString(CURRENT_ABSOLUTE_PATH_TAG, directoryManager.getAbsolutePath());
        outState.putBoolean(SELECTION_MODE_TAG, selectionMode);
        outState.putIntArray(SELECTION_VALUES_TAG, listAdapter.getSelectedElementsPositions());
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState != null) {
            directoryManager.tryToGoInAbsoluteFolder(savedInstanceState.getString(CURRENT_ABSOLUTE_PATH_TAG));
            setSelectionMode(savedInstanceState.getBoolean(SELECTION_MODE_TAG));
            selectedPositionsToRestore = savedInstanceState.getIntArray(SELECTION_VALUES_TAG);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        this.menu = menu;
        setSelectionMode(selectionMode); // refresh list and selection mode icon
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int menuItemId = menuItem.getItemId();
        DialogFragment newFragment;
        switch (menuItemId) {
        case R.id.action_new_directory:
            newFragment = new NewDirectoryDialogFragment();
            newFragment.show(getSupportFragmentManager(), "newDirectory");
            return true;
        case R.id.action_new_position:
            newFragment = new NewPositionDialogFragment();
            newFragment.show(getSupportFragmentManager(), "newPosition");
            return true;
        case R.id.action_toggle_selection_mode:
            setSelectionMode(!selectionMode);
            return true;
        case R.id.action_remove:
            if (selectionMode) {
                final ListFileElement[] selectedElements = listAdapter.getSelectedElements();
                boolean thereIsSelection = selectedElements != null && selectedElements.length > 0;

                if (thereIsSelection) {
                    new AsyncTask<Void, Void, Void>() {
                        @Override
                        protected Void doInBackground(Void... params) {
                            ArrayList<String> folders = new ArrayList<>();
                            ArrayList<String> positions = new ArrayList<>();

                            for (ListFileElement currentFileElement : selectedElements) {
                                if (currentFileElement.isDirectory()) {
                                    folders.add(currentFileElement.getFileName());
                                } else {
                                    positions.add(currentFileElement.getFileName());
                                }
                            }

                            final String[] foldersArray = new String[folders.size()];
                            final String[] positionsArray = new String[positions.size()];
                            folders.toArray(foldersArray);
                            positions.toArray(positionsArray);

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    DialogFragment newFragment = new ConfirmRemoveElementsDialogFragment();
                                    Bundle arguments = new Bundle();
                                    arguments.putStringArray(ConfirmRemoveElementsDialogFragment.FOLDERS_TAG,
                                            foldersArray);
                                    arguments.putStringArray(ConfirmRemoveElementsDialogFragment.POSITIONS_TAG,
                                            positionsArray);
                                    newFragment.setArguments(arguments);
                                    newFragment.show(getSupportFragmentManager(), "confirmRemoveElements");
                                }
                            });

                            return null;
                        }
                    }.execute();
                }
                // if (thereIsSelection)
                else {
                    Toast.makeText(this, R.string.error_select_removing_elements_first, Toast.LENGTH_LONG).show();
                }
            }
            // if (selectionMode)
            else {
                Toast.makeText(this, R.string.error_enter_selection_mode_first, Toast.LENGTH_LONG).show();
            }
            return true;
        /////////////////// temporary
        case R.id.action_test:
            DialogFragment dialog = new ExistingFileDialogFragment();
            Bundle arguments = new Bundle();
            arguments.putString(ExistingFileDialogFragment.FILE_NAME_TAG, "MyTest.epd");
            dialog.setArguments(arguments);
            dialog.show(getSupportFragmentManager(), "testDialog");
            return true;
        ////////////////////
        default:
            return super.onOptionsItemSelected(menuItem);
        }
    }

    @Override
    public void onNewDirectoryDialogPositiveClick(String directoryName) {
        int result = directoryManager.tryToAddDirectory(directoryName);
        switch (result) {
        case DirectoryManager.DIRECTORY_ALREADY_EXISTS:
            Toast.makeText(this, R.string.error_folder_already_exists, Toast.LENGTH_SHORT).show();
            break;
        case DirectoryManager.DIRECTORY_CREATION_MISC_FAILURE:
            Toast.makeText(this, R.string.directory_creation_error, Toast.LENGTH_SHORT).show();
            break;
        case DirectoryManager.DIRECTORY_MUST_BE_NAMED:
            Toast.makeText(this, R.string.error_directory_must_be_named, Toast.LENGTH_SHORT).show();
            break;
        case DirectoryManager.DIRECTORY_CREATION_SUCCESS:
            refreshList();
            break;
        }
    }

    @Override
    public void onNewPositionDialogPositiveClick(String positionName) {
        int result = directoryManager.tryToAddPosition(positionName);
        switch (result) {
        case DirectoryManager.FILE_ALREADY_EXISTS:
            Toast.makeText(this, R.string.error_file_already_exists, Toast.LENGTH_SHORT).show();
            break;
        case DirectoryManager.FILE_CREATION_MISC_FAILURE:
            Toast.makeText(this, R.string.file_creation_error, Toast.LENGTH_SHORT).show();
            break;
        case DirectoryManager.FILE_MUST_BE_NAMED:
            Toast.makeText(this, R.string.error_position_must_be_named, Toast.LENGTH_SHORT).show();
            break;
        case DirectoryManager.FILE_CREATION_SUCCESS:
            refreshList();
            break;
        }
    }

    @Override
    public void onConfirmRemoveElementsDialogPositiveClick(String[] foldersNames, String[] positionsNames) {
        ArrayList<String> failedFolders = new ArrayList<>();
        ArrayList<String> failedPositions = new ArrayList<>();

        for (String currentFolderName : foldersNames) {
            if (!directoryManager.tryToRemoveFileOrFolder(currentFolderName)) {
                failedFolders.add(currentFolderName);
            }
        }

        for (String currentPositionName : positionsNames) {
            if (!directoryManager.tryToRemoveFileOrFolder(currentPositionName)) {
                failedPositions.add(currentPositionName);
            }
        }

        boolean allSucceed = failedPositions.isEmpty() && failedFolders.isEmpty();
        if (!allSucceed) {
            Collections.sort(failedFolders);
            Collections.sort(failedPositions);

            String[] failedFoldersArray = new String[failedFolders.size()];
            String[] failedPositionsArray = new String[failedPositions.size()];

            failedFolders.toArray(failedFoldersArray);
            failedPositions.toArray(failedPositionsArray);

            DialogFragment newFragment = new RemovingFilesErrorDialogFragment();
            Bundle arguments = new Bundle();
            arguments.putStringArray(RemovingFilesErrorDialogFragment.FOLDERS_TAG, failedFoldersArray);
            arguments.putStringArray(RemovingFilesErrorDialogFragment.POSITIONS_TAG, failedPositionsArray);
            newFragment.setArguments(arguments);
            newFragment.show(getSupportFragmentManager(), "removingElementsError");
        }

        refreshList();
    }

    @Override
    protected void onResume() {
        super.onResume();

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);
        filter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addAction(Intent.ACTION_MEDIA_NOFS);
        filter.addAction(Intent.ACTION_MEDIA_SHARED);
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        registerReceiver(mStorageReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mStorageReceiver != null)
            unregisterReceiver(mStorageReceiver);
    }

    private void notifyClosed() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_closed_notification_icon)
                .setContentTitle(getResources().getString(R.string.title_closed_application))
                .setContentText(getResources().getString(R.string.closed_application_notification));
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(
                Context.NOTIFICATION_SERVICE);

        // notificationID allows you to update the notification later on.
        mNotificationManager.notify(notificationID, mBuilder.build());
    }

    private void setSelectionMode(boolean selectionMode) {
        this.selectionMode = selectionMode;
        if (listAdapter != null)
            listAdapter.setSelectionMode(selectionMode);
        if (menu != null) {
            MenuItem toggleSelectionItem = menu.findItem(R.id.action_toggle_selection_mode);
            toggleSelectionItem.setIcon(
                    selectionMode ? R.drawable.ic_action_action_navigate : R.drawable.ic_action_action_list);
            toggleSelectionItem.setTitle(selectionMode ? R.string.action_toggle_in_navigation_mode
                    : R.string.action_toggle_in_list_mode);
        }
    }

    private void refreshList() {

        setSelectionMode(false);

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {

                try {
                    File[] currentDirectoryFiles = directoryManager.getCurrentDirectoryFiles();
                    final ArrayList<ListFileElement> tempFileElementsList = new ArrayList<>();

                    for (File currentFile : currentDirectoryFiles) {
                        tempFileElementsList
                                .add(new ListFileElement(currentFile.getName(), currentFile.isDirectory()));
                    }
                    if (!directoryManager.isInAppRoot()) {
                        tempFileElementsList.add(ListFileElement.PARENT_DIR);
                    }
                    Collections.sort(tempFileElementsList);

                    final ListFileElement[] listFileElements = new ListFileElement[tempFileElementsList.size()];

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ListView listView = (ListView) findViewById(R.id.files_list);
                            listAdapter = new FilesListArrayAdapter(MainActivity.this,
                                    tempFileElementsList.toArray(listFileElements), selectionMode,
                                    new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            int position = (int) view.getTag();
                                            ListFileElement matchingElement = listAdapter.getElementAt(position);
                                            if (matchingElement.isDirectory()) {
                                                if (matchingElement == ListFileElement.PARENT_DIR) {
                                                    if (directoryManager.tryToGoUp()) {
                                                        refreshList();
                                                    }
                                                } else {
                                                    if (directoryManager.tryToGoInRelativeFolder(
                                                            matchingElement.getFileName())) {
                                                        refreshList();
                                                    }
                                                }
                                            } else {
                                                // todo manage position viewing
                                            }
                                        }
                                    });
                            listView.setAdapter(listAdapter);
                            if (selectedPositionsToRestore != null) {
                                listAdapter.setSelectedElementsFromPositions(selectedPositionsToRestore);
                                selectedPositionsToRestore = null;
                            }

                            TextView textView = (TextView) findViewById(R.id.current_path);
                            textView.setText(directoryManager.getCurrentPath());
                        }
                    });

                } catch (ExternalStorageUnavailableException e) {
                    notifyClosed();
                    finish();
                }

                return null;
            }
        }.execute();

    }

    private BroadcastReceiver mStorageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == Intent.ACTION_MEDIA_REMOVED || action == Intent.ACTION_MEDIA_BAD_REMOVAL
                    || action == Intent.ACTION_MEDIA_EJECT || action == Intent.ACTION_MEDIA_NOFS
                    || action == Intent.ACTION_MEDIA_SHARED || action == Intent.ACTION_MEDIA_UNMOUNTED) {
                notifyClosed();
                finish();
            }
        }
    };

    private Menu menu;
    private boolean selectionMode = false;
    private DirectoryManager directoryManager = new DirectoryManager();
    private FilesListArrayAdapter listAdapter;
    private int[] selectedPositionsToRestore;

    private final static int notificationID = 100;
    private static final String CURRENT_ABSOLUTE_PATH_TAG = "com.loloof64.android.chess_position_manager.current_absolute_path";
    private static final String SELECTION_MODE_TAG = "com.loloof64.android.chess_position_manager.current_selection_mode";
    private static final String SELECTION_VALUES_TAG = "com.loloof64.android.chess_position_manager.selection_values";
}