Example usage for android.preference PreferenceScreen setKey

List of usage examples for android.preference PreferenceScreen setKey

Introduction

In this page you can find the example usage for android.preference PreferenceScreen setKey.

Prototype

public void setKey(String key) 

Source Link

Document

Sets the key for this Preference, which is used as a key to the SharedPreferences or PreferenceDataStore .

Usage

From source file:net.openfiretechnologies.veloxcontrol.github.tasks.GetCommitsInProjectTask.java

protected Void doInBackground(String... params) {
    PROJECT_ = params[0];/*from  w ww  . j a  v  a2  s.  c o  m*/
    LAST_SHA_ = params[1];
    String requestCommits;
    if (LAST_SHA_ == null) {
        mCategory.removeAll();
        requestCommits = String.format(mConfig.INITIAL_COMMITS_REQUEST_FORMAT, PROJECT_);
    } else {
        requestCommits = String.format(mConfig.COMMITS_REQUEST_FORMAT, PROJECT_, LAST_SHA_);
    }
    if (BRANCH_ == null)
        BRANCH_ = DEFAULT_BRANCH;
    try {
        HttpClient httpClient = new DefaultHttpClient();
        Log.i(TAG, "attempting to connect to: " + requestCommits);
        HttpGet requestWebsite = new HttpGet(requestCommits);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        JSONArray projectCommitsArray = new JSONArray(httpClient.execute(requestWebsite, responseHandler));

        // debugging
        if (DEBUG)
            Log.d(TAG, "projectCommitsArray.length() is: " + projectCommitsArray.length());

        String lastSha = null;
        // make a PreferenceScreen for all commits in package
        for (int i = 0; i < projectCommitsArray.length(); i++) {
            // make an object of each commit
            try {
                final CommitObject commitObject = new GithubObject(projectCommitsArray.getJSONObject(i));
                // if we are looking for the next set the we skip the first commit
                // as it is represented as the last commit from the first commit
                // loading loop
                //if (LAST_SHA_ != null && i == 1) {
                //continue;
                //}
                // debugging
                if (Config.StaticVars.JSON_SPEW)
                    Log.d(TAG, "commitObject.toString() is: " + commitObject.toString());

                PreferenceScreen mCommit = mCategory.getPreferenceManager().createPreferenceScreen(mContext);
                // apply info to our preference screen
                mCommit.setKey(commitObject.getCommitHash());
                mCommit.setTitle(commitObject.getSubject());
                mCommit.setSummary(commitObject.getAuthorName());
                mCommit.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference p) {
                        mAlertDialog.setCommitAndShow(commitObject);
                        return true;
                    }
                });
                mCategory.addPreference(mCommit);
                // most recent non null sha hash will be to iterate throught commits list
                if (commitObject.getCommitHash() != null) {
                    lastSha = commitObject.getCommitHash();
                }
            } catch (JSONException je) {
                // no author found for commit
                if (DEBUG)
                    Log.d(TAG, "encountered a null value", je);
            }
        }

        if (projectCommitsArray.length() == 100) {
            // append next 100 commits onClick()
            final PreferenceScreen mNext = mCategory.getPreferenceManager().createPreferenceScreen(mContext);
            mNext.setTitle(mContext.getString(R.string.next_commits_page_title));
            mNext.setSummary(mContext.getString(R.string.next_commits_page_summary));
            final String finalString = lastSha;
            mNext.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference p) {
                    GetCommitsInProjectTask nextList = new GetCommitsInProjectTask(mContext, mCategory,
                            mAlertDialog);
                    Log.d(TAG, "Sending project: " + PROJECT_ + " with last sha of " + finalString);
                    nextList.execute(PROJECT_, finalString);
                    // remove last entry it will be first entry in next list
                    mCategory.removePreference(mCategory.findPreference(finalString));
                    // don't keep in list after we click
                    mCategory.removePreference(mNext);
                    return true;
                }
            });
            mCategory.addPreference(mNext);
        }
    } catch (JSONException je) {
        if (DEBUG)
            Log.e(TAG, "Bad json interaction...", je);
    } catch (IOException ioe) {
        if (DEBUG)
            Log.e(TAG, "IOException...", ioe);
    } catch (NullPointerException ne) {
        if (DEBUG)
            Log.e(TAG, "NullPointer...", ne);
    }
    return null;
}

From source file:com.aokp.romcontrol.github.tasks.GetCommitsInProjectTask.java

protected Void doInBackground(String... params) {
    PROJECT_ = params[0];/*  w w  w  .  ja  va2 s  .c om*/
    LAST_SHA_ = params[1];
    String requestCommits;
    if (LAST_SHA_ == null) {
        mCategory.removeAll();
        requestCommits = String.format(mConfig.INITIAL_COMMITS_REQUEST_FORMAT, PROJECT_);
    } else {
        requestCommits = String.format(mConfig.COMMITS_REQUEST_FORMAT, PROJECT_, LAST_SHA_);
    }
    if (BRANCH_ == null)
        BRANCH_ = DEFAULT_BRANCH;
    try {
        HttpClient httpClient = new DefaultHttpClient();
        Log.i(TAG, "attempting to connect to: " + requestCommits);
        HttpGet requestWebsite = new HttpGet(requestCommits);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        JSONArray projectCommitsArray = new JSONArray(httpClient.execute(requestWebsite, responseHandler));

        // debugging
        if (DEBUG)
            Log.d(TAG, "projectCommitsArray.length() is: " + projectCommitsArray.length());

        String lastSha = null;
        // make a PreferenceScreen for all commits in package
        for (int i = 0; i < projectCommitsArray.length(); i++) {
            // make an object of each commit
            try {
                final CommitObject commitObject = new GithubObject(projectCommitsArray.getJSONObject(i));
                // if we are looking for the next set the we skip the first commit
                // as it is represented as the last commit from the first commit
                // loading loop
                //if (LAST_SHA_ != null && i == 1) {
                //continue;
                //}
                // debugging
                if (Config.StaticVars.JSON_SPEW)
                    Log.d(TAG, "commitObject.toString() is: " + commitObject.toString());

                if ("merge".contains(commitObject.getSubject().substring(0, 5).toLowerCase()))
                    continue;
                PreferenceScreen mCommit = mCategory.getPreferenceManager().createPreferenceScreen(mContext);
                // apply info to our preference screen
                mCommit.setKey(commitObject.getCommitHash());
                mCommit.setTitle(commitObject.getSubject());
                mCommit.setSummary(commitObject.getAuthorName());
                mCommit.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference p) {
                        mAlertDialog.setCommitAndShow(commitObject);
                        return true;
                    }
                });
                mCategory.addPreference(mCommit);
                // most recent non null sha hash will be to iterate throught commits list
                if (commitObject.getCommitHash() != null) {
                    lastSha = commitObject.getCommitHash();
                }
            } catch (JSONException je) {
                // no author found for commit
                if (DEBUG)
                    Log.d(TAG, "encountered a null value", je);
            }
        }

        if (projectCommitsArray.length() == 100) {
            // append next 100 commits onClick()
            final PreferenceScreen mNext = mCategory.getPreferenceManager().createPreferenceScreen(mContext);
            mNext.setTitle(mContext.getString(R.string.next_commits_page_title));
            mNext.setSummary(mContext.getString(R.string.next_commits_page_summary));
            final String finalString = lastSha;
            mNext.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference p) {
                    GetCommitsInProjectTask nextList = new GetCommitsInProjectTask(mContext, mCategory,
                            mAlertDialog);
                    Log.d(TAG, "Sending project: " + PROJECT_ + " with last sha of " + finalString);
                    nextList.execute(PROJECT_, finalString);
                    // remove last entry it will be first entry in next list
                    mCategory.removePreference(mCategory.findPreference(finalString));
                    // don't keep in list after we click
                    mCategory.removePreference(mNext);
                    return true;
                }
            });
            mCategory.addPreference(mNext);
        }
    } catch (JSONException je) {
        if (DEBUG)
            Log.e(TAG, "Bad json interaction...", je);
    } catch (IOException ioe) {
        if (DEBUG)
            Log.e(TAG, "IOException...", ioe);
    } catch (NullPointerException ne) {
        if (DEBUG)
            Log.e(TAG, "NullPointer...", ne);
    }
    return null;
}

From source file:com.aokp.romcontrol.github.tasks.GetJSONChangelogTask.java

protected Void doInBackground(Void... unused) {
    HttpClient httpClient = null;//w ww  .  j a v  a 2 s  .  c  o  m
    try {
        httpClient = new DefaultHttpClient();
        String url = String.valueOf(STATIC_DEBUG ? "https://raw.github.com/JBirdVegas/tests/master/example.json"
                : mConfig.CHANGELOG_JSON);
        HttpGet requestWebsite = new HttpGet(url);
        Log.d(TAG, "attempting to connect to: " + url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        JSONArray projectCommitsArray = new JSONArray(httpClient.execute(requestWebsite, responseHandler));

        // debugging
        if (DEBUG)
            Log.d(TAG, "projectCommitsArray.length() is: " + projectCommitsArray.length());
        if (Config.StaticVars.JSON_SPEW)
            Log.d(TAG, "projectCommitsArray.toString() is: " + projectCommitsArray.toString());

        final ChangelogObject commitObject = new ChangelogObject(new JSONObject());
        for (int i = 0; i < projectCommitsArray.length(); i++) {
            JSONObject projectsObject = (JSONObject) projectCommitsArray.get(i);
            PreferenceScreen newCommitPreference = mCategory.getPreferenceManager()
                    .createPreferenceScreen(mContext);
            commitObject.reParse(projectsObject);
            newCommitPreference.setTitle(commitObject.getSubject());
            newCommitPreference.setSummary(commitObject.getBody());
            newCommitPreference.setKey(commitObject.getCommitHash());
            newCommitPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    mAlertDialog.setCommitAndShow(commitObject);
                    return false;
                }
            });
            mCategory.addPreference(newCommitPreference);
        }
    } catch (HttpResponseException httpError) {
        Log.e(TAG, "bad HTTP response:", httpError);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "client protocal exception:", e);
    } catch (JSONException e) {
        Log.d(TAG, "bad json interaction:", e);
    } catch (IOException e) {
        Log.d(TAG, "io exception:", e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return null;
}

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

private void loadRules() {
    new AsyncTask<Void, Void, JSONObject>() {
        @Override/*from   w  ww.j a  v  a  2  s  .c o 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:net.freifunk.android.discover.SettingsActivity.java

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

    addPreferencesFromResource(R.xml.pref_data_sync);

    // get data via the key
    ArrayList<NodeMap> nodeMapArrayList = new ArrayList<NodeMap>(MapMaster.getInstance().getMaps().values());
    PreferenceCategory communities = (PreferenceCategory) findPreference("communities");

    // sort by Name
    Collections.sort(nodeMapArrayList, new NodeMapComparator());

    if (nodeMapArrayList != null && communities != null) {
        for (final NodeMap nm : nodeMapArrayList) {

            PreferenceScreen communityPreferenceScreen = getPreferenceManager()
                    .createPreferenceScreen(SettingsActivity.this);

            communityPreferenceScreen.setTitle(nm.getMapName());
            communityPreferenceScreen.setKey(nm.getMapName());

            final CheckBoxPreference deactivateCommunityPreference = new CheckBoxPreference(
                    SettingsActivity.this);

            // TODO: move Strings to resources
            deactivateCommunityPreference.setTitle("Community aktiv");
            deactivateCommunityPreference
                    .setSummary("deaktivieren, falls Community nicht auf der Karte angezeigt werden soll");
            deactivateCommunityPreference.setKey("community_deactivate_" + nm.getMapName());
            deactivateCommunityPreference.setChecked(nm.isActive());
            deactivateCommunityPreference
                    .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

                        @Override
                        public boolean onPreferenceChange(Preference preference, Object newValue) {

                            Database db = Database.getInstance(null);

                            boolean newActive = newValue.toString().equals("true") ? true : false;

                            nm.setActive(newActive);
                            db.addNodeMap(nm);

                            // reload if set to active
                            if (newActive) {
                                nm.loadNodes();
                            } else {
                                nm.updateNodes();
                            }/* ww  w. j av a  2 s.co  m*/

                            return true;
                        }
                    });

            EditTextPreference editCommunityPreference = new EditTextPreference(SettingsActivity.this);

            // TODO: move Strings to resources
            editCommunityPreference.setTitle("URL bearbeiten");
            editCommunityPreference.setSummary("aendern, falls eine andere Quelle genutzt werden soll.");
            editCommunityPreference.setKey("community_edit_" + nm.getMapName());
            editCommunityPreference.setText(nm.getMapUrl());

            editCommunityPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {

                    Database db = Database.getInstance(null);

                    // remove old nodes from map
                    nm.setActive(false);
                    EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.UPDATE_NODES, nm));

                    // we should probably do this async as well
                    db.deleteAllNodesForMap(nm);

                    // load new nodes
                    NodeMap newMap = new NodeMap(nm.getMapName(), (String) newValue, true);
                    db.addNodeMap(newMap);

                    //HashMap<String, NodeMap> nodeResult = new HashMap<String, NodeMap>(1);
                    //nodeResult.put(nm.getMapName(), nm);

                    newMap.updateNodes();
                    //EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.LOAD_NODES, nm));
                    //EventBus.getInstance().post(new NodeResult(NodeResult.NodeResultType.UPDATE_MAP, nodeResult));

                    return true;
                }
            });

            communityPreferenceScreen.addPreference(deactivateCommunityPreference);
            communityPreferenceScreen.addPreference(editCommunityPreference);

            communities.addPreference(communityPreferenceScreen);
        }
    }

    setupActionBar();

}

From source file:github.daneren2005.dsub.fragments.SettingsFragment.java

private PreferenceScreen addServer(final int instance) {
    final PreferenceScreen screen = this.getPreferenceManager().createPreferenceScreen(context);
    screen.setKey(Constants.PREFERENCES_KEY_SERVER_KEY + instance);
    screen.setOrder(instance);//w  w  w . j a v a2 s  .  c o m

    screen.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            SettingsFragment newFragment = new SettingsFragment();

            Bundle args = new Bundle();
            args.putInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, instance);
            newFragment.setArguments(args);

            replaceFragment(newFragment);
            return false;
        }
    });

    return screen;
}

From source file:net.basilwang.StaticAttachmentActivity.java

 private void reloadData(PreferenceCategory logonPreference,
      PreferenceScreen logonAddPreference,
      PreferenceManager preferenceManager) {
   // 2012-11-23 basilwang refresh tabbar title
   refreshActionBarTitle();//  w  w  w .  j av a2  s  .c o m

   logonPreference.removeAll();
   logonPreference.addPreference(logonAddPreference);
   int accountId = PreferenceManager.getDefaultSharedPreferences(this)
         .getInt(LOGON_ACCOUNT_ID, 0);
   AccountService service = new AccountService(this);
   List<Account> list = service.getAccounts();
   if (list.size() == 0) {
      logonAddPreference.setEnabled(true);

   } else {
      logonAddPreference.setEnabled(false);
      for (Account account : list) {
         PreferenceScreen preferenceItem = preferenceManager
               .createPreferenceScreen(this);
         // CheckBoxPreference checkBoxPreference = new
         // CheckBoxPreference(this);
         // make sure each key is unique
         preferenceItem.setKey(LOGON_ACCOUNT_PREFERENCES);
         preferenceItem.setTitle(PreferenceUtils.getPreferUserName(this));
         if (accountId == account.getId())
            preferenceItem.setSummary(R.string.already_checked);
         // preferenceItem.setChecked(false);
         // checkBoxPreference.setDisableDependentsState(disableDependentsState)
         // checkBoxPreference.setSelectable(false);
         preferenceItem.setOrder(0);
         preferenceItem.setOnPreferenceClickListener(this);
         logonPreference.addPreference(preferenceItem);
      }

   }

}

From source file:github.popeen.dsub.fragments.SettingsFragment.java

private PreferenceScreen expandServer(final int instance) {
    final PreferenceScreen screen = this.getPreferenceManager().createPreferenceScreen(context);
    screen.setTitle(R.string.settings_server_unused);
    screen.setKey(Constants.PREFERENCES_KEY_SERVER_KEY + instance);

    final EditTextPreference serverNamePreference = new EditTextPreference(context);
    serverNamePreference.setKey(Constants.PREFERENCES_KEY_SERVER_NAME + instance);
    serverNamePreference.setDefaultValue(getResources().getString(R.string.settings_server_unused));
    serverNamePreference.setTitle(R.string.settings_server_name);
    serverNamePreference.setDialogTitle(R.string.settings_server_name);

    if (serverNamePreference.getText() == null) {
        serverNamePreference.setText(getResources().getString(R.string.settings_server_unused));
    }//w w w  . ja  va  2 s.c  o m

    serverNamePreference.setSummary(serverNamePreference.getText());

    final EditTextPreference serverUrlPreference = new EditTextPreference(context);
    serverUrlPreference.setKey(Constants.PREFERENCES_KEY_SERVER_URL + instance);
    serverUrlPreference.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_URI);
    serverUrlPreference.setDefaultValue("http://yourhost");
    serverUrlPreference.setTitle(R.string.settings_server_address);
    serverUrlPreference.setDialogTitle(R.string.settings_server_address);

    if (serverUrlPreference.getText() == null) {
        serverUrlPreference.setText("http://yourhost");
    }

    serverUrlPreference.setSummary(serverUrlPreference.getText());
    screen.setSummary(serverUrlPreference.getText());

    final EditTextPreference serverLocalNetworkSSIDPreference = new EditTextPreference(context) {
        @Override
        protected void onAddEditTextToDialogView(View dialogView, final EditText editText) {
            super.onAddEditTextToDialogView(dialogView, editText);
            ViewGroup root = (ViewGroup) ((ViewGroup) dialogView).getChildAt(0);

            Button defaultButton = new Button(getContext());
            defaultButton.setText(internalSSIDDisplay);
            defaultButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    editText.setText(internalSSID);
                }
            });
            root.addView(defaultButton);
        }
    };
    serverLocalNetworkSSIDPreference.setKey(Constants.PREFERENCES_KEY_SERVER_LOCAL_NETWORK_SSID + instance);
    serverLocalNetworkSSIDPreference.setTitle(R.string.settings_server_local_network_ssid);
    serverLocalNetworkSSIDPreference.setDialogTitle(R.string.settings_server_local_network_ssid);

    final EditTextPreference serverInternalUrlPreference = new EditTextPreference(context);
    serverInternalUrlPreference.setKey(Constants.PREFERENCES_KEY_SERVER_INTERNAL_URL + instance);
    serverInternalUrlPreference.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_URI);
    serverInternalUrlPreference.setDefaultValue("");
    serverInternalUrlPreference.setTitle(R.string.settings_server_internal_address);
    serverInternalUrlPreference.setDialogTitle(R.string.settings_server_internal_address);
    serverInternalUrlPreference.setSummary(serverInternalUrlPreference.getText());

    final EditTextPreference serverUsernamePreference = new EditTextPreference(context);
    serverUsernamePreference.setKey(Constants.PREFERENCES_KEY_USERNAME + instance);
    serverUsernamePreference.setTitle(R.string.settings_server_username);
    serverUsernamePreference.setDialogTitle(R.string.settings_server_username);

    final EditTextPreference serverPasswordPreference = new EditTextPreference(context);
    serverPasswordPreference.setKey(Constants.PREFERENCES_KEY_PASSWORD + instance);
    serverPasswordPreference.getEditText()
            .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    serverPasswordPreference.setSummary("***");
    serverPasswordPreference.setTitle(R.string.settings_server_password);
    final CheckBoxPreference serverSyncPreference = new CheckBoxPreference(context);
    serverSyncPreference.setKey(Constants.PREFERENCES_KEY_SERVER_SYNC + instance);
    serverSyncPreference.setChecked(Util.isSyncEnabled(context, instance));
    serverSyncPreference.setSummary(R.string.settings_server_sync_summary);
    serverSyncPreference.setTitle(R.string.settings_server_sync);

    final Preference serverOpenBrowser = new Preference(context);
    serverOpenBrowser.setKey(Constants.PREFERENCES_KEY_OPEN_BROWSER);
    serverOpenBrowser.setPersistent(false);
    serverOpenBrowser.setTitle(R.string.settings_server_open_browser);
    serverOpenBrowser.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            openInBrowser(instance);
            return true;
        }
    });

    Preference serverRemoveServerPreference = new Preference(context);
    serverRemoveServerPreference.setKey(Constants.PREFERENCES_KEY_SERVER_REMOVE + instance);
    serverRemoveServerPreference.setPersistent(false);
    serverRemoveServerPreference.setTitle(R.string.settings_servers_remove);

    serverRemoveServerPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.confirmDialog(context, R.string.common_delete, screen.getTitle().toString(),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Reset values to null so when we ask for them again they are new
                            serverNamePreference.setText(null);
                            serverUrlPreference.setText(null);
                            serverUsernamePreference.setText(null);
                            serverPasswordPreference.setText(null);

                            // Don't use Util.getActiveServer since it is 0 if offline
                            int activeServer = Util.getPreferences(context)
                                    .getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
                            for (int i = instance; i <= serverCount; i++) {
                                Util.removeInstanceName(context, i, activeServer);
                            }

                            serverCount--;
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putInt(Constants.PREFERENCES_KEY_SERVER_COUNT, serverCount);
                            editor.commit();

                            removeCurrent();

                            SubsonicFragment parentFragment = context.getCurrentFragment();
                            if (parentFragment instanceof SettingsFragment) {
                                SettingsFragment serverSelectionFragment = (SettingsFragment) parentFragment;
                                serverSelectionFragment.checkForRemoved();
                            }
                        }
                    });

            return true;
        }
    });

    Preference serverTestConnectionPreference = new Preference(context);
    serverTestConnectionPreference.setKey(Constants.PREFERENCES_KEY_TEST_CONNECTION + instance);
    serverTestConnectionPreference.setPersistent(false);
    serverTestConnectionPreference.setTitle(R.string.settings_test_connection_title);
    serverTestConnectionPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            testConnection(instance);
            return false;
        }
    });

    screen.addPreference(serverNamePreference);
    screen.addPreference(serverUrlPreference);
    screen.addPreference(serverInternalUrlPreference);
    screen.addPreference(serverLocalNetworkSSIDPreference);
    screen.addPreference(serverUsernamePreference);
    screen.addPreference(serverPasswordPreference);
    screen.addPreference(serverSyncPreference);
    screen.addPreference(serverTestConnectionPreference);
    screen.addPreference(serverOpenBrowser);
    screen.addPreference(serverRemoveServerPreference);

    return screen;
}

From source file:github.daneren2005.dsub.fragments.SettingsFragment.java

private PreferenceScreen expandServer(final int instance) {
    final PreferenceScreen screen = this.getPreferenceManager().createPreferenceScreen(context);
    screen.setTitle(R.string.settings_server_unused);
    screen.setKey(Constants.PREFERENCES_KEY_SERVER_KEY + instance);

    final EditTextPreference serverNamePreference = new EditTextPreference(context);
    serverNamePreference.setKey(Constants.PREFERENCES_KEY_SERVER_NAME + instance);
    serverNamePreference.setDefaultValue(getResources().getString(R.string.settings_server_unused));
    serverNamePreference.setTitle(R.string.settings_server_name);
    serverNamePreference.setDialogTitle(R.string.settings_server_name);

    if (serverNamePreference.getText() == null) {
        serverNamePreference.setText(getResources().getString(R.string.settings_server_unused));
    }/*  ww  w  .j  a  v a  2  s  .  co m*/

    serverNamePreference.setSummary(serverNamePreference.getText());

    final EditTextPreference serverUrlPreference = new EditTextPreference(context);
    serverUrlPreference.setKey(Constants.PREFERENCES_KEY_SERVER_URL + instance);
    serverUrlPreference.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_URI);
    serverUrlPreference.setDefaultValue("http://yourhost");
    serverUrlPreference.setTitle(R.string.settings_server_address);
    serverUrlPreference.setDialogTitle(R.string.settings_server_address);

    if (serverUrlPreference.getText() == null) {
        serverUrlPreference.setText("http://yourhost");
    }

    serverUrlPreference.setSummary(serverUrlPreference.getText());
    screen.setSummary(serverUrlPreference.getText());

    final EditTextPreference serverLocalNetworkSSIDPreference = new EditTextPreference(context) {
        @Override
        protected void onAddEditTextToDialogView(View dialogView, final EditText editText) {
            super.onAddEditTextToDialogView(dialogView, editText);
            ViewGroup root = (ViewGroup) ((ViewGroup) dialogView).getChildAt(0);

            Button defaultButton = new Button(getContext());
            defaultButton.setText(internalSSIDDisplay);
            defaultButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    editText.setText(internalSSID);
                }
            });
            root.addView(defaultButton);
        }
    };
    serverLocalNetworkSSIDPreference.setKey(Constants.PREFERENCES_KEY_SERVER_LOCAL_NETWORK_SSID + instance);
    serverLocalNetworkSSIDPreference.setTitle(R.string.settings_server_local_network_ssid);
    serverLocalNetworkSSIDPreference.setDialogTitle(R.string.settings_server_local_network_ssid);

    final EditTextPreference serverInternalUrlPreference = new EditTextPreference(context);
    serverInternalUrlPreference.setKey(Constants.PREFERENCES_KEY_SERVER_INTERNAL_URL + instance);
    serverInternalUrlPreference.getEditText().setInputType(InputType.TYPE_TEXT_VARIATION_URI);
    serverInternalUrlPreference.setDefaultValue("");
    serverInternalUrlPreference.setTitle(R.string.settings_server_internal_address);
    serverInternalUrlPreference.setDialogTitle(R.string.settings_server_internal_address);
    serverInternalUrlPreference.setSummary(serverInternalUrlPreference.getText());

    final EditTextPreference serverUsernamePreference = new EditTextPreference(context);
    serverUsernamePreference.setKey(Constants.PREFERENCES_KEY_USERNAME + instance);
    serverUsernamePreference.setTitle(R.string.settings_server_username);
    serverUsernamePreference.setDialogTitle(R.string.settings_server_username);

    final EditTextPreference serverPasswordPreference = new EditTextPreference(context);
    serverPasswordPreference.setKey(Constants.PREFERENCES_KEY_PASSWORD + instance);
    serverPasswordPreference.getEditText()
            .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
    serverPasswordPreference.setSummary("***");
    serverPasswordPreference.setTitle(R.string.settings_server_password);

    final CheckBoxPreference serverTagPreference = new CheckBoxPreference(context);
    serverTagPreference.setKey(Constants.PREFERENCES_KEY_BROWSE_TAGS + instance);
    serverTagPreference.setChecked(Util.isTagBrowsing(context, instance));
    serverTagPreference.setSummary(R.string.settings_browse_by_tags_summary);
    serverTagPreference.setTitle(R.string.settings_browse_by_tags);
    serverPasswordPreference.setDialogTitle(R.string.settings_server_password);

    final CheckBoxPreference serverSyncPreference = new CheckBoxPreference(context);
    serverSyncPreference.setKey(Constants.PREFERENCES_KEY_SERVER_SYNC + instance);
    serverSyncPreference.setChecked(Util.isSyncEnabled(context, instance));
    serverSyncPreference.setSummary(R.string.settings_server_sync_summary);
    serverSyncPreference.setTitle(R.string.settings_server_sync);

    final Preference serverOpenBrowser = new Preference(context);
    serverOpenBrowser.setKey(Constants.PREFERENCES_KEY_OPEN_BROWSER);
    serverOpenBrowser.setPersistent(false);
    serverOpenBrowser.setTitle(R.string.settings_server_open_browser);
    serverOpenBrowser.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            openInBrowser(instance);
            return true;
        }
    });

    Preference serverRemoveServerPreference = new Preference(context);
    serverRemoveServerPreference.setKey(Constants.PREFERENCES_KEY_SERVER_REMOVE + instance);
    serverRemoveServerPreference.setPersistent(false);
    serverRemoveServerPreference.setTitle(R.string.settings_servers_remove);

    serverRemoveServerPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            Util.confirmDialog(context, R.string.common_delete, screen.getTitle().toString(),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // Reset values to null so when we ask for them again they are new
                            serverNamePreference.setText(null);
                            serverUrlPreference.setText(null);
                            serverUsernamePreference.setText(null);
                            serverPasswordPreference.setText(null);

                            // Don't use Util.getActiveServer since it is 0 if offline
                            int activeServer = Util.getPreferences(context)
                                    .getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
                            for (int i = instance; i <= serverCount; i++) {
                                Util.removeInstanceName(context, i, activeServer);
                            }

                            serverCount--;
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putInt(Constants.PREFERENCES_KEY_SERVER_COUNT, serverCount);
                            editor.commit();

                            removeCurrent();

                            SubsonicFragment parentFragment = context.getCurrentFragment();
                            if (parentFragment instanceof SettingsFragment) {
                                SettingsFragment serverSelectionFragment = (SettingsFragment) parentFragment;
                                serverSelectionFragment.checkForRemoved();
                            }
                        }
                    });

            return true;
        }
    });

    Preference serverTestConnectionPreference = new Preference(context);
    serverTestConnectionPreference.setKey(Constants.PREFERENCES_KEY_TEST_CONNECTION + instance);
    serverTestConnectionPreference.setPersistent(false);
    serverTestConnectionPreference.setTitle(R.string.settings_test_connection_title);
    serverTestConnectionPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            testConnection(instance);
            return false;
        }
    });

    screen.addPreference(serverNamePreference);
    screen.addPreference(serverUrlPreference);
    screen.addPreference(serverInternalUrlPreference);
    screen.addPreference(serverLocalNetworkSSIDPreference);
    screen.addPreference(serverUsernamePreference);
    screen.addPreference(serverPasswordPreference);
    screen.addPreference(serverTagPreference);
    screen.addPreference(serverSyncPreference);
    screen.addPreference(serverTestConnectionPreference);
    screen.addPreference(serverOpenBrowser);
    screen.addPreference(serverRemoveServerPreference);

    return screen;
}