com.armtimes.dialogs.DialogSettings.java Source code

Java tutorial

Introduction

Here is the source code for com.armtimes.dialogs.DialogSettings.java

Source

/*
 * Copyright (C) 2015 VaViAn Labs.
 *
 * 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.armtimes.dialogs;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.armtimes.R;
import com.armtimes.utils.Utils;

public class DialogSettings extends DialogFragment {

    public static final String TAG = DialogSettings.class.getSimpleName();
    private static final String KEY_SAVED_NEWS_COUNT = "saved_news_count";
    private static final String KEY_IMAGE_STORAGE = "image_storage";
    private static final String KEY_IMAGE_QUALITY_THUMBNAIL = "image_quality_thumbnail";
    private static final String KEY_IMAGE_QUALITY_BANNER = "image_quality_banner";
    private static final String KEY_FONT_SIZE = "font_size";

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

        setRetainInstance(true);
    }

    public static int getAllowedNewsCount(final Context context) {
        SharedPreferences prefs = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
        return prefs.getInt(KEY_SAVED_NEWS_COUNT, 25);
    }

    /**
     *
     * @param context Application Storage
     * @return Returns 0 if images will be saved of Internal Storage;
     *  otherwise 1 if images will be saved on External Storage.
     */
    public static int getImageStorage(final Context context) {
        // In the case if External Storage is not available,
        // return Internal Storage by default.
        if (!Utils.checkExternalStorageAvailable())
            return 0;

        SharedPreferences prefs = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
        return prefs.getInt(KEY_IMAGE_STORAGE, 0);
    }

    private void setSavedNewsCount(final String value) {
        SharedPreferences prefs = getActivity().getSharedPreferences(TAG, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(KEY_SAVED_NEWS_COUNT, Integer.parseInt(value));
        editor.apply();
    }

    private void setImageStorage(int value) {
        // In the case if External Storage is not available,
        // save data to Internal Storage by default.
        if (!Utils.checkExternalStorageAvailable())
            value = 0;

        SharedPreferences prefs = getActivity().getSharedPreferences(TAG, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(KEY_IMAGE_STORAGE, value);
        editor.apply();
    }

    /**
     * This function initialize News Preview Font Size Spinner and
     * it's adapter.
     *
     * @param settingsView Settings view with controllers.
     */
    private void initFontSizeStuff(final View settingsView) {
        Spinner fontSizeSpinner = (Spinner) settingsView.findViewById(R.id.spinnerFontSize);
        // Initialize Adapter
        ArrayAdapter fontSizeAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.font_size_array,
                android.R.layout.simple_spinner_item);
        fontSizeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        fontSizeSpinner.setAdapter(fontSizeAdapter);

        int selectedItem = 0;
        switch (getTextFontSize(getActivity())) {
        case android.R.style.TextAppearance_Medium:
            selectedItem = 1;
            break;
        case android.R.style.TextAppearance_Large:
            selectedItem = 2;
            break;
        }

        fontSizeSpinner.setSelection(selectedItem);

        fontSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setTextFontSize(position == 1 ? android.R.style.TextAppearance_Medium
                        : position == 2 ? android.R.style.TextAppearance_Large
                                : android.R.style.TextAppearance_Small);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    /**
     * Get Font Size for the Preview News Dialog.
     * If no value was set before, or error occurs while trying
     * to get value function will return android.R.attr.textAppearanceSmall
     *
     * @param context Application context.
     * @return
     */
    public static int getTextFontSize(final Context context) {
        if (context == null) {
            return android.R.style.TextAppearance_Small;
        }

        SharedPreferences prefs = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
        return prefs.getInt(KEY_FONT_SIZE, android.R.style.TextAppearance_Small);
    }

    private void setTextFontSize(final int value) {
        SharedPreferences prefs = getActivity().getSharedPreferences(TAG, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(KEY_FONT_SIZE, value);
        editor.apply();
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        View settingsView = getActivity().getLayoutInflater().inflate(R.layout.dialog_settings, null);

        // Initialize and set Storage Spinner adapter.
        Spinner storageSpinner = (Spinner) settingsView.findViewById(R.id.spinnerImageStorage);
        ArrayAdapter storageAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.image_storage_array,
                android.R.layout.simple_spinner_item);
        storageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        storageSpinner.setAdapter(storageAdapter);

        storageSpinner.setSelection(getImageStorage(getActivity()));

        storageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setImageStorage(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // Initialize and set Saved news number Spinner Adapter
        Spinner savedNewsSpinner = (Spinner) settingsView.findViewById(R.id.spinnerStoredArticlesCount);
        ArrayAdapter savedNewsAdapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.saved_articles_number_array, android.R.layout.simple_spinner_item);
        savedNewsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        savedNewsSpinner.setAdapter(savedNewsAdapter);

        int pos = savedNewsAdapter.getPosition(Integer.toString(getAllowedNewsCount(getActivity())));
        savedNewsSpinner.setSelection(pos);

        savedNewsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                final String value = (String) parent.getItemAtPosition(position);
                setSavedNewsCount(value);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        initImageQualityControllers(settingsView);
        initFontSizeStuff(settingsView);

        // Creates About Us Alert dialog which extends from DialogFragment.
        return new AlertDialog.Builder(getActivity()).setTitle(R.string.settings)
                .setNeutralButton(R.string.about_us_close, null).setView(settingsView).create();
    }

    private void initImageQualityControllers(final View view) {
        Spinner spinner = (Spinner) view.findViewById(R.id.spinnerImageQuality);
        ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.image_quality_array,
                android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(getImageQuality(getActivity()));

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setImageQuality(getActivity(), position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    /**
     * This function gets the Image Quality prefix, which is used in
     * the URL of downloading image. Allowed values to return
     *
     *              Thumbnail         Banner
     * Extra High:      g               c
     * High:            h               d
     * Low:             i (Default)     e (Default)
     * None:            n               n
     *
     * @param context Application context.
     * @return One of the values mentioned above.
     */
    public static int getImageQuality(final Context context) {
        if (context == null) {
            return 1;
        }
        SharedPreferences sp = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
        if (sp == null)
            return 1;
        switch (sp.getString(KEY_IMAGE_QUALITY_THUMBNAIL, "h")) {
        case "g":
            return 0;
        case "i":
            return 2;
        default:
        case "h":
            return 1;
        }
    }

    public static String getImageQuality(final Context context, boolean type) {
        SharedPreferences sp = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
        if (type) // Thumbnail
            return String.format("/%s/", sp.getString(KEY_IMAGE_QUALITY_THUMBNAIL, "h"));

        return String.format("/%s/", sp.getString(KEY_IMAGE_QUALITY_BANNER, "d"));

    }

    public static void setImageQuality(final Context context, final int value) {
        SharedPreferences sp = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        switch (value) {
        case 0: // Extra High
            editor.putString(KEY_IMAGE_QUALITY_THUMBNAIL, "g");
            editor.putString(KEY_IMAGE_QUALITY_BANNER, "c");
            break;

        case 2:
            editor.putString(KEY_IMAGE_QUALITY_THUMBNAIL, "i");
            editor.putString(KEY_IMAGE_QUALITY_BANNER, "e");
            break;

        default:
        case 1: // High
            editor.putString(KEY_IMAGE_QUALITY_THUMBNAIL, "h");
            editor.putString(KEY_IMAGE_QUALITY_BANNER, "d");
            break;
        }
        editor.apply();
    }
}