com.vignesh.conf.SettingsFragment.java Source code

Java tutorial

Introduction

Here is the source code for com.vignesh.conf.SettingsFragment.java

Source

/*
 * Copyright (C) 2017-2018  Vignesh R
 *
 * 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.vignesh.conf;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

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

/**
 * A {@link PreferenceActivity} that presents a set of application settings. On
 * handset devices, settings are presented as a single list. On tablets,
 * settings are split by category, with category headers shown to the left of
 * the list of settings.
 * <p>
 * See <a href="http://developer.android.com/design/patterns/settings.html">
 * Android Design: Settings</a> for design guidelines and the <a
 * href="http://developer.android.com/guide/topics/ui/settings.html">Settings
 * API Guide</a> for more information on developing a Settings UI.
 */
public class SettingsFragment extends PreferenceFragment
        implements SharedPreferences.OnSharedPreferenceChangeListener, Preference.OnPreferenceClickListener {

    /**
     * A preference value change listener that updates the preference's summary
     * to reflect its new value.
     */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActivity().setTitle(R.string.title_activity_settings);
        addPreferencesFromResource(R.xml.pref_headers);
        SharedPreferences sharedPref = PreferenceManager
                .getDefaultSharedPreferences(getActivity().getApplicationContext());
        sharedPref.registerOnSharedPreferenceChangeListener(this);
        Preference preference = findPreference("contact");
        preference.setOnPreferenceClickListener(this);
        findPreference("calendar").setOnPreferenceClickListener(this);
        for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
            Preference p = getPreferenceScreen().getPreference(i);
            p.setSummary(
                    sharedPref.getString(p.getKey(), (p.getSummary() != null) ? p.getSummary().toString() : null));
            Log.e("WOWOWOW:", (p.getSummary() != null) ? p.getSummary().toString() : "nothing");
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

        Preference preference = findPreference(key);
        String value = sharedPreferences.getString(key, "ERROR");
        if (value == null || value.equals("ERROR") || value.isEmpty()) {
            switch (key) {
            case "contact":
                value = getString(R.string.no_contact);
                break;
            case "calendar":
                value = getString(R.string.no_calendar);
                break;
            case "regex":
                value = "(\\d{8})[\\s\\t\\n#]";
                break;
            case "past_hours":
                value = "3";
                break;
            case "future_hours":
                value = "24";
                break;
            default:
                break;
            }
            sharedPreferences.edit().putString(key, value).commit();
        }
        preference.setSummary(value);
    }

    private void changeCalendar() {
        if (ActivityCompat.checkSelfPermission(getActivity(),
                Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getActivity(), "Cannot access Calendar", Toast.LENGTH_LONG).show();
            return;
        }
        Cursor cursor = getActivity().getContentResolver().query(CalendarContract.Calendars.CONTENT_URI,
                new String[] { CalendarContract.Calendars._ID, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME },
                null, null, null);
        final List<String> list = new ArrayList<>();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),
                R.layout.support_simple_spinner_dropdown_item, list);
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {
                list.add(cursor.getString(1));
                cursor.moveToNext();
            }
        } else {
            Toast.makeText(getActivity().getApplicationContext(), "No calendars!", Toast.LENGTH_SHORT).show();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Choose a Calendar");
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferences sharedPreferences = PreferenceManager
                        .getDefaultSharedPreferences(getActivity().getApplicationContext());
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("calendar", list.get(which));
                editor.commit();
            }
        });
        builder.show();
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        Log.e("ERR", "DASDASDSAD " + preference.getKey());
        switch (preference.getKey()) {
        case "contact":
            startActivityForResult(
                    new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI), 800);
            return true;
        case "calendar":
            changeCalendar();
            return true;
        default:
            return false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == getActivity().RESULT_OK && requestCode == 800) {
            try {
                Uri uri = data.getData();
                Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
                cursor.moveToFirst();
                int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                String phoneNo = cursor.getString(numberIndex);
                String name = cursor.getString(nameIndex);
                cursor.close();
                SharedPreferences sharedPreferences = PreferenceManager
                        .getDefaultSharedPreferences(getActivity().getApplicationContext());
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("contact", name + ": " + phoneNo);
                editor.commit();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}