Example usage for android.content Intent setType

List of usage examples for android.content Intent setType

Introduction

In this page you can find the example usage for android.content Intent setType.

Prototype

public @NonNull Intent setType(@Nullable String type) 

Source Link

Document

Set an explicit MIME data type.

Usage

From source file:com.example.zf_android.trade.ApplyDetailActivity.java

private void setupItem(LinearLayout item, int itemType, final String key, final String value) {
    switch (itemType) {
    case ITEM_EDIT: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        EditText etValue = (EditText) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);//from w  ww. j a  v  a 2s .c o  m
        if (!TextUtils.isEmpty(value))
            etValue.setText(value);
        break;
    }
    case ITEM_CHOOSE: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        if (!TextUtils.isEmpty(value))
            tvValue.setText(value);
        break;
    }
    case ITEM_UPLOAD: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        final TextView tvValue = (TextView) item.findViewById(R.id.apply_detail_value);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        tvValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                uploadingTextView = tvValue;
                AlertDialog.Builder builder = new AlertDialog.Builder(ApplyDetailActivity.this);
                final String[] items = getResources().getStringArray(R.array.apply_detail_upload);
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0: {
                            Intent intent = new Intent();
                            intent.setType("image/*");
                            intent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(intent, REQUEST_UPLOAD_IMAGE);
                            break;
                        }
                        case 1: {
                            String state = Environment.getExternalStorageState();
                            if (state.equals(Environment.MEDIA_MOUNTED)) {
                                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                File outDir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                                if (!outDir.exists()) {
                                    outDir.mkdirs();
                                }
                                File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
                                photoPath = outFile.getAbsolutePath();
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
                                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                                startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                            } else {
                                CommonUtil.toastShort(ApplyDetailActivity.this,
                                        getString(R.string.toast_no_sdcard));
                            }
                            break;
                        }
                        }
                    }
                });
                builder.show();

            }
        });
        break;
    }
    case ITEM_VIEW: {
        TextView tvKey = (TextView) item.findViewById(R.id.apply_detail_key);
        ImageButton ibView = (ImageButton) item.findViewById(R.id.apply_detail_view);

        if (!TextUtils.isEmpty(key))
            tvKey.setText(key);
        ibView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(ApplyDetailActivity.this, ImageViewer.class);
                i.putExtra("url", value);
                i.putExtra("justviewer", true);
                startActivity(i);
            }
        });
    }
    }
}

From source file:com.piusvelte.taplock.client.core.TapLockSettings.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    if (itemId == R.id.button_add_device)
        addDevice();/*  w ww.j  a va 2 s.c o m*/
    else if (itemId == R.id.button_about) {
        mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle(R.string.button_about)
                .setMessage(R.string.about)
                .setNeutralButton(R.string.button_getserver, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();

                        mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                .setTitle(R.string.msg_pickinstaller)
                                .setItems(R.array.installer_entries, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                        final String installer_file = getResources()
                                                .getStringArray(R.array.installer_values)[which];

                                        mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                                .setTitle(R.string.msg_pickdownloader)
                                                .setItems(R.array.download_entries,
                                                        new DialogInterface.OnClickListener() {

                                                            @Override
                                                            public void onClick(DialogInterface dialog,
                                                                    int which) {
                                                                dialog.cancel();
                                                                String action = getResources().getStringArray(
                                                                        R.array.download_values)[which];
                                                                if (ACTION_DOWNLOAD_SDCARD.equals(action)
                                                                        && copyFileToSDCard(installer_file))
                                                                    Toast.makeText(TapLockSettings.this,
                                                                            "Done!", Toast.LENGTH_SHORT).show();
                                                                else if (ACTION_DOWNLOAD_EMAIL.equals(action)
                                                                        && copyFileToSDCard(installer_file)) {
                                                                    Intent emailIntent = new Intent(
                                                                            android.content.Intent.ACTION_SEND);
                                                                    emailIntent.setType(
                                                                            "application/java-archive");
                                                                    emailIntent.putExtra(Intent.EXTRA_TEXT,
                                                                            getString(
                                                                                    R.string.email_instructions));
                                                                    emailIntent.putExtra(Intent.EXTRA_SUBJECT,
                                                                            getString(R.string.app_name));
                                                                    emailIntent.putExtra(Intent.EXTRA_STREAM,
                                                                            Uri.parse("file://" + Environment
                                                                                    .getExternalStorageDirectory()
                                                                                    .getPath() + "/"
                                                                                    + installer_file));
                                                                    startActivity(Intent.createChooser(
                                                                            emailIntent, getString(
                                                                                    R.string.button_getserver)));
                                                                }
                                                            }

                                                        })
                                                .create();
                                        mDialog.show();
                                    }
                                }).create();
                        mDialog.show();
                    }
                }).setPositiveButton(R.string.button_license, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                .setTitle(R.string.button_license).setMessage(R.string.license).create();
                        mDialog.show();
                    }

                }).create();
        mDialog.show();
    }
    return super.onOptionsItemSelected(item);
}

From source file:dk.dr.radio.data.DRData.java

public void kundividi(Activity akt) {
      Intent sendIntent = new Intent();
      sendIntent.setAction(Intent.ACTION_SEND);
      sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Esperanto-radio por Androjd");
      sendIntent.putExtra(Intent.EXTRA_TEXT,
              "Saluton!\n\n" + "Mi rekomendas ke vi elprovas tiun i programon per via Androjda telefono:\n"
                      + "La Esperanto-radio de Muzaiko\n"
                      + "https://market.android.com/details?id=dk.nordfalk.esperanto.radio\n" + "\n"
                      + "Muzaiko estas Esperanto-radio kiu konstante elsendas.\n"
                      + "Eblas anka askulti la lastatempajn elsendojn de deko da aliaj radistacioj." //         +"\n\n(kaj... ne forgesu meti 5 stelojn :-)"
      );//from w w w .  j a v  a 2s  .  com
      sendIntent.setType("text/plain");
      akt.startActivity(Intent.createChooser(sendIntent, "Sendi al"));
  }

From source file:com.justone.android.main.MainActivity.java

public void shareOnClick(View view) {
    String shareTitle = "";
    String shareContent = "    ";
    if (tabs.getCurrentTabTag() == "home tab") {
        shareTitle = "home tab";
        shareContent = shareContent + ((TextView) this.findViewById(R.id.fPage_tView)).getText().toString()
                + ((TextView) this.findViewById(R.id.imageBelow_tView)).getText().toString()
                + "()  " + ((TextView) this.findViewById(R.id.home_share_url)).getText().toString();
    } else if (tabs.getCurrentTabTag() == "QA Tab") {
        shareTitle = "QA Tab";
        shareContent = shareContent + ((TextView) this.findViewById(R.id.question_content)).getText().toString()
                + " -  ()  "
                + ((TextView) this.findViewById(R.id.qa_share_url)).getText().toString();

    } else if (tabs.getCurrentTabTag() == "list tab") {
        shareTitle = "list tab";
        shareContent = shareContent + ""
                + ((TextView) this.findViewById(R.id.one_content_title)).getText().toString() + " by "
                + ((TextView) this.findViewById(R.id.one_content_author)).getText().toString()
                + "- ()  "
                + ((TextView) this.findViewById(R.id.list_share_url)).getText().toString();

    }/*w w w. java2  s .c o  m*/

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    // intent.setPackage("com.sina.weibo");
    intent.putExtra(Intent.EXTRA_SUBJECT, "");
    //intent.putExtra(Intent.EXTRA_TEXT, shareTitle+"   VOL.516   () http://caodan.org/516-photo.html ");
    intent.putExtra(Intent.EXTRA_TEXT, shareContent);
    intent.putExtra(Intent.EXTRA_TITLE, shareTitle);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(Intent.createChooser(intent, ""));
}

From source file:io.ingame.squarecamera.CameraLauncher.java

/**
 * Get image from photo library./*from  w ww .  j  ava 2  s  .co m*/
 *
 * @param srcType           The album to get image from.
 * @param returnType        Set the type of image to return.
 * @param encodingType
 */
// TODO: Images selected from SDCARD don't display correctly, but from CAMERA ALBUM do!
// TODO: Images from kitkat filechooser not going into crop function
public void getImage(int srcType, int returnType, int encodingType) {
    Intent intent = new Intent();
    String title = GET_PICTURE;
    croppedUri = null;
    if (this.mediaType == PICTURE) {
        intent.setType("image/*");
        if (this.allowEdit) {
            intent.setAction(Intent.ACTION_PICK);
            intent.putExtra("crop", "true");
            if (targetWidth > 0) {
                intent.putExtra("outputX", targetWidth);
            }
            if (targetHeight > 0) {
                intent.putExtra("outputY", targetHeight);
            }
            if (targetHeight > 0 && targetWidth > 0 && targetWidth == targetHeight) {
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
            }
            File photo = createCaptureFile(encodingType);
            croppedUri = Uri.fromFile(photo);
            setOutputUri(intent, croppedUri);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
        }
    } else if (this.mediaType == VIDEO) {
        intent.setType("video/*");
        title = GET_VIDEO;
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
    } else if (this.mediaType == ALLMEDIA) {
        // I wanted to make the type 'image/*, video/*' but this does not work on all versions
        // of android so I had to go with the wildcard search.
        intent.setType("*/*");
        title = GET_All;
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
    }
    if (this.cordova != null) {
        this.cordova.startActivityForResult((CordovaPlugin) this,
                Intent.createChooser(intent, new String(title)), (srcType + 1) * 16 + returnType + 1);
    }
}

From source file:com.piusvelte.sonet.core.SonetCreatePost.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int itemId = item.getItemId();
    if (itemId == R.id.menu_post_accounts)
        chooseAccounts();/* w  w  w  . jav a 2  s .  co  m*/
    else if (itemId == R.id.menu_post_photo) {
        boolean supported = false;
        Iterator<Integer> services = mAccountsService.values().iterator();
        while (services.hasNext() && ((supported = sPhotoSupported.contains(services.next())) == false))
            ;
        if (supported) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PHOTO);
        } else
            unsupportedToast(sPhotoSupported);
        //      } else if (itemId == R.id.menu_post_tags) {
        //         if (mAccountsService.size() == 1) {
        //            if (sTaggingSupported.contains(mAccountsService.values().iterator().next()))
        //               selectFriends(mAccountsService.keySet().iterator().next());
        //            else
        //               unsupportedToast(sTaggingSupported);
        //         } else {
        //            // dialog to select an account
        //            Iterator<Long> accountIds = mAccountsService.keySet().iterator();
        //            HashMap<Long, String> accountEntries = new HashMap<Long, String>();
        //            while (accountIds.hasNext()) {
        //               Long accountId = accountIds.next();
        //               Cursor account = this.getContentResolver().query(Accounts.getContentUri(this), new String[]{Accounts._ID, ACCOUNTS_QUERY}, Accounts._ID + "=?", new String[]{Long.toString(accountId)}, null);
        //               if (account.moveToFirst() && sTaggingSupported.contains(mAccountsService.get(accountId)))
        //                  accountEntries.put(account.getLong(0), account.getString(1));
        //            }
        //            int size = accountEntries.size();
        //            if (size != 0) {
        //               final long[] accountIndexes = new long[size];
        //               final String[] accounts = new String[size];
        //               int i = 0;
        //               Iterator<Map.Entry<Long, String>> entries = accountEntries.entrySet().iterator();
        //               while (entries.hasNext()) {
        //                  Map.Entry<Long, String> entry = entries.next();
        //                  accountIndexes[i] = entry.getKey();
        //                  accounts[i++] = entry.getValue();
        //               }
        //               mDialog = (new AlertDialog.Builder(this))
        //                     .setTitle(R.string.accounts)
        //                     .setSingleChoiceItems(accounts, -1, new DialogInterface.OnClickListener() {
        //                        @Override
        //                        public void onClick(DialogInterface dialog, int which) {
        //                           selectFriends(accountIndexes[which]);
        //                           dialog.dismiss();
        //                        }
        //                     })
        //                     .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        //                        @Override
        //                        public void onClick(DialogInterface dialog, int which) {
        //                           dialog.dismiss();
        //                        }
        //                     })
        //                     .create();
        //               mDialog.show();
        //            } else
        //               unsupportedToast(sTaggingSupported);
        //         }
    } else if (itemId == R.id.menu_post_location) {
        LocationManager locationManager = (LocationManager) SonetCreatePost.this
                .getSystemService(Context.LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            mLat = Double.toString(location.getLatitude());
            mLong = Double.toString(location.getLongitude());
            if (mAccountsService.size() == 1) {
                if (sLocationSupported.contains(mAccountsService.values().iterator().next()))
                    setLocation(mAccountsService.keySet().iterator().next());
                else
                    unsupportedToast(sLocationSupported);
            } else {
                // dialog to select an account
                Iterator<Long> accountIds = mAccountsService.keySet().iterator();
                HashMap<Long, String> accountEntries = new HashMap<Long, String>();
                while (accountIds.hasNext()) {
                    Long accountId = accountIds.next();
                    Cursor account = this.getContentResolver().query(Accounts.getContentUri(this),
                            new String[] { Accounts._ID, ACCOUNTS_QUERY }, Accounts._ID + "=?",
                            new String[] { Long.toString(accountId) }, null);
                    if (account.moveToFirst() && sLocationSupported.contains(mAccountsService.get(accountId)))
                        accountEntries.put(account.getLong(account.getColumnIndex(Accounts._ID)),
                                account.getString(account.getColumnIndex(Accounts.USERNAME)));
                }
                int size = accountEntries.size();
                if (size != 0) {
                    final long[] accountIndexes = new long[size];
                    final String[] accounts = new String[size];
                    int i = 0;
                    Iterator<Map.Entry<Long, String>> entries = accountEntries.entrySet().iterator();
                    while (entries.hasNext()) {
                        Map.Entry<Long, String> entry = entries.next();
                        accountIndexes[i] = entry.getKey();
                        accounts[i++] = entry.getValue();
                    }
                    mDialog = (new AlertDialog.Builder(this)).setTitle(R.string.accounts)
                            .setSingleChoiceItems(accounts, -1, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    setLocation(accountIndexes[which]);
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    mDialog.show();
                } else
                    unsupportedToast(sLocationSupported);
            }
        } else
            (Toast.makeText(this, getString(R.string.location_unavailable), Toast.LENGTH_LONG)).show();
    }
    return super.onOptionsItemSelected(item);
}

From source file:it.feio.android.omninotes.SettingsFragment.java

@SuppressWarnings("deprecation")
@Override// ww w .  j a  v a  2 s . co  m
public void onResume() {
    super.onResume();

    // Export notes
    Preference export = findPreference("settings_export_data");
    if (export != null) {
        export.setOnPreferenceClickListener(arg0 -> {

            // Inflate layout
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View v = inflater.inflate(R.layout.dialog_backup_layout, null);

            // Finds actually saved backups names
            PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    R.string.permission_external_storage, activity.findViewById(R.id.crouton_handle),
                    () -> export(v));

            return false;
        });
    }

    // Import notes
    Preference importData = findPreference("settings_import_data");
    if (importData != null) {
        importData.setOnPreferenceClickListener(arg0 -> {

            // Finds actually saved backups names
            PermissionsHelper.requestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE,
                    R.string.permission_external_storage, activity.findViewById(R.id.crouton_handle),
                    this::importNotes);

            return false;
        });
    }

    // Import notes from Springpad export zip file
    Preference importFromSpringpad = findPreference("settings_import_from_springpad");
    if (importFromSpringpad != null) {
        importFromSpringpad.setOnPreferenceClickListener(arg0 -> {
            Intent intent;
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("application/zip");
            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
                Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
            startActivityForResult(intent, SPRINGPAD_IMPORT);
            return false;
        });
    }

    //      Preference syncWithDrive = findPreference("settings_backup_drive");
    //      importFromSpringpad.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //         @Override
    //         public boolean onPreferenceClick(Preference arg0) {
    //            Intent intent;
    //            intent = new Intent(Intent.ACTION_GET_CONTENT);
    //            intent.addCategory(Intent.CATEGORY_OPENABLE);
    //            intent.setType("application/zip");
    //            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
    //               Crouton.makeText(getActivity(), R.string.feature_not_available_on_this_device,
    // ONStyle.ALERT).show();
    //               return false;
    //            }
    //            startActivityForResult(intent, SPRINGPAD_IMPORT);
    //            return false;
    //         }
    //      });

    // Swiping action
    final SwitchPreference swipeToTrash = (SwitchPreference) findPreference("settings_swipe_to_trash");
    if (swipeToTrash != null) {
        if (prefs.getBoolean("settings_swipe_to_trash", false)) {
            swipeToTrash.setChecked(true);
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
        } else {
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            swipeToTrash.setChecked(false);
        }
        swipeToTrash.setOnPreferenceChangeListener((preference, newValue) -> {
            if ((Boolean) newValue) {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
            } else {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            }
            swipeToTrash.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show uncategorized notes in menu
    final SwitchPreference showUncategorized = (SwitchPreference) findPreference(
            Constants.PREF_SHOW_UNCATEGORIZED);
    if (showUncategorized != null) {
        showUncategorized.setOnPreferenceChangeListener((preference, newValue) -> {
            showUncategorized.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show Automatically adds location to new notes
    final SwitchPreference autoLocation = (SwitchPreference) findPreference(Constants.PREF_AUTO_LOCATION);
    if (autoLocation != null) {
        autoLocation.setOnPreferenceChangeListener((preference, newValue) -> {
            autoLocation.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Maximum video attachment size
    final EditTextPreference maxVideoSize = (EditTextPreference) findPreference("settings_max_video_size");
    if (maxVideoSize != null) {
        String maxVideoSizeValue = prefs.getString("settings_max_video_size", getString(R.string.not_set));
        maxVideoSize.setSummary(
                getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(maxVideoSizeValue));
        maxVideoSize.setOnPreferenceChangeListener((preference, newValue) -> {
            maxVideoSize.setSummary(
                    getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(newValue));
            prefs.edit().putString("settings_max_video_size", newValue.toString()).commit();
            return false;
        });
    }

    // Set notes' protection password
    Preference password = findPreference("settings_password");
    if (password != null) {
        password.setOnPreferenceClickListener(preference -> {
            Intent passwordIntent = new Intent(getActivity(), PasswordActivity.class);
            startActivity(passwordIntent);
            return false;
        });
    }

    // Use password to grant application access
    final SwitchPreference passwordAccess = (SwitchPreference) findPreference("settings_password_access");
    if (passwordAccess != null) {
        if (prefs.getString(Constants.PREF_PASSWORD, null) == null) {
            passwordAccess.setEnabled(false);
            passwordAccess.setChecked(false);
        } else {
            passwordAccess.setEnabled(true);
        }
        passwordAccess.setOnPreferenceChangeListener((preference, newValue) -> {
            BaseActivity.requestPassword(getActivity(), passwordConfirmed -> {
                if (passwordConfirmed) {
                    passwordAccess.setChecked((Boolean) newValue);
                }
            });
            return false;
        });
    }

    // Languages
    ListPreference lang = (ListPreference) findPreference("settings_language");
    if (lang != null) {
        String languageName = getResources().getConfiguration().locale.getDisplayName();
        lang.setSummary(languageName.substring(0, 1).toUpperCase(getResources().getConfiguration().locale)
                + languageName.substring(1, languageName.length()));
        lang.setOnPreferenceChangeListener((preference, value) -> {
            OmniNotes.updateLanguage(getActivity(), value.toString());
            MiscUtils.restartApp(getActivity().getApplicationContext(), MainActivity.class);
            return false;
        });
    }

    // Text size
    final ListPreference textSize = (ListPreference) findPreference("settings_text_size");
    if (textSize != null) {
        int textSizeIndex = textSize.findIndexOfValue(prefs.getString("settings_text_size", "default"));
        String textSizeString = getResources().getStringArray(R.array.text_size)[textSizeIndex];
        textSize.setSummary(textSizeString);
        textSize.setOnPreferenceChangeListener((preference, newValue) -> {
            int textSizeIndex1 = textSize.findIndexOfValue(newValue.toString());
            String checklistString = getResources().getStringArray(R.array.text_size)[textSizeIndex1];
            textSize.setSummary(checklistString);
            prefs.edit().putString("settings_text_size", newValue.toString()).commit();
            textSize.setValueIndex(textSizeIndex1);
            return false;
        });
    }

    // Application's colors
    final ListPreference colorsApp = (ListPreference) findPreference("settings_colors_app");
    if (colorsApp != null) {
        int colorsAppIndex = colorsApp
                .findIndexOfValue(prefs.getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsAppString = getResources().getStringArray(R.array.colors_app)[colorsAppIndex];
        colorsApp.setSummary(colorsAppString);
        colorsApp.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsAppIndex1 = colorsApp.findIndexOfValue(newValue.toString());
            String colorsAppString1 = getResources().getStringArray(R.array.colors_app)[colorsAppIndex1];
            colorsApp.setSummary(colorsAppString1);
            prefs.edit().putString("settings_colors_app", newValue.toString()).commit();
            colorsApp.setValueIndex(colorsAppIndex1);
            return false;
        });
    }

    // Checklists
    final ListPreference checklist = (ListPreference) findPreference("settings_checked_items_behavior");
    if (checklist != null) {
        int checklistIndex = checklist
                .findIndexOfValue(prefs.getString("settings_checked_items_behavior", "0"));
        String checklistString = getResources().getStringArray(R.array.checked_items_behavior)[checklistIndex];
        checklist.setSummary(checklistString);
        checklist.setOnPreferenceChangeListener((preference, newValue) -> {
            int checklistIndex1 = checklist.findIndexOfValue(newValue.toString());
            String checklistString1 = getResources()
                    .getStringArray(R.array.checked_items_behavior)[checklistIndex1];
            checklist.setSummary(checklistString1);
            prefs.edit().putString("settings_checked_items_behavior", newValue.toString()).commit();
            checklist.setValueIndex(checklistIndex1);
            return false;
        });
    }

    // Widget's colors
    final ListPreference colorsWidget = (ListPreference) findPreference("settings_colors_widget");
    if (colorsWidget != null) {
        int colorsWidgetIndex = colorsWidget
                .findIndexOfValue(prefs.getString("settings_colors_widget", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsWidgetString = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex];
        colorsWidget.setSummary(colorsWidgetString);
        colorsWidget.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsWidgetIndex1 = colorsWidget.findIndexOfValue(newValue.toString());
            String colorsWidgetString1 = getResources()
                    .getStringArray(R.array.colors_widget)[colorsWidgetIndex1];
            colorsWidget.setSummary(colorsWidgetString1);
            prefs.edit().putString("settings_colors_widget", newValue.toString()).commit();
            colorsWidget.setValueIndex(colorsWidgetIndex1);
            return false;
        });
    }

    // Notification snooze delay
    final EditTextPreference snoozeDelay = (EditTextPreference) findPreference(
            "settings_notification_snooze_delay");
    if (snoozeDelay != null) {
        String snooze = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT);
        snooze = TextUtils.isEmpty(snooze) ? Constants.PREF_SNOOZE_DEFAULT : snooze;
        snoozeDelay.setSummary(String.valueOf(snooze) + " " + getString(R.string.minutes));
        snoozeDelay.setOnPreferenceChangeListener((preference, newValue) -> {
            String snoozeUpdated = TextUtils.isEmpty(String.valueOf(newValue)) ? Constants.PREF_SNOOZE_DEFAULT
                    : String.valueOf(newValue);
            snoozeDelay.setSummary(snoozeUpdated + " " + getString(R.string.minutes));
            prefs.edit().putString("settings_notification_snooze_delay", snoozeUpdated).apply();
            return false;
        });
    }

    // NotificationServiceListener shortcut
    final Preference norificationServiceListenerPreference = findPreference(
            "settings_notification_service_listener");
    if (norificationServiceListenerPreference != null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            getPreferenceScreen().removePreference(norificationServiceListenerPreference);
        }
    }

    // Changelog
    Preference changelog = findPreference("settings_changelog");
    if (changelog != null) {
        changelog.setOnPreferenceClickListener(arg0 -> {

            AnalyticsHelper.trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_changelog");

            new MaterialDialog.Builder(activity).customView(R.layout.activity_changelog, false)
                    .positiveText(R.string.ok).build().show();
            return false;
        });
        // Retrieval of installed app version to write it as summary
        PackageInfo pInfo;
        String versionString = "";
        try {
            pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            versionString = pInfo.versionName;
        } catch (NameNotFoundException e) {
            Log.e(Constants.TAG, "Error retrieving version", e);
        }
        changelog.setSummary(versionString);
    }

    // Settings reset
    Preference resetData = findPreference("reset_all_data");
    if (resetData != null) {
        resetData.setOnPreferenceClickListener(arg0 -> {

            new MaterialDialog.Builder(activity).content(R.string.reset_all_data_confirmation)
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            prefs.edit().clear().commit();
                            File db = getActivity().getDatabasePath(Constants.DATABASE_NAME);
                            StorageHelper.delete(getActivity(), db.getAbsolutePath());
                            File attachmentsDir = StorageHelper.getAttachmentDir(getActivity());
                            StorageHelper.delete(getActivity(), attachmentsDir.getAbsolutePath());
                            File cacheDir = StorageHelper.getCacheDir(getActivity());
                            StorageHelper.delete(getActivity(), cacheDir.getAbsolutePath());
                            MiscUtils.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();

            return false;
        });
    }

    // Instructions
    Preference instructions = findPreference("settings_tour_show_again");
    if (instructions != null) {
        instructions.setOnPreferenceClickListener(arg0 -> {
            new MaterialDialog.Builder(getActivity())
                    .content(getString(R.string.settings_tour_show_again_summary) + "?")
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog materialDialog) {

                            AnalyticsHelper.trackEvent(AnalyticsHelper.CATEGORIES.SETTING,
                                    "settings_tour_show_again");

                            prefs.edit().putBoolean(Constants.PREF_TOUR_COMPLETE, false).commit();
                            MiscUtils.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();
            return false;
        });
    }

    // Donations
    //        Preference donation = findPreference("settings_donation");
    //        if (donation != null) {
    //            donation.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //                @Override
    //                public boolean onPreferenceClick(Preference preference) {
    //                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    //
    //                    ArrayList<ImageAndTextItem> options = new ArrayList<ImageAndTextItem>();
    //                    options.add(new ImageAndTextItem(R.drawable.ic_paypal, getString(R.string.paypal)));
    //                    options.add(new ImageAndTextItem(R.drawable.ic_bitcoin, getString(R.string.bitcoin)));
    //
    //                    alertDialogBuilder
    //                            .setAdapter(new ImageAndTextAdapter(getActivity(), options),
    //                                    new DialogInterface.OnClickListener() {
    //                                        @Override
    //                                        public void onClick(DialogInterface dialog, int which) {
    //                                            switch (which) {
    //                                                case 0:
    //                                                    Intent intentPaypal = new Intent(Intent.ACTION_VIEW);
    //                                                    intentPaypal.setData(Uri.parse(getString(R.string.paypal_url)));
    //                                                    startActivity(intentPaypal);
    //                                                    break;
    //                                                case 1:
    //                                                    Intent intentBitcoin = new Intent(Intent.ACTION_VIEW);
    //                                                    intentBitcoin.setData(Uri.parse(getString(R.string.bitcoin_url)));
    //                                                    startActivity(intentBitcoin);
    //                                                    break;
    //                                            }
    //                                        }
    //                                    });
    //
    //
    //                    // create alert dialog
    //                    AlertDialog alertDialog = alertDialogBuilder.create();
    //                    // show it
    //                    alertDialog.show();
    //                    return false;
    //                }
    //            });
    //        }
}

From source file:nf.frex.android.FrexActivity.java

private void prepareColorsDialog(final Dialog dialog) {

    //Log.d(TAG, "prepareColorsDialog() entered");

    getColorSchemes();/*from   w w  w. jav  a  2 s. com*/

    //Log.d(TAG, "prepareColorsDialog: new bitmaps are being created");
    Bitmap[] colorSchemeIcons = new Bitmap[colorSchemes.getSize()];
    for (int i = 0; i < colorSchemeIcons.length; i++) {
        ColorScheme colorScheme = colorSchemes.getValue(i);
        colorSchemeIcons[i] = colorScheme.getGradientIcon();
    }

    int checkedIndex = Registries.colorSchemes.getIndex(view.getColorSchemeId());
    //Log.d(TAG, "prepareColorsDialog: checkedIndex = " + checkedIndex);
    final Spinner colorTableSpinner = (Spinner) dialog.findViewById(R.id.color_table_spinner);
    colorTableSpinner.setAdapter(new ImageArrayAdapter(this, 0, colorSchemeIcons));
    colorTableSpinner.setSelection(checkedIndex, false);
    colorTableSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View spinnerView, int position, long id) {
            view.setColorSchemeId(Registries.colorSchemes.getId(position));
            view.setColorScheme(Registries.colorSchemes.getValue(position));
            view.recomputeColors();
        }

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

    final SeekBar colorFactorSeekBar = (SeekBar) dialog.findViewById(R.id.color_gain_seek_bar);
    final double colorFactorMin = -3.0;
    final double colorFactorMax = 2.0;
    final SeekBarConfigurer colorFactorSeekBarConfigurer = SeekBarConfigurer.create(colorFactorSeekBar,
            colorFactorMin, colorFactorMax, true, view.getColorGain());
    colorFactorSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            view.setColorGain((float) colorFactorSeekBarConfigurer.getValue());
            view.recomputeColors();
        }
    });

    final SeekBar colorBiasSeekBar = (SeekBar) dialog.findViewById(R.id.color_offset_seek_bar);
    final double colorBiasMin = 0;
    final double colorBiasMax = 1024;
    final SeekBarConfigurer colorBiasSeekBarConfigurer = SeekBarConfigurer.create(colorBiasSeekBar,
            colorBiasMin, colorBiasMax, false, view.getColorOffset());
    colorBiasSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            view.setColorOffset((float) colorBiasSeekBarConfigurer.getValue());
            view.recomputeColors();
        }
    });

    final CheckBox colorRepeatCheckBox = (CheckBox) dialog.findViewById(R.id.color_repeat);
    colorRepeatCheckBox.setChecked(view.isColorRepeat());
    colorRepeatCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            view.setColorRepeat(isChecked);
            view.recomputeColors();
        }
    });

    Button randomButton = (Button) dialog.findViewById(R.id.random_button);
    randomButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            colorTableSpinner.setSelection((int) (Math.random() * colorSchemes.getSize()));
            colorFactorSeekBarConfigurer.setRandomValue();
            colorBiasSeekBarConfigurer.setRandomValue();
            view.recomputeColors();
        }
    });

    Button getPalFromImgButton = (Button) dialog.findViewById(R.id.get_pal_from_img_button);
    getPalFromImgButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            dialog.dismiss();
            startActivityForResult(photoPickerIntent, SELECT_PICTURE_REQUEST_CODE);
        }
    });

    //Log.d(TAG, "prepareColorsDialog() exited");
}

From source file:com.dycody.android.idealnote.SettingsFragment.java

@SuppressWarnings("deprecation")
@Override/* w w  w.  ja  va 2s  .  co m*/
public void onResume() {
    super.onResume();

    // Export notes
    Preference export = findPreference("settings_export_data");
    if (export != null) {
        export.setOnPreferenceClickListener(arg0 -> {

            // Inflate layout
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View v = inflater.inflate(R.layout.dialog_backup_layout, null);

            // Finds actually saved backups names
            PermissionsHelper.requestPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    R.string.permission_external_storage, activity.findViewById(R.id.crouton_handle),
                    () -> export(v));

            return false;
        });
    }

    // Import notes
    Preference importData = findPreference("settings_import_data");
    if (importData != null) {
        importData.setOnPreferenceClickListener(arg0 -> {
            importNotes();
            return false;
        });
    }

    // Import notes from Springpad export zip file
    Preference importFromSpringpad = findPreference("settings_import_from_springpad");
    if (importFromSpringpad != null) {
        importFromSpringpad.setOnPreferenceClickListener(arg0 -> {
            Intent intent;
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("application/zip");
            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
                Toast.makeText(getActivity(), R.string.feature_not_available_on_this_device, Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
            startActivityForResult(intent, SPRINGPAD_IMPORT);
            return false;
        });
    }

    //      Preference syncWithDrive = findPreference("settings_backup_drive");
    //      importFromSpringpad.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //         @Override
    //         public boolean onPreferenceClick(Preference arg0) {
    //            Intent intent;
    //            intent = new Intent(Intent.ACTION_GET_CONTENT);
    //            intent.addCategory(Intent.CATEGORY_OPENABLE);
    //            intent.setType("application/zip");
    //            if (!IntentChecker.isAvailable(getActivity(), intent, null)) {
    //               Crouton.makeText(getActivity(), R.string.feature_not_available_on_this_device,
    // ONStyle.ALERT).show();
    //               return false;
    //            }
    //            startActivityForResult(intent, SPRINGPAD_IMPORT);
    //            return false;
    //         }
    //      });

    // Swiping action
    final SwitchPreference swipeToTrash = (SwitchPreference) findPreference("settings_swipe_to_trash");
    if (swipeToTrash != null) {
        if (prefs.getBoolean("settings_swipe_to_trash", false)) {
            swipeToTrash.setChecked(true);
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
        } else {
            swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            swipeToTrash.setChecked(false);
        }
        swipeToTrash.setOnPreferenceChangeListener((preference, newValue) -> {
            if ((Boolean) newValue) {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_2));
            } else {
                swipeToTrash.setSummary(getResources().getString(R.string.settings_swipe_to_trash_summary_1));
            }
            swipeToTrash.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show uncategorized notes in menu
    final SwitchPreference showUncategorized = (SwitchPreference) findPreference(
            Constants.PREF_SHOW_UNCATEGORIZED);
    if (showUncategorized != null) {
        showUncategorized.setOnPreferenceChangeListener((preference, newValue) -> {
            showUncategorized.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Show Automatically adds location to new notes
    final SwitchPreference autoLocation = (SwitchPreference) findPreference(Constants.PREF_AUTO_LOCATION);
    if (autoLocation != null) {
        autoLocation.setOnPreferenceChangeListener((preference, newValue) -> {
            autoLocation.setChecked((Boolean) newValue);
            return false;
        });
    }

    // Maximum video attachment size
    final EditTextPreference maxVideoSize = (EditTextPreference) findPreference("settings_max_video_size");
    if (maxVideoSize != null) {
        String maxVideoSizeValue = prefs.getString("settings_max_video_size", getString(R.string.not_set));
        maxVideoSize.setSummary(
                getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(maxVideoSizeValue));
        maxVideoSize.setOnPreferenceChangeListener((preference, newValue) -> {
            maxVideoSize.setSummary(
                    getString(R.string.settings_max_video_size_summary) + ": " + String.valueOf(newValue));
            prefs.edit().putString("settings_max_video_size", newValue.toString()).commit();
            return false;
        });
    }

    // Set notes' protection password
    Preference password = findPreference("settings_password");
    if (password != null) {
        password.setOnPreferenceClickListener(preference -> {
            Intent passwordIntent = new Intent(getActivity(), PasswordActivity.class);
            startActivity(passwordIntent);
            return false;
        });
    }

    // Use password to grant application access
    final SwitchPreference passwordAccess = (SwitchPreference) findPreference("settings_password_access");
    if (passwordAccess != null) {
        if (prefs.getString(Constants.PREF_PASSWORD, null) == null) {
            passwordAccess.setEnabled(false);
            passwordAccess.setChecked(false);
        } else {
            passwordAccess.setEnabled(true);
        }
        passwordAccess.setOnPreferenceChangeListener((preference, newValue) -> {
            PasswordHelper.requestPassword(getActivity(), passwordConfirmed -> {
                if (passwordConfirmed) {
                    passwordAccess.setChecked((Boolean) newValue);
                }
            });
            return false;
        });
    }

    // Languages
    ListPreference lang = (ListPreference) findPreference("settings_language");
    if (lang != null) {
        String languageName = getResources().getConfiguration().locale.getDisplayName();
        lang.setSummary(languageName.substring(0, 1).toUpperCase(getResources().getConfiguration().locale)
                + languageName.substring(1, languageName.length()));
        lang.setOnPreferenceChangeListener((preference, value) -> {
            IdealNote.updateLanguage(getActivity(), value.toString());
            SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class);
            return false;
        });
    }

    // Text size
    final ListPreference textSize = (ListPreference) findPreference("settings_text_size");
    if (textSize != null) {
        int textSizeIndex = textSize.findIndexOfValue(prefs.getString("settings_text_size", "default"));
        String textSizeString = getResources().getStringArray(R.array.text_size)[textSizeIndex];
        textSize.setSummary(textSizeString);
        textSize.setOnPreferenceChangeListener((preference, newValue) -> {
            int textSizeIndex1 = textSize.findIndexOfValue(newValue.toString());
            String checklistString = getResources().getStringArray(R.array.text_size)[textSizeIndex1];
            textSize.setSummary(checklistString);
            prefs.edit().putString("settings_text_size", newValue.toString()).commit();
            textSize.setValueIndex(textSizeIndex1);
            return false;
        });
    }

    // Application's colors
    final ListPreference colorsApp = (ListPreference) findPreference("settings_colors_app");
    if (colorsApp != null) {
        int colorsAppIndex = colorsApp
                .findIndexOfValue(prefs.getString("settings_colors_app", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsAppString = getResources().getStringArray(R.array.colors_app)[colorsAppIndex];
        colorsApp.setSummary(colorsAppString);
        colorsApp.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsAppIndex1 = colorsApp.findIndexOfValue(newValue.toString());
            String colorsAppString1 = getResources().getStringArray(R.array.colors_app)[colorsAppIndex1];
            colorsApp.setSummary(colorsAppString1);
            prefs.edit().putString("settings_colors_app", newValue.toString()).commit();
            colorsApp.setValueIndex(colorsAppIndex1);
            return false;
        });
    }

    // Checklists
    final ListPreference checklist = (ListPreference) findPreference("settings_checked_items_behavior");
    if (checklist != null) {
        int checklistIndex = checklist
                .findIndexOfValue(prefs.getString("settings_checked_items_behavior", "0"));
        String checklistString = getResources().getStringArray(R.array.checked_items_behavior)[checklistIndex];
        checklist.setSummary(checklistString);
        checklist.setOnPreferenceChangeListener((preference, newValue) -> {
            int checklistIndex1 = checklist.findIndexOfValue(newValue.toString());
            String checklistString1 = getResources()
                    .getStringArray(R.array.checked_items_behavior)[checklistIndex1];
            checklist.setSummary(checklistString1);
            prefs.edit().putString("settings_checked_items_behavior", newValue.toString()).commit();
            checklist.setValueIndex(checklistIndex1);
            return false;
        });
    }

    // Widget's colors
    final ListPreference colorsWidget = (ListPreference) findPreference("settings_colors_widget");
    if (colorsWidget != null) {
        int colorsWidgetIndex = colorsWidget
                .findIndexOfValue(prefs.getString("settings_colors_widget", Constants.PREF_COLORS_APP_DEFAULT));
        String colorsWidgetString = getResources().getStringArray(R.array.colors_widget)[colorsWidgetIndex];
        colorsWidget.setSummary(colorsWidgetString);
        colorsWidget.setOnPreferenceChangeListener((preference, newValue) -> {
            int colorsWidgetIndex1 = colorsWidget.findIndexOfValue(newValue.toString());
            String colorsWidgetString1 = getResources()
                    .getStringArray(R.array.colors_widget)[colorsWidgetIndex1];
            colorsWidget.setSummary(colorsWidgetString1);
            prefs.edit().putString("settings_colors_widget", newValue.toString()).commit();
            colorsWidget.setValueIndex(colorsWidgetIndex1);
            return false;
        });
    }

    // Notification snooze delay
    final EditTextPreference snoozeDelay = (EditTextPreference) findPreference(
            "settings_notification_snooze_delay");
    if (snoozeDelay != null) {
        String snooze = prefs.getString("settings_notification_snooze_delay", Constants.PREF_SNOOZE_DEFAULT);
        snooze = TextUtils.isEmpty(snooze) ? Constants.PREF_SNOOZE_DEFAULT : snooze;
        snoozeDelay.setSummary(String.valueOf(snooze) + " " + getString(R.string.minutes));
        snoozeDelay.setOnPreferenceChangeListener((preference, newValue) -> {
            String snoozeUpdated = TextUtils.isEmpty(String.valueOf(newValue)) ? Constants.PREF_SNOOZE_DEFAULT
                    : String.valueOf(newValue);
            snoozeDelay.setSummary(snoozeUpdated + " " + getString(R.string.minutes));
            prefs.edit().putString("settings_notification_snooze_delay", snoozeUpdated).apply();
            return false;
        });
    }

    // NotificationServiceListener shortcut
    final Preference norificationServiceListenerPreference = findPreference(
            "settings_notification_service_listener");
    if (norificationServiceListenerPreference != null) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            getPreferenceScreen().removePreference(norificationServiceListenerPreference);
        }
    }

    // Changelog
    Preference changelog = findPreference("settings_changelog");
    if (changelog != null) {
        changelog.setOnPreferenceClickListener(arg0 -> {

            ((IdealNote) getActivity().getApplication()).getAnalyticsHelper()
                    .trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_changelog");

            new MaterialDialog.Builder(activity).customView(R.layout.activity_changelog, false)
                    .positiveText(R.string.ok).build().show();
            return false;
        });
        // Retrieval of installed app version to write it as summary
        PackageInfo pInfo;
        String versionString = "";
        try {
            pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            versionString = pInfo.versionName + getString(R.string.version_postfix);
        } catch (NameNotFoundException e) {
            Log.e(Constants.TAG, "Error retrieving version", e);
        }
        changelog.setSummary(versionString);
    }

    // Settings reset
    Preference resetData = findPreference("reset_all_data");
    if (resetData != null) {
        resetData.setOnPreferenceClickListener(arg0 -> {

            new MaterialDialog.Builder(activity).content(R.string.reset_all_data_confirmation)
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog dialog) {
                            prefs.edit().clear().commit();
                            File db = getActivity().getDatabasePath(Constants.DATABASE_NAME);
                            StorageHelper.delete(getActivity(), db.getAbsolutePath());
                            File attachmentsDir = StorageHelper.getAttachmentDir(getActivity());
                            StorageHelper.delete(getActivity(), attachmentsDir.getAbsolutePath());
                            File cacheDir = StorageHelper.getCacheDir(getActivity());
                            StorageHelper.delete(getActivity(), cacheDir.getAbsolutePath());
                            SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();

            return false;
        });
    }

    // Instructions
    Preference instructions = findPreference("settings_tour_show_again");
    if (instructions != null) {
        instructions.setOnPreferenceClickListener(arg0 -> {
            new MaterialDialog.Builder(getActivity())
                    .content(getString(R.string.settings_tour_show_again_summary) + "?")
                    .positiveText(R.string.confirm).callback(new MaterialDialog.ButtonCallback() {
                        @Override
                        public void onPositive(MaterialDialog materialDialog) {

                            ((IdealNote) getActivity().getApplication()).getAnalyticsHelper()
                                    .trackEvent(AnalyticsHelper.CATEGORIES.SETTING, "settings_tour_show_again");

                            prefs.edit().putBoolean(Constants.PREF_TOUR_COMPLETE, false).commit();
                            SystemHelper.restartApp(getActivity().getApplicationContext(), MainActivity.class);
                        }
                    }).build().show();
            return false;
        });
    }

    // Donations
    //        Preference donation = findPreference("settings_donation");
    //        if (donation != null) {
    //            donation.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //                @Override
    //                public boolean onPreferenceClick(Preference preference) {
    //                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
    //
    //                    ArrayList<ImageAndTextItem> options = new ArrayList<ImageAndTextItem>();
    //                    options.add(new ImageAndTextItem(R.drawable.ic_paypal, getString(R.string.paypal)));
    //                    options.add(new ImageAndTextItem(R.drawable.ic_bitcoin, getString(R.string.bitcoin)));
    //
    //                    alertDialogBuilder
    //                            .setAdapter(new ImageAndTextAdapter(getActivity(), options),
    //                                    new DialogInterface.OnClickListener() {
    //                                        @Override
    //                                        public void onClick(DialogInterface dialog, int which) {
    //                                            switch (which) {
    //                                                case 0:
    //                                                    Intent intentPaypal = new Intent(Intent.ACTION_VIEW);
    //                                                    intentPaypal.setData(Uri.parse(getString(R.string.paypal_url)));
    //                                                    startActivity(intentPaypal);
    //                                                    break;
    //                                                case 1:
    //                                                    Intent intentBitcoin = new Intent(Intent.ACTION_VIEW);
    //                                                    intentBitcoin.setData(Uri.parse(getString(R.string.bitcoin_url)));
    //                                                    startActivity(intentBitcoin);
    //                                                    break;
    //                                            }
    //                                        }
    //                                    });
    //
    //
    //                    // create alert dialog
    //                    AlertDialog alertDialog = alertDialogBuilder.create();
    //                    // show it
    //                    alertDialog.show();
    //                    return false;
    //                }
    //            });
    //        }
}

From source file:com.ccxt.whl.activity.SettingsFragmentC_0815.java

/**
 * ?/*  w  w  w .  ja  v a  2  s. c  o m*/
 */
public void selectPicFromLocal() {
    Intent intent;
    if (Build.VERSION.SDK_INT < 19) {
        intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");

        //Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); 
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 600);
        intent.putExtra("outputY", 600);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUritest);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection 
        //startActivityForResult(intent, CHOOSE_BIG_PICTURE);
        startActivityForResult(intent, USERPIC_REQUEST_CODE_LOCAL);
    } else {
        intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, USERPIC_REQUEST_CODE_LOCAL_19);
    }
    /*//???
    cutFile = new File(PathUtil.getInstance().getImagePath(), DemoApplication.getInstance().getUser()
    + System.currentTimeMillis() + "_m.jpg");
    cutFile.getParentFile().mkdirs();*/

}