eu.codeplumbers.cosi.activities.CozyActivity.java Source code

Java tutorial

Introduction

Here is the source code for eu.codeplumbers.cosi.activities.CozyActivity.java

Source

/*
 *     Cos android client for Cozy Cloud
 *
 *     Copyright (C)  2016 Hamza Abdelkebir
 *
 *     This program 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.
 *
 *     This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package eu.codeplumbers.cosi.activities;

import android.app.ActivityManager;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.TextView;
import android.widget.Toast;

import com.kobakei.ratethisapp.RateThisApp;

import java.util.ArrayList;
import java.util.List;

import eu.codeplumbers.cosi.R;
import eu.codeplumbers.cosi.api.tasks.DeleteFileTask;
import eu.codeplumbers.cosi.db.models.Call;
import eu.codeplumbers.cosi.db.models.Contact;
import eu.codeplumbers.cosi.db.models.Device;
import eu.codeplumbers.cosi.db.models.Expense;
import eu.codeplumbers.cosi.db.models.File;
import eu.codeplumbers.cosi.db.models.LoyaltyCard;
import eu.codeplumbers.cosi.db.models.Note;
import eu.codeplumbers.cosi.db.models.Place;
import eu.codeplumbers.cosi.db.models.Sms;
import eu.codeplumbers.cosi.fragments.AboutFragment;
import eu.codeplumbers.cosi.fragments.CallListFragment;
import eu.codeplumbers.cosi.fragments.ContactListFragment;
import eu.codeplumbers.cosi.fragments.ExpenseListFragment;
import eu.codeplumbers.cosi.fragments.FileManagerFragment;
import eu.codeplumbers.cosi.fragments.LoyaltyCardListFragment;
import eu.codeplumbers.cosi.fragments.MainFragment;
import eu.codeplumbers.cosi.fragments.NoteListFragment;
import eu.codeplumbers.cosi.fragments.PlacesFragment;
import eu.codeplumbers.cosi.fragments.SmsListFragment;
import eu.codeplumbers.cosi.listeners.OnListFragmentInteractionListener;
import eu.codeplumbers.cosi.services.CosiFileDownloadService;
import eu.codeplumbers.cosi.services.CosiSmsService;
import eu.codeplumbers.cosi.utils.FileUtils;

public class CozyActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
        MainFragment.OnFragmentInteractionListener, OnListFragmentInteractionListener {

    private Fragment currentFragment;
    private NavigationView navigationView;
    private View header;
    private TextView txtDeviceUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cozy);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        header = navigationView.getHeaderView(0);
        txtDeviceUrl = (TextView) header.findViewById(R.id.txtDeviceUrl);
        txtDeviceUrl.setText(Device.registeredDevice().getUrl());

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        currentFragment = new MainFragment();
        fragmentTransaction.add(R.id.container, currentFragment);
        fragmentTransaction.commit();

        RateThisApp.Config config = new RateThisApp.Config(3, 5);
        config.setTitle(R.string.lbl_rate_me_title);
        config.setMessage(R.string.lbl_rate_me_message);
        config.setYesButtonText(R.string.YES);
        config.setNoButtonText(R.string.NO);
        config.setCancelButtonText(R.string.CANCEL);
        RateThisApp.init(config);
        // Monitor launch times and interval from installation
        RateThisApp.onStart(this);
        // If the criteria is satisfied, "Rate this app" dialog will be shown
        RateThisApp.showRateDialogIfNeeded(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }

        if (currentFragment instanceof FileManagerFragment) {
            ((FileManagerFragment) currentFragment).pathUp();
        } else {
            if (getFragmentManager().getBackStackEntryCount() <= 1) {
                super.onBackPressed();
            } else {
                getFragmentManager().popBackStack();
            }
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (id == R.id.nav_dashboard) {
            currentFragment = new MainFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_dashboard));
        } else if (id == R.id.nav_files) {
            currentFragment = new FileManagerFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_files) + " (" + File.getAll().size() + ")");
        } else if (id == R.id.nav_notes) {
            currentFragment = new NoteListFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_notes) + " (" + Note.getAll().size() + ")");
        } else if (id == R.id.nav_calls) {
            currentFragment = new CallListFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_calls) + " (" + Call.getAll().size() + ")");
        } else if (id == R.id.nav_sms) {
            currentFragment = new SmsListFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_sms) + " (" + Sms.getAll().size() + ")");
        } else if (id == R.id.nav_places) {
            currentFragment = new PlacesFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_places) + " (" + Place.getAll().size() + ")");
        } else if (id == R.id.nav_contacts) {
            currentFragment = new ContactListFragment();
            getSupportActionBar()
                    .setSubtitle(getString(R.string.lbl_contacts) + " (" + Contact.getAll().size() + ")");
        } else if (id == R.id.nav_configure) {
            currentFragment = new AboutFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_configure));
        } else if (id == R.id.nav_loyalty) {
            currentFragment = new LoyaltyCardListFragment();
            getSupportActionBar()
                    .setSubtitle(getString(R.string.lbl_loyalty_cards) + " (" + LoyaltyCard.getAll().size() + ")");
        } else if (id == R.id.nav_expense) {
            currentFragment = new ExpenseListFragment();
            getSupportActionBar()
                    .setSubtitle(getString(R.string.lbl_expenses) + " (" + Expense.getAll().size() + ")");
        } else if (id == R.id.nav_exit) {
            System.exit(0);
        }

        fragmentTransaction.replace(R.id.container, currentFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

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

        txtDeviceUrl = (TextView) header.findViewById(R.id.txtDeviceUrl);
        txtDeviceUrl.setText(Device.registeredDevice().getUrl());

        if (currentFragment instanceof NoteListFragment) {
            switchToFragment(getString(R.string.lbl_notes));
        } else if (currentFragment instanceof FileManagerFragment) {
            switchToFragment(getString(R.string.lbl_files));
        } else if (currentFragment instanceof SmsListFragment) {
            switchToFragment(getString(R.string.lbl_sms));
        } else if (currentFragment instanceof CallListFragment) {
            switchToFragment(getString(R.string.lbl_calls));
        } else if (currentFragment instanceof PlacesFragment) {
            switchToFragment(getString(R.string.lbl_places));
        } else if (currentFragment instanceof ContactListFragment) {
            switchToFragment(getString(R.string.lbl_contacts));
        } else if (currentFragment instanceof LoyaltyCardListFragment) {
            switchToFragment(getString(R.string.lbl_loyalty_cards));
        } else if (currentFragment instanceof ExpenseListFragment) {
            switchToFragment(getString(R.string.lbl_expenses));
        } else {
            switchToFragment(getString(R.string.lbl_dashboard));
        }

    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public void onListFragmentInteraction(Note note) {
        Intent intent = new Intent(CozyActivity.this, NoteDetailsActivity.class);
        intent.putExtra("noteId", note.getId());
        startActivity(intent);
    }

    @Override
    public void onListFragmentInteraction(final Call call) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.dial_this_number)
                .setPositiveButton(R.string.YES, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + call.getCallerNumber()));
                        startActivity(intent);
                    }
                }).setNegativeButton(R.string.NO, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).show();

    }

    @Override
    public void onListFragmentInteraction(Contact contact) {

    }

    @Override
    public void onListFragmentInteraction(Sms sms) {

    }

    @Override
    public void onListFragmentInteraction(File file) {
        if (currentFragment instanceof FileManagerFragment) {
            if (!file.isFile()) {
                String path = file.getPath().equals("") ? "/" : file.getPath() + "/";
                ((FileManagerFragment) currentFragment).setCurrentPath(path + file.getName());
                ((FileManagerFragment) currentFragment).refreshList();
            } else {
                if (file.getDownloaded()) {
                    MimeTypeMap myMime = MimeTypeMap.getSingleton();
                    Intent newIntent = new Intent(Intent.ACTION_VIEW);
                    String mimeType = myMime
                            .getMimeTypeFromExtension(FileUtils.fileExt(file.getName()).substring(1));
                    newIntent.setDataAndType(Uri.fromFile(file.getLocalPath()), mimeType);
                    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    try {
                        startActivity(newIntent);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(this, "No handler for this type of file.", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Intent intent = new Intent(CozyActivity.this, CosiFileDownloadService.class);
                    ArrayList<String> arrayList = new ArrayList<String>();
                    arrayList.add(0, file.getId() + "");
                    intent.putStringArrayListExtra("fileToDownload", arrayList);
                    startService(intent);
                }
            }
        }
    }

    @Override
    public void onListFragmentInteraction(Expense expense) {
        Intent intent = new Intent(CozyActivity.this, ExpenseDetailsActivity.class);
        intent.putExtra("expenseId", expense.getId());
        startActivity(intent);
    }

    @Override
    public void onDownloadFolder(File file) {
        if (currentFragment instanceof FileManagerFragment) {
            List<File> filesInFolder = File.getAllFileInFolderRecursive(file);
            File[] array = filesInFolder.toArray(new File[filesInFolder.size()]);

            ArrayList<String> arrayList = new ArrayList<>();

            for (int i = 0; i < array.length; i++) {
                arrayList.add(i, array[i].getId() + "");
            }

            Intent intent = new Intent(CozyActivity.this, CosiFileDownloadService.class);
            intent.putStringArrayListExtra("fileToDownload", arrayList);

            startService(intent);
        }
    }

    /**
     * Deletes file from Cozy and from local phone
     *
     * @param file
     */
    @Override
    public void onDeleteFile(File file) {
        new DeleteFileTask((FileManagerFragment) currentFragment).execute(file);
    }

    /**
     * Deletes file from phone only
     *
     * @param file
     */
    @Override
    public void onDeleteFileFromPhone(File file) {
        java.io.File f = file.getLocalPath();

        if (f.exists()) {
            f.delete();
            file.setDownloaded(false);
            file.save();
            Toast.makeText(this, file.getName() + getString(R.string.delete_from_your_phone), Toast.LENGTH_LONG)
                    .show();
            ((FileManagerFragment) currentFragment).refreshList();
        }
    }

    @Override
    public void onLoyaltyCardDeleted() {
        if (currentFragment instanceof LoyaltyCardListFragment) {
            ((LoyaltyCardListFragment) currentFragment).refreshList();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (currentFragment instanceof CallListFragment)
                    ((CallListFragment) currentFragment).refreshList();
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, R.string.permission_denied_call_log, Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case 2: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (currentFragment instanceof SmsListFragment)
                    ((SmsListFragment) currentFragment).refreshList();
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, R.string.permission_denied_sms, Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case 3: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (currentFragment instanceof FileManagerFragment)
                    ((FileManagerFragment) currentFragment).initDirs();
                ((FileManagerFragment) currentFragment).refreshList();
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, R.string.permission_denied_files, Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case 4: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (currentFragment instanceof PlacesFragment)
                    ((PlacesFragment) currentFragment).initMap();
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, R.string.permission_denied_internet, Toast.LENGTH_SHORT).show();
            }
            return;
        }
        case 5: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (currentFragment instanceof ContactListFragment)
                    ((ContactListFragment) currentFragment).refreshList();
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, R.string.permission_denied_contacts, Toast.LENGTH_SHORT).show();
            }
            return;
        }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    // Starts the IntentService
    public void onStartService() {
        Intent i = new Intent(this, CosiSmsService.class);
        startService(i);
    }

    public boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("eu.codeplumbers.attachmentbackup.app.services.ReklaimService"
                    .equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    public void switchToFragment(String docType) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (docType.equalsIgnoreCase(getString(R.string.lbl_files))) {
            currentFragment = new FileManagerFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_files) + " (" + File.getAll().size() + ")");
        } else if (docType.equalsIgnoreCase(getString(R.string.lbl_notes))) {
            currentFragment = new NoteListFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_notes) + " (" + Note.getAll().size() + ")");
        } else if (docType.equalsIgnoreCase(getString(R.string.lbl_calls))) {
            currentFragment = new CallListFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_calls) + " (" + Call.getAll().size() + ")");
        } else if (docType.equalsIgnoreCase(getString(R.string.lbl_sms))) {
            currentFragment = new SmsListFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_sms) + " (" + Sms.getAll().size() + ")");
        } else if (docType.equalsIgnoreCase(getString(R.string.lbl_places))) {
            currentFragment = new PlacesFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_places) + " (" + Place.getAll().size() + ")");
        } else if (docType.equalsIgnoreCase(getString(R.string.lbl_contacts))) {
            currentFragment = new ContactListFragment();
            getSupportActionBar()
                    .setSubtitle(getString(R.string.lbl_contacts) + " (" + Contact.getAll().size() + ")");
        } else if (docType.equalsIgnoreCase(getString(R.string.lbl_loyalty_cards))) {
            currentFragment = new LoyaltyCardListFragment();
            getSupportActionBar()
                    .setSubtitle(getString(R.string.lbl_loyalty_cards) + " (" + LoyaltyCard.getAll().size() + ")");
        } else if (docType.equalsIgnoreCase(getString(R.string.lbl_expenses))) {
            currentFragment = new ExpenseListFragment();
            getSupportActionBar()
                    .setSubtitle(getString(R.string.lbl_expenses) + " (" + Expense.getAll().size() + ")");
        } else {
            currentFragment = new MainFragment();
            getSupportActionBar().setSubtitle(getString(R.string.lbl_dashboard));
        }

        fragmentTransaction.replace(R.id.container, currentFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }
}