com.brayanarias.alarmproject.activity.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.brayanarias.alarmproject.activity.MainActivity.java

Source

/*
 * Copyright (C) 2015 brayanarias.com ing.brayanarias@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.brayanarias.alarmproject.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
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.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.TextView;

import com.android.datetimepicker.time.RadialPickerLayout;
import com.android.datetimepicker.time.TimePickerDialog;
import com.brayanarias.alarmproject.R;
import com.brayanarias.alarmproject.database.AlarmDataBase;
import com.brayanarias.alarmproject.database.DataBaseManager;
import com.brayanarias.alarmproject.fragment.AlarmEmptyFragment;
import com.brayanarias.alarmproject.fragment.AlarmListFragment;
import com.brayanarias.alarmproject.fragment.CalendarHolidayFragment;
import com.brayanarias.alarmproject.model.Alarm;
import com.brayanarias.alarmproject.receiver.AlarmReceiver;
import com.brayanarias.alarmproject.util.AlarmUtilities;
import com.brayanarias.alarmproject.util.Constant;

import java.util.ArrayList;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    public static final String tag = MainActivity.class.getName();
    private Toolbar toolbar;
    private DataBaseManager dataBaseManager;
    private ActionBarDrawerToggle drawerToggle;
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    public static final String actualFragmentKey = "ActualFragmentKey";
    private int actualItem;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Database instance
        this.dataBaseManager = DataBaseManager.getInstance(this);
        this.dataBaseManager.open();
        this.dataBaseManager.close();
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(this.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        actualItem = R.id.itMyAlarms;
        if (savedInstanceState != null) {
            actualItem = savedInstanceState.getInt(actualFragmentKey);
        }
        this.showFragment(actualItem);
        setupDrawerLayout();
        setupNavigationView();
    }

    private void setupNavigationView() {
        navigationView = (NavigationView) findViewById(R.id.navigation);
        MenuItem item = navigationView.getMenu().findItem(actualItem);
        View nav_header = LayoutInflater.from(this).inflate(R.layout.nav_header, null);
        final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
        navigationView.addHeaderView(nav_header);
        //salute
        String salute = AlarmUtilities.getSalute(getApplicationContext());
        TextView tvWellcome = (TextView) nav_header.findViewById(R.id.tvWellcome);
        tvWellcome.setText(salute);
        if (item != null) {
            item.setChecked(true);
        }
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                CharSequence title = menuItem.getTitle();
                closeDrawer();
                switch (menuItem.getItemId()) {
                case R.id.itMyAlarms:
                    showFragment(R.id.itMyAlarms);
                    actualItem = menuItem.getItemId();
                    menuItem.setChecked(true);
                    getSupportActionBar().setTitle(title);
                    return true;
                case R.id.itAddAlarm:
                    Calendar calendar = Calendar.getInstance();
                    int hour = calendar.get(Calendar.HOUR_OF_DAY);
                    int minute = calendar.get(Calendar.MINUTE);
                    TimePickerDialog timePickerDialog = TimePickerDialog
                            .newInstance(new TimePickerDialog.OnTimeSetListener() {
                                @Override
                                public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
                                    Alarm alarm = AlarmUtilities.createDefaultAlarm();
                                    String min = minute < 10 ? "0" + minute : "" + minute;
                                    if (hourOfDay == 12) {
                                        alarm.setAmPm("PM");
                                        alarm.setHour(hourOfDay);
                                        alarm.setHourFormatted((hourOfDay) + ":" + min);
                                    } else if (hourOfDay > 12) {
                                        alarm.setAmPm("PM");
                                        alarm.setHour(hourOfDay - 12);
                                        alarm.setHourFormatted((hourOfDay - 12) + ":" + min);
                                    } else {
                                        if (hourOfDay == 0) {
                                            hourOfDay = 12;
                                        }
                                        alarm.setAmPm("AM");
                                        alarm.setHour(hourOfDay);
                                        alarm.setHourFormatted(hourOfDay + ":" + min);
                                    }
                                    alarm.setMinute(minute);
                                    Intent intent = new Intent(getApplicationContext(), AddAlarmActivity.class);
                                    intent.putExtra(Constant.actionAlarmKey, Constant.addAlarm);
                                    intent.putExtra(Constant.alarmSerializableKey, alarm);
                                    startActivity(intent);
                                }
                            }, hour, minute, false);
                    timePickerDialog.show(getSupportFragmentManager(), "tag");
                    return true;
                case R.id.itCurrentMonth:
                    actualItem = menuItem.getItemId();
                    menuItem.setChecked(true);
                    showFragment(R.id.itCurrentMonth);
                    getSupportActionBar().setTitle(title);
                    return true;
                /*
                case R.id.itConfig:
                    actualItem = menuItem.getItemId();
                    menuItem.setChecked(true);
                    showFragment(R.id.itConfig);
                    getSupportActionBar().setTitle(title);
                    closeDrawer();
                    return true;
                */
                case R.id.itAbout:
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
                    WebView wvLegal = (WebView) LayoutInflater.from(getApplication())
                            .inflate(R.layout.web_view_legal, null);
                    wvLegal.loadData(getString(R.string.html_legal), "text/html", "UTF-8");
                    wvLegal.setWebChromeClient(new WebChromeClient());
                    alertBuilder.setView(wvLegal);
                    alertBuilder.setTitle(R.string.txt_about_app);
                    alertBuilder.setCancelable(true).setPositiveButton(getString(R.string.txt_button_ok),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                }
                            });
                    alertBuilder.show();
                    return true;
                default:
                    return false;
                }

            }
        });
    }

    private void closeDrawer() {
        drawerLayout.closeDrawer(GravityCompat.START);
    }

    private void setupDrawerLayout() {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,
                R.string.drawer_close);
        drawerLayout.setDrawerListener(drawerToggle);
        drawerToggle.syncState();
    }

    public void showFragment(int itemId) {
        try {
            Fragment fragmentToShow = null;
            ArrayList<Alarm> alarmsConfigured = AlarmDataBase.getAlarmList(this.dataBaseManager);
            switch (itemId) {
            case R.id.itMyAlarms:
                if (alarmsConfigured.isEmpty()) {
                    fragmentToShow = new AlarmEmptyFragment();
                } else {
                    fragmentToShow = new AlarmListFragment();
                }
                break;
            case R.id.itCurrentMonth:
                fragmentToShow = new CalendarHolidayFragment();
                break;
            /*
            case R.id.itConfig:
                fragmentToShow = new AlarmEmptyFragment();
                break;
            */
            default:
                break;
            }
            if (fragmentToShow != null) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.contentFrame, fragmentToShow, fragmentToShow.getClass().getName()).commit();
            }
        } catch (Exception e) {
            Log.e(this.getClass().getName(), e.getLocalizedMessage(), e);
        }
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        showFragment(actualItem);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // 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 id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(actualFragmentKey, actualItem);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        AlarmReceiver.setAlarms(this);

    }
}