0

我有一个非常不完整的 android 项目,它的设置选项有一个列表首选项。我想要做的是 - 从列表中永久隐藏字符黑名单选项,但它会在内部工作。为此我做了

<EditTextPreference android:key="preference_character_blacklist"
        android:title="Character blacklist"
        android:visibility="gone"/>

但它没有用。而是在我运行项目后进入设置时显示错误。设置看起来像这样-file:///home/Piyal/Desktop/Scr​​eenshot.png 我的preference.xml 是-

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<!-- GENERAL SETTINGS -->
<PreferenceCategory android:title="General settings">

    <CheckBoxPreference android:key="preference_capture_continuous"
        android:title="Continuous preview"
        android:entries="@array/capturemodes" />

    <ListPreference android:title="Recognize"
        android:key="sourceLanguageCodeOcrPref"
        android:entries="@array/languagenames"
        android:entryValues="@array/iso6393" />

</PreferenceCategory>

<!-- TRANSLATION SETTINGS -->
<PreferenceCategory android:title="Translation settings"
                    >

    <CheckBoxPreference android:key="preference_translation_toggle_translation"
        android:title="Translate"/>

    <ListPreference android:key="targetLanguageCodeTranslationPref"  
        android:title="Translate to"
        android:dependency="preference_translation_toggle_translation"
        android:entries="@array/translationtargetlanguagenames_google" 
        android:entryValues="@array/translationtargetiso6391_google" />

    <ListPreference android:key="preference_translator" 
        android:title="Translator"
        android:dependency="preference_translation_toggle_translation"
        android:entries="@array/translators" 
        android:entryValues="@array/translators"

         />


</PreferenceCategory>

<!-- ADVANCED SETTINGS -->
<PreferenceCategory android:title="Advanced settings">

    <ListPreference android:key="preference_ocr_engine_mode"
        android:title="OCR engine"
        android:entries="@array/ocrenginemodes"
        android:entryValues="@array/ocrenginemodes"/>

    <ListPreference android:key="preference_operator_mode"
        android:title="Operator"
        android:entries="@array/operatormodes"
        android:entryValues="@array/operatormodes"
        />

    <CheckBoxPreference
        android:key="preferences_auto_focus"
        android:title="Autofocus"/>

    <CheckBoxPreference
        android:key="preferences_play_beep"
        android:title="Beep"/>

    <EditTextPreference android:key="preference_character_blacklist"
        android:title="Character blacklist"/>

    <EditTextPreference

        android:key="preference_character_whitelist"
        android:title="Character whitelist"

        />


 <!-- 
    <CheckBoxPreference
        android:key="preference_toggle_light"
        android:title="Light"/>
-->

    <ListPreference android:key="preference_page_segmentation_mode"
        android:title="Page segmentation"
        android:entries="@array/pagesegmentationmodes"
        android:entryValues="@array/pagesegmentationmodes" />

    <CheckBoxPreference
        android:key="preferences_reverse_image"
        android:title="Reversed camera image"
        android:summary="(For devices with only a front camera)"/>

</PreferenceCategory>

  </PreferenceScreen>`

这是我的偏好-

    public class PreferencesActivity extends PreferenceActivity implements
  OnSharedPreferenceChangeListener {

  // Preference keys not carried over from R.M Theis project project
  public static final String KEY_OPERATOR_MODE = "preference_operator_mode";


  // Preference keys not carried over from ZXing project
  public static final String KEY_SOURCE_LANGUAGE_PREFERENCE = 

  "sourceLanguageCodeOcrPref";
  public static final String KEY_TARGET_LANGUAGE_PREFERENCE =  

"targetLanguageCodeTranslationPref";
  public static final String KEY_TOGGLE_TRANSLATION = 

"preference_translation_toggle_translation";
  public static final String KEY_CONTINUOUS_PREVIEW = 

"preference_capture_continuous";
  public static final String KEY_PAGE_SEGMENTATION_MODE = 

"preference_page_segmentation_mode";
  public static final String KEY_OCR_ENGINE_MODE = "preference_ocr_engine_mode";
  public static final String KEY_CHARACTER_BLACKLIST = 

"preference_character_blacklist";
  public static final String KEY_CHARACTER_WHITELIST = 

"preference_character_whitelist";
  public static final String KEY_TOGGLE_LIGHT = "preference_toggle_light";
  public static final String KEY_TRANSLATOR = "preference_translator";

  // Preference keys carried over from ZXing project
  public static final String KEY_AUTO_FOCUS = "preferences_auto_focus";
  public static final String KEY_HELP_VERSION_SHOWN = 

"preferences_help_version_shown";
  public static final String KEY_NOT_OUR_RESULTS_SHOWN = 

"preferences_not_our_results_shown";
  public static final String KEY_REVERSE_IMAGE = "preferences_reverse_image";
  public static final String KEY_PLAY_BEEP = "preferences_play_beep";
  public static final String KEY_VIBRATE = "preferences_vibrate";

  public static final String TRANSLATOR_BING = "Bing Translator";
  public static final String TRANSLATOR_GOOGLE = "Google Translate";

  //private CheckBoxPreference checkBoxPreferenceContinuousPreview;
  private ListPreference listPreferenceSourceLanguage;
  //private CheckBoxPreference checkBoxTranslate;
  private ListPreference listPreferenceTargetLanguage;  
  private ListPreference listPreferenceTranslator;
  private ListPreference listPreferenceOcrEngineMode;
  //private CheckBoxPreference checkBoxBeep;
  private EditTextPreference editTextPreferenceCharacterBlacklist;
  private EditTextPreference editTextPreferenceCharacterWhitelist;
  private ListPreference listPreferencePageSegmentationMode;
  //private CheckBoxPreference checkBoxReversedImage;

  private ListPreference listPreferenceOperatorMode;

  private static SharedPreferences sharedPreferences;

  /**
   * Set the default preference values.
   * 
   * @param Bundle
   *            savedInstanceState the current Activity's state, as passed by
   *            Android
   */
  @Override
  protected void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    getWindow().setBackgroundDrawableResource(R.drawable.background_holo_dark);
    addPreferencesFromResource(R.xml.preferences);

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    //checkBoxPreferenceContinuousPreview = (CheckBoxPreference) 

getPreferenceScreen().findPreference(KEY_CONTINUOUS_PREVIEW);
    listPreferenceSourceLanguage = (ListPreference) 

getPreferenceScreen().findPreference(KEY_SOURCE_LANGUAGE_PREFERENCE);
    //checkBoxTranslate = (CheckBoxPreference) 

getPreferenceScreen().findPreference(KEY_TOGGLE_TRANSLATION);
    listPreferenceTargetLanguage = (ListPreference) 

getPreferenceScreen().findPreference(KEY_TARGET_LANGUAGE_PREFERENCE);
    listPreferenceTranslator = (ListPreference) 

getPreferenceScreen().findPreference(KEY_TRANSLATOR);    
    listPreferenceOcrEngineMode = (ListPreference) 

getPreferenceScreen().findPreference(KEY_OCR_ENGINE_MODE);
    listPreferenceOperatorMode = (ListPreference)  

getPreferenceScreen().findPreference(KEY_OPERATOR_MODE);

    //checkBoxBeep = (CheckBoxPreference) 

getPreferenceScreen().findPreference(KEY_PLAY_BEEP);
    editTextPreferenceCharacterBlacklist = (EditTextPreference) 
getPreferenceScreen().findPreference(KEY_CHARACTER_BLACKLIST);
    editTextPreferenceCharacterWhitelist = (EditTextPreference) 
getPreferenceScreen().findPreference(KEY_CHARACTER_WHITELIST);
    listPreferencePageSegmentationMode = (ListPreference) 
getPreferenceScreen().findPreference(KEY_PAGE_SEGMENTATION_MODE);
    //checkBoxReversedImage = (CheckBoxPreference) 
getPreferenceScreen().findPreference(KEY_REVERSE_IMAGE);

    // Create the entries/entryvalues for the translation target language list.
    initTranslationTargetList();

  }

  /**
   * Interface definition for a callback to be invoked when a shared
   * preference is changed. Sets summary text for the app's preferences. Summary  
text values show the
   * current settings for the values.
   * 
   * @param sharedPreferences
   *            the Android.content.SharedPreferences that received the change
   * @param key
   *            the key of the preference that was changed, added, or removed
   */
  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
      String key) {    
    // Update preference summary values to show current preferences
    if (key.equals(KEY_TRANSLATOR)) {
      listPreferenceTranslator.setSummary(sharedPreferences.getString(key, 
CaptureActivity.DEFAULT_TRANSLATOR));
    } else if(key.equals(KEY_SOURCE_LANGUAGE_PREFERENCE)) {

      // Set the summary text for the source language name

  listPreferenceSourceLanguage.
setSummary(LanguageCodeHelper.getOcrLanguageName(getBaseContext(),  
sharedPreferences.getString(key,         
CaptureActivity.DEFAULT_SOURCE_LANGUAGE_CODE)));

      // Retrieve the character blacklist/whitelist for the new language
      String blacklist = OcrCharacterHelper.getBlacklist(sharedPreferences, 
listPreferenceSourceLanguage.getValue());
      String whitelist = OcrCharacterHelper.getWhitelist(sharedPreferences, 
listPreferenceSourceLanguage.getValue());

      // Save the character blacklist/whitelist to preferences
      sharedPreferences.edit().putString(KEY_CHARACTER_BLACKLIST, 
blacklist).commit();
      sharedPreferences.edit().putString(KEY_CHARACTER_WHITELIST, 
whitelist).commit();

      // Set the blacklist/whitelist summary text
      editTextPreferenceCharacterBlacklist.setSummary(blacklist);
      editTextPreferenceCharacterWhitelist.setSummary(whitelist);

    } else if (key.equals(KEY_TARGET_LANGUAGE_PREFERENCE)) {

listPreferenceTargetLanguage.
setSummary(LanguageCodeHelper.getTranslationLanguageName(this,  
sharedPreferences.getString(key,        
CaptureActivity.DEFAULT_TARGET_LANGUAGE_CODE)));
        } else if (key.equals(KEY_PAGE_SEGMENTATION_MODE)) {

listPreferencePageSegmentationMode.setSummary(sharedPreferences.getString(key,  
CaptureActivity.DEFAULT_PAGE_SEGMENTATION_MODE));
    } else if (key.equals(KEY_OCR_ENGINE_MODE)) {
      listPreferenceOcrEngineMode.setSummary(sharedPreferences.getString(key,  
CaptureActivity.DEFAULT_OCR_ENGINE_MODE));
    }
    else if (key.equals(KEY_OPERATOR_MODE))
    {
        listPreferenceOperatorMode.setSummary(sharedPreferences.getString(key, 
CaptureActivity.DEFAULT_OPERATOR_MODE));
    }  
    else if (key.equals(KEY_CHARACTER_BLACKLIST)) {  

      // Save a separate, language-specific character blacklist for this language
      OcrCharacterHelper.setBlacklist(sharedPreferences, 
          listPreferenceSourceLanguage.getValue(), 
          sharedPreferences.getString(key, 
OcrCharacterHelper.getDefaultBlacklist(listPreferenceSourceLanguage.getValue())));

      // Set the summary text
    editTextPreferenceCharacterBlacklist.
setSummary(sharedPreferences.getString(key, 
OcrCharacterHelper.getDefaultBlacklist(listPreferenceSourceLanguage.getValue())));

    } else if (key.equals(KEY_CHARACTER_WHITELIST)) {

      // Save a separate, language-specific character blacklist for this language
      OcrCharacterHelper.setWhitelist(sharedPreferences, 
          listPreferenceSourceLanguage.getValue(), 
          sharedPreferences.getString(key, 
OcrCharacterHelper.getDefaultWhitelist(listPreferenceSourceLanguage.getValue())));

      // Set the summary text
      editTextPreferenceCharacterWhitelist.
setSummary(sharedPreferences.getString(key, 
OcrCharacterHelper.getDefaultWhitelist  
(listPreferenceSourceLanguage.getValue())));

    }

    // Update the languages available for translation based on the current 
translator selected.
    if (key.equals(KEY_TRANSLATOR)) {
      initTranslationTargetList();
    }

  }

  /**
   * Sets the list of available languages and the current target language for 
translation. Called
   * when the key for the current translator is changed.
   */
  void initTranslationTargetList() {
    // Set the preference for the target language code, in case we've just 
switched from Google
    // to Bing, or Bing to Google.
    String currentLanguageCode = 
sharedPreferences.getString(KEY_TARGET_LANGUAGE_PREFERENCE, 
        CaptureActivity.DEFAULT_TARGET_LANGUAGE_CODE);

    // Get the name of our language
    String currentLanguage = 
LanguageCodeHelper.getTranslationLanguageName(getBaseContext(), 
        currentLanguageCode);
    String[] translators = getResources().getStringArray(R.array.translators);
    String translator = sharedPreferences.getString(KEY_TRANSLATOR, 
CaptureActivity.DEFAULT_TRANSLATOR);
    String newLanguageCode = "";
    if (translator.equals(translators[0])) { // Bing
      // Update the list of available languages for the currently-chosen 
translation API.

listPreferenceTargetLanguage.
setEntries(R.array.translationtargetlanguagenames_microsoft);
      listPreferenceTargetLanguage.
setEntryValues(R.array.translationtargetiso6391_microsoft);

      // Get the corresponding code for our language name
      newLanguageCode = TranslatorBing.toLanguage(currentLanguage);
    } else if (translator.equals(translators[1])) { // Google
      // Update the list of available languages for the currently-chosen 
translation API.
      listPreferenceTargetLanguage.
setEntries(R.array.translationtargetlanguagenames_google);
      listPreferenceTargetLanguage.
setEntryValues(R.array.translationtargetiso6391_google);

      // Get the corresponding code for our language name      
      newLanguageCode = TranslatorGoogle.toLanguage(currentLanguage);
    }

    // Store the code as the target language preference
    String newLanguageName = LanguageCodeHelper.
getTranslationLanguageName(getBaseContext(),
        newLanguageCode);
    listPreferenceTargetLanguage.
setValue(newLanguageName); // Set the radio button in the list

sharedPreferences.edit().putString(PreferencesActivity.KEY_TARGET_LANGUAGE_PREFERENCE, 
        newLanguageCode).commit();
    listPreferenceTargetLanguage.setSummary(newLanguageName);
  }

  /**
   * Sets up initial preference summary text
   * values and registers the OnSharedPreferenceChangeListener.
   */
  @Override
  protected void onResume() {
    super.onResume();
    // Set up the initial summary values
    listPreferenceTranslator.
setSummary(sharedPreferences.getString(KEY_TRANSLATOR, 
CaptureActivity.DEFAULT_TRANSLATOR));
    listPreferenceSourceLanguage.
setSummary(LanguageCodeHelper.getOcrLanguageName(getBaseContext(), 
sharedPreferences.getString     
(KEY_SOURCE_LANGUAGE_PREFERENCE, CaptureActivity.DEFAULT_SOURCE_LANGUAGE_CODE)));
    listPreferenceTargetLanguage.
setSummary(LanguageCodeHelper.getTranslationLanguageName(getBaseContext(), 
sharedPreferences.getString 
(KEY_TARGET_LANGUAGE_PREFERENCE, CaptureActivity.DEFAULT_TARGET_LANGUAGE_CODE)));
    listPreferencePageSegmentationMode.
setSummary(sharedPreferences.getString(KEY_PAGE_SEGMENTATION_MODE,
    CaptureActivity.DEFAULT_PAGE_SEGMENTATION_MODE));
    listPreferenceOcrEngineMode.
setSummary(sharedPreferences.getString(KEY_OCR_ENGINE_MODE, 
CaptureActivity.DEFAULT_OCR_ENGINE_MODE));
    listPreferenceOperatorMode.
setSummary(sharedPreferences.getString(KEY_OPERATOR_MODE, 
CaptureActivity.DEFAULT_OPERATOR_MODE));
    editTextPreferenceCharacterBlacklist.
setSummary(sharedPreferences.getString(KEY_CHARACTER_BLACKLIST,     
OcrCharacterHelper.getDefaultBlacklist(listPreferenceSourceLanguage.getValue())));
   editTextPreferenceCharacterWhitelist.
setSummary(sharedPreferences.getString
(KEY_CHARACTER_WHITELIST,OcrCharacterHelper.getDefaultWhitelist 
(listPreferenceSourceLanguage.getValue())));

    // Set up a listener whenever a key changes
    getPreferenceScreen().
getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
  }

  /**
   * Called when Activity is about to lose focus. Unregisters the
   * OnSharedPreferenceChangeListener.
   */
  @Override
  protected void onPause() {
    super.onPause();
    getPreferenceScreen().
getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
  }
}       

`

添加 getPreferenceScreen().removePreference(editTextPreferenceCharacterBlacklist) 后的堆栈跟踪;

在 onCreate() 中。

05-30 17:42:00.546: E/AndroidRuntime(379): FATAL EXCEPTION: main

05-30 17:42:00.546: E/AndroidRuntime(379): java.lang.RuntimeException: Unable to start 
activity  
ComponentInfo{automated.card.recharge.ocr/automated.card.
recharge.ocr.PreferencesActivity}: java.lang.NullPointerException
05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.app.ActivityThread.access$1500(ActivityThread.java:117)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.os.Handler.dispatchMessage(Handler.java:99)

05-30 17:42:00.546: E/AndroidRuntime(379):  at android.os.Looper.loop(Looper.java:123)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.app.ActivityThread.main(ActivityThread.java:3683)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
java.lang.reflect.Method.invokeNative(Native Method)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
java.lang.reflect.Method.invoke(Method.java:507)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)

05-30 17:42:00.546: E/AndroidRuntime(379):  at dalvik.system.NativeStart.main(Native 
Method)

05-30 17:42:00.546: E/AndroidRuntime(379): Caused by: java.lang.NullPointerException

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.preference.PreferenceGroup.removePreferenceInt(PreferenceGroup.java:181)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 

android.preference.PreferenceGroup.removePreference(PreferenceGroup.java:174) 

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
automated.card.recharge.ocr.PreferencesActivity.onCreate(PreferencesActivity.java:103)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

05-30 17:42:00.546: E/AndroidRuntime(379):  at  
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)

05-30 17:42:00.546: E/AndroidRuntime(379):  at dalvik.system.NativeStart.main(Native  
Method)

05-30 17:42:00.546: E/AndroidRuntime(379): Caused by: java.lang.NullPointerException

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.preference.PreferenceGroup.removePreferenceInt(PreferenceGroup.java:181)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.preference.PreferenceGroup.removePreference(PreferenceGroup.java:174)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
automated.card.recharge.ocr.PreferencesActivity.onCreate(PreferencesActivity.java:103)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

05-30 17:42:00.546: E/AndroidRuntime(379):  at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
4

1 回答 1

1

You should be able to remove:

<EditTextPreference android:key="preference_character_blacklist"
        android:title="Character blacklist"
        android:visibility="gone"/>

from your preferences.xml. This will stop it from appearing in the Settings menu.

For the setting to work internally I would suggest reading into SharedPreferences. The Android Storage Options Guide will explain how you can store and retrieve setting values using SharedPreferences.

I've modified the following example to store a string from the guide linked above:

public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

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

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       String silent = settings.getString("character_blacklist", "");
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      //Some test characters for the blacklist
      mBlackListChars = "a,g,t,h,f";
      editor.putString("character_blacklist", mBlackListChars);

      // Commit the edits
      editor.commit();
    }
}

Please note you will probably want to call these methods outside of onCreate() and onStop(), this is purely for illustration. In addition I'll draw your attention to the fact SharedPreferences can handle a StringSet which may be useful to you in storing multiple characters. See the getStringSet() method in SharedPreferences.

UPDATE

In order to keep the preference but just hide it from the user you could remove it programatically. Seems like a bit of a hack but consider adding this to your 'OnCreate()' in your 'PreferenceActivity'

getPreferenceScreen().removePreference(editTextPreferenceCharacterBlacklist);

UPDATE

Looks like your problem is caused by editTextPreferenceCharacterBlacklist being null. Problem because it's not been set to your instance variable at the point you are running the line I specified. You could try finding it as follows:

getPreferenceScreen().removePreference(getPreferenceScreen().findPreference(KEY_CHARACTER_BLACKLIST));

于 2013-05-28T14:40:59.787 回答