com.joeyturczak.jtscanner.utils.Utility.java Source code

Java tutorial

Introduction

Here is the source code for com.joeyturczak.jtscanner.utils.Utility.java

Source

package com.joeyturczak.jtscanner.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.text.format.Time;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.joeyturczak.jtscanner.R;
import com.joeyturczak.jtscanner.models.Asset;
import com.joeyturczak.jtscanner.models.TodayData;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * Created by joeyturczak on 8/18/15.
 * Copyright (C) 2015 Joey Turczak
 *
 *       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.
 */
public class Utility {

    /**
     * Hides the keyboard
     * Credit: http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard
     */
    public static void hideKeyboard(Activity activity) {
        // Check if no view has focus:
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    // To make it easy to query for the exact date, we normalize all dates that go into
    // the database to the start of the the Julian day at UTC.
    public static long normalizeDate(long startDate) {
        // normalize the start date to the beginning of the (UTC) day
        Time time = new Time();
        time.set(startDate);
        int julianDay = Time.getJulianDay(startDate, time.gmtoff);
        return time.setJulianDay(julianDay);
    }

    public static String getTodayDateString() {
        Calendar calendar = Calendar.getInstance();
        Date today = calendar.getTime();
        DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
        return formatter.format(today);
    }

    public static String getDateString(int daysBefore) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -daysBefore);
        Date date = calendar.getTime();
        DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
        return formatter.format(date);
    }

    public static String getTodayDateAndTimeString() {
        Calendar calendar = Calendar.getInstance();
        Date today = calendar.getTime();
        DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy-HHmmss");
        return formatter.format(today);
    }

    public static long dateToMilliseconds(String dateString, String dateFormat) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        Date date = new Date();
        try {
            date = simpleDateFormat.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();
    }

    public static boolean isDateToday(long time) {
        long currentDay = normalizeDate(System.currentTimeMillis());

        return time > currentDay;
    }

    // A method to find height of the status bar
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static Boolean getSharedPreferenceValueBoolean(Context context, String key) {

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

        return sharedPreferences.getBoolean(key, Boolean.parseBoolean(key));
    }

    public static String getSharedPreferenceValueString(Context context, String key) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

        return sharedPreferences.getString(key, "");
    }

    public static int getBarcodeLength(Context context) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

        return sharedPreferences.getInt(context.getString(R.string.pref_barcode_length_key), 5);
    }

    public static void createSpreadsheet(Context context, TodayData todayData) {
        List<String> headerRow = new ArrayList<String>();
        headerRow.add("");
        headerRow.add("Machine ID");
        headerRow.add("Hot Box ID");
        headerRow.add("Cold Box ID");

        List<List> recordToAdd = new ArrayList<List>();
        recordToAdd.add(headerRow);

        long currentDay = normalizeDate(System.currentTimeMillis());

        List<Asset> assets = todayData.getAssets();

        String machine, hotBox, coldBox;

        for (Asset asset : assets) {
            List<String> nextRow = new ArrayList<>();
            machine = asset.getMachine();
            hotBox = asset.getHotBox();
            coldBox = asset.getColdBox();
            nextRow.add(String.valueOf(assets.indexOf(asset) + 1));
            nextRow.add(machine);
            nextRow.add(hotBox);
            nextRow.add(coldBox);
            recordToAdd.add(nextRow);
        }

        CreateExcelSpreadsheet cls = new CreateExcelSpreadsheet(recordToAdd);
        try {
            deleteFilesOnDate(context, currentDay);
            Uri fileUri = cls.createExcelFile();
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fileUri));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void deleteFilesOnDate(Context context, long dateInMillis) {
        long date = normalizeDate(dateInMillis);

        File externalDir = Environment.getExternalStorageDirectory();
        String externalDirPath = externalDir.getPath();

        File scannerDir = new File(externalDirPath + context.getString(R.string.file_directory));

        File[] files = scannerDir.listFiles();
        if (files != null) {
            Arrays.sort(files, Collections.reverseOrder());

            for (File file : files) {
                String fileName = file.getName();
                fileName = fileName.replace("JTS_", "");
                fileName = fileName.replace(".xls", "");

                long fileDate = Utility.dateToMilliseconds(fileName, "MM-dd-yyyy");

                if (fileDate == date) {
                    file.delete();
                }
            }
        }
    }

    public static void trimCache(Context context) {
        try {
            File dir = context.getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String child : children) {
                boolean success = deleteDir(new File(dir, child));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }

    /**
     * Checks if there is an active network interface.
     * Credit: http://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public static int getDaysToKeepFiles(Context context) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPreferences.getInt("days_to_keep", 7);
    }

    public static boolean getManualEntryPreference(Context context) {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPreferences.getBoolean("manual_entries", true);
    }

    public static void tintMenuIcon(Context context, MenuItem menuItem, int color) {
        Drawable drawable = menuItem.getIcon();

        drawable = DrawableCompat.wrap(drawable);
        DrawableCompat.setTint(drawable, ContextCompat.getColor(context, color));
        menuItem.setIcon(drawable);
    }

    public static Drawable tintDrawable(Context context, int id, int color) {
        Drawable drawable = context.getResources().getDrawable(id);

        if (drawable != null) {
            drawable = DrawableCompat.wrap(drawable);
            DrawableCompat.setTint(drawable, ContextCompat.getColor(context, color));
        }
        return drawable;
    }
}