List of usage examples for android.preference PreferenceScreen addPreference
public boolean addPreference(Preference preference)
From source file:com.rareventure.gps2.reviewer.SettingsActivity.java
private void createPreferenceHierarchy() { PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this); this.setPreferenceScreen(root); isCollectData = new CheckBoxPreference(this); isCollectData.setTitle(R.string.collect_gps_data); isCollectData.setSummary(R.string.collect_gps_data_desc); root.addPreference(isCollectData); isCollectData.setOnPreferenceClickListener(this); percTimeGpsOn = new SeekBarDialogPreference(this, getText(R.string.title_perc_time_gps_on), getText(R.string.desc_perc_time_gps_on), getResources().getInteger(R.dimen.perc_time_gps_on_min_value), getResources().getInteger(R.dimen.perc_time_gps_on_max_value), getResources().getInteger(R.dimen.perc_time_gps_on_steps), getResources().getInteger(R.dimen.perc_time_gps_on_log_scale), getText(R.string.seekbar_perc_printf_format).toString(), null); percTimeGpsOn.setOnPreferenceChangeListener(this); root.addPreference(percTimeGpsOn);//from ww w . ja v a2 s . c om minBatteryLife = new SeekBarDialogPreference(this, getText(R.string.title_min_battery_life_perc), getText(R.string.desc_min_battery_life_perc), getResources().getInteger(R.dimen.min_battery_level_min_value), getResources().getInteger(R.dimen.min_battery_level_max_value), getResources().getInteger(R.dimen.min_battery_level_steps), getResources().getInteger(R.dimen.min_battery_level_log_scale), getText(R.string.seekbar_perc_printf_format).toString(), null); minBatteryLife.setOnPreferenceChangeListener(this); root.addPreference(minBatteryLife); enableToolTips = new CheckBoxPreference(this); enableToolTips.setTitle(R.string.enable_tooltips); enableToolTips.setKey("enable_tooltips"); root.addPreference(enableToolTips); enableToolTips.setOnPreferenceClickListener(this); useMetricUnits = new CheckBoxPreference(this); useMetricUnits.setTitle(R.string.use_metric_units); useMetricUnits.setChecked(GTG.prefs.useMetric); root.addPreference(useMetricUnits); //note that we can't use setIntent() for these preferences, since that would // be interpreted as an outside action causing us to lose the password is set flag colorblindSettings = getPreferenceManager().createPreferenceScreen(this); // screenPref.setKey("screen_preference"); // colorblindSettings.setIntent(new Intent(this, ChooseColorsScreen.class)); colorblindSettings.setTitle(R.string.colorblind_title); colorblindSettings.setSummary(R.string.colorblind_summary); colorblindSettings.setOnPreferenceClickListener(this); root.addPreference(colorblindSettings); mapFontSize = new SeekBarDialogPreference(this, getText(R.string.title_map_font_size), getText(R.string.desc_map_font_size), getResources().getInteger(R.dimen.map_font_size_min_value), getResources().getInteger(R.dimen.map_font_size_max_value), getResources().getInteger(R.dimen.map_font_size_steps), getResources().getInteger(R.dimen.map_font_size_log_scale), "%1.0f", null); mapFontSize.setOnPreferenceChangeListener(this); root.addPreference(mapFontSize); enablePassword = new CheckBoxPreference(this); enablePassword.setTitle(R.string.enable_password); enablePassword.setKey("enable_password"); root.addPreference(enablePassword); enablePassword.setOnPreferenceClickListener(this); changePassword = new Preference(this); changePassword.setTitle(R.string.change_password); root.addPreference(changePassword); changePassword.setDependency("enable_password"); changePassword.setOnPreferenceClickListener(this); passwordTimeout = new SeekBarDialogPreference(this, getText(R.string.title_password_timeout), getText(R.string.desc_password_timeout), 0, passwordTimeoutStrs.length - 1, passwordTimeoutStrs.length, 0, null, new SeekBarWithText.CustomUpdateTextView() { @Override public String updateText(float value) { return passwordTimeoutStrs[(int) value]; } }); passwordTimeout.setOnPreferenceChangeListener(this); root.addPreference(passwordTimeout); createBackupFilePref = getPreferenceManager().createPreferenceScreen(this); createBackupFilePref.setTitle(R.string.create_backup_pref); root.addPreference(createBackupFilePref); createBackupFilePref.setOnPreferenceClickListener(this); restoreBackupFilePref = getPreferenceManager().createPreferenceScreen(this); restoreBackupFilePref.setTitle(R.string.restore_backup_pref); root.addPreference(restoreBackupFilePref); restoreBackupFilePref.setOnPreferenceClickListener(this); allowErrorReporting = new CheckBoxPreference(this); allowErrorReporting.setTitle(R.string.allow_error_reporting); allowErrorReporting.setSummary(R.string.allow_error_reporting_summary); allowErrorReporting.setChecked(GTG.isAcraEnabled(this)); root.addPreference(allowErrorReporting); aboutPref = getPreferenceManager().createPreferenceScreen(this); aboutPref.setOnPreferenceClickListener(this); aboutPref.setTitle(R.string.about); root.addPreference(aboutPref); PreferenceCategory advancedCategory = new PreferenceCategory(this); advancedCategory.setTitle("Advanced"); root.addPreference(advancedCategory); writeGpsWakeLockDebugFile = new CheckBoxPreference(this); writeGpsWakeLockDebugFile.setTitle(R.string.write_to_gps_wake_lock_log); writeGpsWakeLockDebugFile.setSummary(String.format(getString(R.string.write_to_gps_wake_lock_log_summary), getString(R.string.gps_wake_lock_filename))); writeGpsWakeLockDebugFile.setChecked(GTG.prefs.writeGpsWakeLockDebug); writeGpsWakeLockDebugFile.setOnPreferenceClickListener(this); advancedCategory.addPreference(writeGpsWakeLockDebugFile); }
From source file:com.provision.alarmemi.paper.fragments.SetAlarmFragment.java
private void showCategory() { PreferenceScreen preferenceScreen = getPreferenceScreen(); preferenceScreen.addPreference(category1); preferenceScreen.addPreference(category2); }
From source file:com.probam.updater.activity.GooActivity.java
@SuppressWarnings("deprecation") @Override//from ww w. ja v a 2s. c o m protected void onCreate(Bundle savedInstanceState) { boolean useDarkTheme = ManagerFactory.getPreferencesManager(this).isDarkTheme(); setTheme(useDarkTheme ? R.style.DarkTheme : R.style.AppTheme); super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.empty_pref_screen); PreferenceScreen pScreen = getPreferenceScreen(); mInfos = new HashMap<String, PackageInfo>(); if (CURRENT_NAVIGATION == null) { Preference preference = null; preference = new Preference(this); preference.getExtras().putBoolean("BROWSING_ALL", false); preference.getExtras().putBoolean("FOLDER", true); preference.getExtras().putString("PATH", "/devs"); preference.setKey(Constants.GOO_SEARCH_URL + "/devs&ro_board=" + mDevice); preference.setTitle(R.string.goo_browse_all_compatible); pScreen.addPreference(preference); preference = new Preference(this); preference.getExtras().putBoolean("BROWSING_ALL", true); preference.getExtras().putBoolean("FOLDER", true); preference.getExtras().putString("PATH", "/devs"); preference.setKey(Constants.GOO_SEARCH_URL + "/devs"); preference.setTitle(R.string.goo_browse_all); pScreen.addPreference(preference); preference = new Preference(this); preference.getExtras().putBoolean("BROWSING_ALL", false); preference.getExtras().putBoolean("FOLDER", false); preference.getExtras().putString("PATH", ""); preference.setKey("watchlist"); preference.setTitle(R.string.goo_browse_watchlist); pScreen.addPreference(preference); } else { if ("watchlist".equals(CURRENT_FOLDER)) { PreferenceCategory category = new PreferenceCategory(this); category.setKey("category"); category.setTitle( getResources().getString(R.string.goo_category_title, new Object[] { CURRENT_FOLDER })); pScreen.addPreference(category); refreshWatchlist(); } else { PreferenceCategory category = new PreferenceCategory(this); category.setTitle( getResources().getString(R.string.goo_category_title, new Object[] { CURRENT_FOLDER })); pScreen.addPreference(category); try { JSONObject object = (JSONObject) new JSONTokener(CURRENT_NAVIGATION).nextValue(); JSONArray list = object.getJSONArray("list"); for (int i = 0; i < list.length(); i++) { JSONObject result = list.getJSONObject(i); String fileName = result.optString("filename"); if (fileName != null && !"".equals(fileName.trim())) { String path = result.optString("path"); if (!BROWSING_ALL && !mDevice.equals(result.optString("ro_board"))) { continue; } GooPackage info = new GooPackage(result, -1); mInfos.put(path, info); Preference preference = new Preference(this); preference.getExtras().putBoolean("FOLDER", false); preference.setKey(path); preference.setTitle(fileName); preference.setSummary(path); category.addPreference(preference); } else { String folder = result.optString("folder"); String folderName = folder.substring(folder.lastIndexOf("/") + 1); Preference preference = new FolderPreference(this, folder, false); preference.getExtras().putBoolean("BROWSING_ALL", BROWSING_ALL); preference.getExtras().putBoolean("FOLDER", true); preference.getExtras().putString("PATH", folder); if (!BROWSING_ALL) { preference.setKey(Constants.GOO_SEARCH_URL + folder + "&ro_board=" + mDevice); } else { preference.setKey(Constants.GOO_SEARCH_URL + folder); } preference.setTitle(folderName); preference.setSummary(folder); category.addPreference(preference); } } } catch (Exception ex) { ex.printStackTrace(); Toast.makeText(this, R.string.goo_browse_error, Toast.LENGTH_LONG).show(); } } } if (DIALOG != null) DIALOG.dismiss(); DIALOG = null; ListView listView = getListView(); listView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { ListView listView = (ListView) parent; ListAdapter listAdapter = listView.getAdapter(); Object obj = listAdapter.getItem(position); if (obj != null && obj instanceof View.OnLongClickListener) { View.OnLongClickListener longListener = (View.OnLongClickListener) obj; return longListener.onLongClick(view); } return false; } }); }
From source file:de.ub0r.android.callmeter.ui.prefs.PreferencesPlain.java
/** Load widget list. */ @SuppressWarnings("deprecation") private void loadWidgets() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); Preference p = findPreference("container"); if (p != null && p instanceof PreferenceScreen) { PreferenceScreen ps = (PreferenceScreen) p; ps.removeAll();/*from w w w .ja v a2 s . co m*/ int[] ids = AppWidgetManager.getInstance(this) .getAppWidgetIds(new ComponentName(this, StatsAppWidgetProvider.class)); boolean added = false; if (ids != null && ids.length > 0) { for (int id : ids) { if (prefs.getLong(StatsAppWidgetProvider.WIDGET_PLANID + id, -1) <= 0) { continue; } added = true; p = new Preference(this); p.setTitle(getString(R.string.widget_) + " #" + id); final int fid = id; p.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(final Preference preference) { Intent i = new Intent(PreferencesPlain.this, StatsAppWidgetConfigure.class); i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, fid); PreferencesPlain.this.startActivity(i); return true; } }); ps.addPreference(p); } } ids = AppWidgetManager.getInstance(this) .getAppWidgetIds(new ComponentName(this, LogsAppWidgetProvider.class)); if (ids != null && ids.length > 0) { for (int id : ids) { if (prefs.getLong(LogsAppWidgetProvider.WIDGET_PLANID + id, -1) <= 0) { continue; } added = true; p = new Preference(this); p.setTitle(getString(R.string.widget_) + " #" + id); final int fid = id; p.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(final Preference preference) { Intent i = new Intent(PreferencesPlain.this, LogsAppWidgetConfigure.class); i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, fid); PreferencesPlain.this.startActivity(i); return true; } }); ps.addPreference(p); } } if (!added) { p = new Preference(this); p.setTitle(R.string.widgets_no_widgets_); p.setSummary(R.string.widgets_no_widgets_hint); ps.addPreference(p); } } }
From source file:info.balthaus.geologrenewed.app.ui.SettingsFragment.java
@Override protected PreferenceScreen createPreferenceHierarchy(PreferenceManager prefMan) { PreferenceScreen root = prefMan.createPreferenceScreen(getActivity()); resources = getActivity().getResources(); prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); String app = APP_TITLE;/*from w ww . j ava2 s . c o m*/ PackageManager pm = getActivity().getPackageManager(); if (pm != null) { try { PackageInfo pi = pm.getPackageInfo(getActivity().getPackageName(), 0); if (pi != null) { app = app + " v" + pi.versionName; } } catch (Exception e) { } } Preference copyright = new Preference(getActivity()); copyright.setTitle(app); copyright.setSummary(APP_COPYRIGHT + (char) 10 + "Twitter: @ChainfireXDA" + (char) 10 + "G+: http://google.com/+Chainfire" + (char) 10 + S(R.string.settings_tap_xda)); copyright.setKey("copyright"); copyright.setEnabled(true); copyright.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(APP_WEBSITE_URL)); startActivity(i); } catch (Exception e) { // no http handler installed (wtf, it happens) } return false; } }); root.addPreference(copyright); /* maybe one day if (!proPresent) { Preference upgrade = new Preference(getActivity()); upgrade.setTitle(R.string.settings_upgrade); upgrade.setSummary(R.string.settings_upgrade_description); upgrade.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("market://details?id=eu.chainfire.geolog.pro")); startActivity(i); } catch (Exception e) { // no market installed } return false; } }); root.addPreference(upgrade); } */ PreferenceCategory catUnits = Pref.Category(getActivity(), root, R.string.settings_category_units); prefUnits = Pref.List(getActivity(), catUnits, getString(R.string.settings_units_caption), "", getString(R.string.settings_units_popup), PREF_UNITS, PREF_UNITS_DEFAULT, new String[] { getString(R.string.settings_units_metric), getString(R.string.settings_units_imperial) }, new String[] { VALUE_UNITS_METRIC, VALUE_UNITS_IMPERIAL }); PreferenceCategory catMarket = Pref.Category(getActivity(), root, R.string.settings_category_market); Pref.Preference(getActivity(), catMarket, R.string.settings_market, R.string.settings_market_description, true, new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("market://search?q=pub:Chainfire")); startActivity(i); } catch (Exception e) { // market not installed } return false; } }); Pref.Preference(getActivity(), catMarket, R.string.follow_pref_title, R.string.follow_pref_desc, true, new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { showFollow(false); return false; } }); int shown_follow = prefs.getInt(PREF_FOLLOW_SHOWN, 0); if (shown_follow == 0) { prefs.edit().putInt(PREF_FOLLOW_SHOWN, 1).commit(); showFollow(true); } updatePrefs(null); return root; }
From source file:eu.chainfire.geolog.ui.SettingsFragment.java
@Override protected PreferenceScreen createPreferenceHierarchy(PreferenceManager prefMan) { PreferenceScreen root = prefMan.createPreferenceScreen(getActivity()); resources = getActivity().getResources(); prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); String app = APP_TITLE;/* www . j a va 2s. c o m*/ PackageManager pm = getActivity().getPackageManager(); if (pm != null) { try { PackageInfo pi = pm.getPackageInfo(getActivity().getPackageName(), 0); if (pi != null) { app = app + " v" + pi.versionName; } } catch (Exception e) { } } Preference copyright = new Preference(getActivity()); copyright.setTitle(app); copyright.setSummary(APP_COPYRIGHT + (char) 10 + "Twitter: @ChainfireXDA" + (char) 10 + "G+: http://google.com/+Chainfire" + (char) 10 + S(R.string.settings_tap_xda)); copyright.setKey("copyright"); copyright.setEnabled(true); copyright.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(APP_WEBSITE_URL)); startActivity(i); } catch (Exception e) { // no http handler installed (wtf, it happens) } return false; } }); root.addPreference(copyright); /* maybe one day if (!proPresent) { Preference upgrade = new Preference(getActivity()); upgrade.setTitle(R.string.settings_upgrade); upgrade.setSummary(R.string.settings_upgrade_description); upgrade.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("market://details?id=eu.chainfire.geolog.pro")); startActivity(i); } catch (Exception e) { // no market installed } return false; } }); root.addPreference(upgrade); } */ PreferenceCategory catUnits = Pref.Category(getActivity(), root, R.string.settings_category_units); prefUnits = Pref.List(getActivity(), catUnits, getString(R.string.settings_units_caption), "", getString(R.string.settings_units_popup), PREF_UNITS, PREF_UNITS_DEFAULT, new String[] { getString(R.string.settings_units_metric), getString(R.string.settings_units_imperial) }, new String[] { VALUE_UNITS_METRIC, VALUE_UNITS_IMPERIAL }); PreferenceCategory catMarket = Pref.Category(getActivity(), root, R.string.settings_category_market); Pref.Preference(getActivity(), catMarket, R.string.settings_market, R.string.settings_market_description, true, new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { try { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("market://search?q=pub:Chainfire")); startActivity(i); } catch (Exception e) { // market not installed } return false; } }); Pref.Preference(getActivity(), catMarket, R.string.follow_pref_title, R.string.follow_pref_desc, true, new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { showFollow(false); return false; } }); int shown_follow = prefs.getInt(PREF_FOLLOW_SHOWN, 0); if (shown_follow == 0) { prefs.edit().putInt(PREF_FOLLOW_SHOWN, 1).commit(); showFollow(true); } updatePrefs(null); return root; }
From source file:im.vector.fragments.VectorRoomSettingsFragment.java
/** * Refresh the banned users list./* ww w. ja va2 s . c o m*/ */ private void refreshBannedMembersList() { ArrayList<RoomMember> bannedMembers = new ArrayList<>(); Collection<RoomMember> members = mRoom.getMembers(); if (null != members) { for (RoomMember member : members) { if (TextUtils.equals(member.membership, RoomMember.MEMBERSHIP_BAN)) { bannedMembers.add(member); } } } Collections.sort(bannedMembers, new Comparator<RoomMember>() { @Override public int compare(RoomMember m1, RoomMember m2) { return m1.getUserId().toLowerCase(VectorApp.getApplicationLocale()) .compareTo(m2.getUserId().toLowerCase(VectorApp.getApplicationLocale())); } }); PreferenceScreen preferenceScreen = getPreferenceScreen(); preferenceScreen.removePreference(mBannedMembersSettingsCategoryDivider); preferenceScreen.removePreference(mBannedMembersSettingsCategory); mBannedMembersSettingsCategory.removeAll(); if (bannedMembers.size() > 0) { preferenceScreen.addPreference(mBannedMembersSettingsCategoryDivider); preferenceScreen.addPreference(mBannedMembersSettingsCategory); for (RoomMember member : bannedMembers) { VectorCustomActionEditTextPreference preference = new VectorCustomActionEditTextPreference( getActivity()); final String userId = member.getUserId(); preference.setTitle(userId); preference.setKey(BANNED_PREFERENCE_KEY_BASE + userId); preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { Intent startRoomInfoIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class); startRoomInfoIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, userId); startRoomInfoIntent.putExtra(VectorMemberDetailsActivity.EXTRA_ROOM_ID, mRoom.getRoomId()); startRoomInfoIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); getActivity().startActivity(startRoomInfoIntent); return false; } }); mBannedMembersSettingsCategory.addPreference(preference); } } }
From source file:im.vector.fragments.VectorSettingsPreferencesFragment.java
/** * Refresh the ignored users list/* w w w .j a v a2 s. co m*/ */ private void refreshIgnoredUsersList() { List<String> ignoredUsersList = mSession.getDataHandler().getIgnoredUserIds(); Collections.sort(ignoredUsersList, new Comparator<String>() { @Override public int compare(String u1, String u2) { return u1.toLowerCase(VectorApp.getApplicationLocale()) .compareTo(u2.toLowerCase(VectorApp.getApplicationLocale())); } }); PreferenceScreen preferenceScreen = getPreferenceScreen(); preferenceScreen.removePreference(mIgnoredUserSettingsCategory); preferenceScreen.removePreference(mIgnoredUserSettingsCategoryDivider); mIgnoredUserSettingsCategory.removeAll(); if (ignoredUsersList.size() > 0) { preferenceScreen.addPreference(mIgnoredUserSettingsCategoryDivider); preferenceScreen.addPreference(mIgnoredUserSettingsCategory); for (final String userId : ignoredUsersList) { VectorCustomActionEditTextPreference preference = new VectorCustomActionEditTextPreference( getActivity()); preference.setTitle(userId); preference.setKey(IGNORED_USER_KEY_BASE + userId); preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { new AlertDialog.Builder(getActivity()) .setMessage(getString(R.string.settings_unignore_user, userId)) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); displayLoadingView(); ArrayList<String> idsList = new ArrayList<>(); idsList.add(userId); mSession.unIgnoreUsers(idsList, new ApiCallback<Void>() { @Override public void onSuccess(Void info) { onCommonDone(null); } @Override public void onNetworkError(Exception e) { onCommonDone(e.getLocalizedMessage()); } @Override public void onMatrixError(MatrixError e) { onCommonDone(e.getLocalizedMessage()); } @Override public void onUnexpectedError(Exception e) { onCommonDone(e.getLocalizedMessage()); } }); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); return false; } }); mIgnoredUserSettingsCategory.addPreference(preference); } } }
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(); }/*from w w w . ja v a2s . 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: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. j av a 2 s. co 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); }