Example usage for android.preference PreferenceGroup addPreference

List of usage examples for android.preference PreferenceGroup addPreference

Introduction

In this page you can find the example usage for android.preference PreferenceGroup addPreference.

Prototype

public boolean addPreference(Preference preference) 

Source Link

Document

Adds a Preference at the correct position based on the preference's order.

Usage

From source file:de.ub0r.android.callmeter.ui.prefs.PreferencesPlain.java

private void loadRules() {
    new AsyncTask<Void, Void, JSONObject>() {
        @Override//  w  ww.j a  v a  2 s .co  m
        protected JSONObject doInBackground(final Void... params) {
            try {
                String l;
                StringBuilder sb = new StringBuilder();

                File f = new File(PreferencesPlain.this.getCacheDir(), "ub0rrules.json");
                if (f.exists() && f.lastModified() + CACHE_TIMEOUT > System.currentTimeMillis()) {
                    Log.i(TAG, "found cached data: " + f.getAbsolutePath());
                    BufferedReader r = new BufferedReader(new FileReader(f));
                    while ((l = r.readLine()) != null) {
                        sb.append(l);
                    }
                    r.close();
                }
                if (sb.length() == 0) {
                    if (f.exists()) {
                        f.delete();
                    }
                    HttpURLConnection c = (HttpURLConnection) new URL(
                            "http://ub0r.de/android/callmeter/rulesets/rulesets.json").openConnection();
                    Log.i(TAG, "load new data: " + c.getURL());
                    BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    FileWriter w = new FileWriter(f);
                    while ((l = r.readLine()) != null) {
                        sb.append(l);
                        w.write(l);
                    }
                    r.close();
                    w.close();
                }
                try {
                    return new JSONObject(sb.toString());
                } catch (JSONException e) {
                    Log.e(TAG, "JSON Error", e);
                    Log.e(TAG, "JSON: " + sb.toString());
                    return null;
                }
            } catch (IOException e) {
                Log.e(TAG, "IOError", e);
            }
            return null;
        }

        @SuppressWarnings({ "deprecation", "rawtypes" })
        @Override
        protected void onPostExecute(final JSONObject result) {
            if (result == null) {
                Toast.makeText(PreferencesPlain.this, R.string.err_export_read, Toast.LENGTH_LONG).show();
                return;
            }
            PreferenceGroup base = (PreferenceGroup) PreferencesPlain.this.findPreference("import_rules_users");
            PreferenceManager pm = base.getPreferenceManager();
            // delete old
            base.removeAll();
            base = (PreferenceGroup) PreferencesPlain.this.findPreference("import_rules_base");
            // build list
            ArrayList<String> keys = new ArrayList<String>(result.length());

            Iterator it = result.keys();
            while (it.hasNext()) {
                keys.add(it.next().toString());
            }
            Collections.sort(keys);
            keys.remove("common");
            keys.add(0, "common");

            OnPreferenceClickListener opcl = new OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(final Preference preference) {
                    Intent intent = new Intent(PreferencesPlain.this, PreferencesRules.class);
                    intent.putExtra(PreferencesRules.EXTRA_JSON, result.toString());
                    intent.putExtra(PreferencesRules.EXTRA_COUNTRY, preference.getKey());
                    PreferencesPlain.this.startActivity(intent);
                    return true;
                }
            };

            for (String k : keys) {
                PreferenceScreen p = pm.createPreferenceScreen(PreferencesPlain.this);
                p.setPersistent(false);
                p.setKey(k);
                p.setTitle(k);
                p.setOnPreferenceClickListener(opcl);
                base.addPreference(p);
            }
        }

        ;
    }.execute((Void) null);
}

From source file:com.nttec.everychan.chans.fourchan.FourchanModule.java

private void addPasscodePreference(PreferenceGroup preferenceGroup) {
    final Context context = preferenceGroup.getContext();
    PreferenceScreen passScreen = preferenceGroup.getPreferenceManager().createPreferenceScreen(context);
    passScreen.setTitle("4chan pass");
    EditTextPreference passTokenPreference = new EditTextPreference(context);
    EditTextPreference passPINPreference = new EditTextPreference(context);
    Preference passLoginPreference = new Preference(context);
    Preference passClearPreference = new Preference(context);
    passTokenPreference.setTitle("Token");
    passTokenPreference.setDialogTitle("Token");
    passTokenPreference.setKey(getSharedKey(PREF_KEY_PASS_TOKEN));
    passTokenPreference.getEditText().setSingleLine();
    passTokenPreference.getEditText()//from  w  ww . ja  va2  s.  c o m
            .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    passPINPreference.setTitle("PIN");
    passPINPreference.setDialogTitle("PIN");
    passPINPreference.setKey(getSharedKey(PREF_KEY_PASS_PIN));
    passPINPreference.getEditText().setSingleLine();
    passPINPreference.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
    passLoginPreference.setTitle("Log In");
    passLoginPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (!useHttps())
                Toast.makeText(context, "Using HTTPS even if HTTP is selected", Toast.LENGTH_SHORT).show();
            final String token = preferences.getString(getSharedKey(PREF_KEY_PASS_TOKEN), "");
            final String pin = preferences.getString(getSharedKey(PREF_KEY_PASS_PIN), "");
            final String authUrl = "https://sys.4chan.org/auth"; //only https
            final CancellableTask passAuthTask = new CancellableTask.BaseCancellableTask();
            final ProgressDialog passAuthProgressDialog = new ProgressDialog(context);
            passAuthProgressDialog.setMessage("Logging in");
            passAuthProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    passAuthTask.cancel();
                }
            });
            passAuthProgressDialog.setCanceledOnTouchOutside(false);
            passAuthProgressDialog.show();
            Async.runAsync(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (passAuthTask.isCancelled())
                            return;
                        setPasscodeCookie(null, true);
                        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                        pairs.add(new BasicNameValuePair("act", "do_login"));
                        pairs.add(new BasicNameValuePair("id", token));
                        pairs.add(new BasicNameValuePair("pin", pin));
                        HttpRequestModel request = HttpRequestModel.builder()
                                .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8")).build();
                        String response = HttpStreamer.getInstance().getStringFromUrl(authUrl, request,
                                httpClient, null, passAuthTask, false);
                        if (passAuthTask.isCancelled())
                            return;
                        if (response.contains("Your device is now authorized")) {
                            String passId = null;
                            for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
                                if (cookie.getName().equals("pass_id")) {
                                    String value = cookie.getValue();
                                    if (!value.equals("0")) {
                                        passId = value;
                                        break;
                                    }
                                }
                            }
                            if (passId == null) {
                                showToast("Could not get pass id");
                            } else {
                                setPasscodeCookie(passId, true);
                                showToast("Success! Your device is now authorized.");
                            }
                        } else if (response.contains("Your Token must be exactly 10 characters")) {
                            showToast("Incorrect token");
                        } else if (response.contains("You have left one or more fields blank")) {
                            showToast("You have left one or more fields blank");
                        } else if (response.contains("Incorrect Token or PIN")) {
                            showToast("Incorrect Token or PIN");
                        } else {
                            Matcher m = Pattern
                                    .compile("<strong style=\"color: red; font-size: larger;\">(.*?)</strong>")
                                    .matcher(response);
                            if (m.find()) {
                                showToast(m.group(1));
                            } else {
                                showWebView(response);
                            }
                        }
                    } catch (Exception e) {
                        showToast(e.getMessage() == null ? resources.getString(R.string.error_unknown)
                                : e.getMessage());
                    } finally {
                        passAuthProgressDialog.dismiss();
                    }
                }

                private void showToast(final String message) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }

                private void showWebView(final String html) {
                    if (context instanceof Activity) {
                        ((Activity) context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                WebView webView = new WebView(context);
                                webView.getSettings().setSupportZoom(true);
                                webView.loadData(html, "text/html", null);
                                new AlertDialog.Builder(context).setView(webView)
                                        .setNeutralButton(android.R.string.ok, null).show();
                            }
                        });
                    }
                }
            });
            return true;
        }
    });
    passClearPreference.setTitle("Reset pass cookie");
    passClearPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            setPasscodeCookie(null, true);
            Toast.makeText(context, "Cookie is reset", Toast.LENGTH_LONG).show();
            return true;
        }
    });
    passScreen.addPreference(passTokenPreference);
    passScreen.addPreference(passPINPreference);
    passScreen.addPreference(passLoginPreference);
    passScreen.addPreference(passClearPreference);
    preferenceGroup.addPreference(passScreen);
}