从SharedPreferences读取后的Android ClassCastException

时间:2013-08-11 15:15:15

标签: android sharedpreferences classcastexception

昨天,我为我的Android应用程序构建了一个SettingsActivity,用户可以在其中输入webservice-server的URL。我使用以下方法保存:

editor = sharedPref.edit();
editor.putString(
    getString(R.string.SAVED_URL_MOBILEHELPER), lvsURL_mobilehelper);
editor.commit();

在按下“保存”按钮后的SharedPreferences中。

onStart()我读取了设置,将保存的值设置为所属文本字段:

// line 29
String lvsURL_mobilehelper = sharedPref.getString(
    getString(R.string.SAVED_URL_MOBILEHELPER), "");

昨天也运作良好;我输入并成功从设置中读取的最后一个字符串是“testURL12345”。

今天,我试图在我的应用程序周围添加用户身份验证,因此,当我打开SettingsActivity时,我得到ClassCastException

Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to
    java.lang.String
at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:224)
at de.unibonn.sdb.wissappmobile.activities.SettingsActivity.onResume(
    SettingsActivity.java:29)

有没有人知道为什么昨天一切正常,现在却没有?

注意:我不希望将用户凭据存储在AccountManager或我的偏好设置中,因为该应用程序应在“商务平板电脑”上使用,而不是“个人平板电脑”。 HTTP-Basic身份验证需要用户凭据。所以我的想法是检查父Activity是否用户“登录”并且不活动超过1800秒。

SettingsActivity:

/*
 * Activity for settings page (webservice URL)
 */
public class SettingsActivity extends AppFragmentActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
  }

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

    // Fill content

    // URL of the Mobile Helper
    String lvsURL_mobilehelper = sharedPref.getString(
        getString(R.string.SAVED_URL_MOBILEHELPER), "");
    EditText dfsURLMobileHelper = (EditText) findViewById(R.id.dfsURLMobileHelper);
    dfsURLMobileHelper.setText(lvsURL_mobilehelper);        
  }

  /*
   * Action called when pressing the "Save"-Button
   * 
   * Saves the entered Data in a local file.
   */
  public void ClickBtnSave(View view) {
    EditText dfsURLMobileHelper = (EditText) findViewById(R.id.dfsURLMobileHelper);
    TextView txtError = (TextView) findViewById(R.id.txtError);

    String lvsURL_mobilehelper = dfsURLMobileHelper.getText().toString();
    String Eceptiontext = "";

    Boolean success = false;

    // Write to file
    try {
      editor = sharedPref.edit();
      editor.putString(getString(R.string.SAVED_URL_MOBILEHELPER), lvsURL_mobilehelper);
      editor.commit();

      success = true;
    } catch (Exception e) {
      success = false;
      Eceptiontext = e.getLocalizedMessage();
    }

    if (success) {
      txtError.setText(getString(R.string.SAVING_SUCCESS));
    } else {
      txtError.setText(getString(R.string.SAVING_FAILED) + " : " +  Eceptiontext);
    }
  }     

  /*
   * Action called when pressing the "Back"-Button
   * 
   * Opens the Search-Acitivity
   */
  public void ClickBtnBack(View view) {
    // Back to SearchActivity
    Intent intent = new Intent(this, SearchActivity.class);
    startActivity(intent);
  }        
}

Parent AppFragmentActivity:

/**
 * Class to handle global Callbacks (e.g. user credentials)
 */
public class AppFragmentActivity extends FragmentActivity  {

  protected SharedPreferences sharedPref;
  protected SharedPreferences.Editor editor;    

  protected String WebServiceUsername;
  protected String WebServicePassword;


  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_appfragmentactivity);
  } 


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


    // Check if user is "logged in".
    // Meaning: Are there given user credentials and are they valid of was the user inactive for too long?

    // We only do this "onResume" because this callback is the only one, which is called everytime an user 
    // starts/restarts/resumes an application
    checkForUserCredentials();


    // Set new "last action" now "now"
    setLastAction(new Date().getTime());
  }

  @Override
  protected void onStart () {
    // Fill content
    super.onStart();

    // Set global sharedPreferences
    sharedPref = getSharedPreferences(
        getString(R.string.FILE_settings_file), Context.MODE_PRIVATE);
  }



  /*
   * Checks if user credentials are valid meaning if they are set and not too old
   */
  private void checkForUserCredentials() {
    // Get filehandle to PreferencesFile


    long TimeLastAction = sharedPref.getLong(
        getString(R.string.SETTINGS_USER_LAST_ACTION), 0);
    long TimeNow = new Date().getTime();

    // Ask for User credentials when last action is too long ago
    if(TimeLastAction < (TimeNow - 1800)) {
      // Inactive for too long

      // Set credentials back
      setUsernameAndPassword("", "");

    } else {
      WebServiceUsername = sharedPref.getString(
          getString(R.string.SETTINGS_USER_USERNAME), "");
      WebServicePassword = sharedPref.getString(
          getString(R.string.SETTINGS_USER_PASSWORD), "");              
    }
  }

  /*
   * Saves the given last action in the sharedPreferences
   * @param long LastAction - Time of the last action
   */
  private void setLastAction(long LastAction) {
    editor = sharedPref.edit();
    editor.putLong(getString(R.string.SETTINGS_USER_LAST_ACTION), LastAction);
    editor.commit();        
  }

  /*
   * Saves the given username and userpassword sharedPreferences
   * @param String username
   * @param String password
   */
  private void setUsernameAndPassword(String username, String password) {
    editor = sharedPref.edit();
    editor.putString(
        getString(R.string.SETTINGS_USER_USERNAME), username);
    editor.putString(
        getString(R.string.SETTINGS_USER_PASSWORD), username);
    editor.commit();    

    WebServiceUsername = username;
    WebServicePassword = password;
  } 

  /*
   * Method called when pressing the OK-Button
   */
    public void ClickBtnOK(View view) {
        // Save User-Creentials

      EditText dfsUsername = (EditText) findViewById(R.id.dfsUsername);
      String lvsUsername = dfsUsername.getText().toString();        

      EditText dfsPassword = (EditText) findViewById(R.id.dfsPassword);
      String lvsPassword = dfsPassword.getText().toString();        

      if(lvsUsername.equals("") || lvsPassword.equals("")) {
        TextView txtError = (TextView) findViewById(R.id.txtError);
        txtError.setText(getString(R.string.ERR_Name_or_Password_empty));
      } else {
        // Save credentials
        setUsernameAndPassword(lvsUsername, lvsPassword);
        setLastAction(new Date().getTime());

        // open Searchactivity
          Intent intent = new Intent(this, SearchActivity.class);
          startActivity(intent);            

      }
    }   

    @Override
    protected void onPause() {
      super.onPause();
      setLastAction(new Date().getTime());
    }

    @Override
  protected void onStop() {
    super.onStop();
    setLastAction(0);
    setUsernameAndPassword("", "");
  }
}

1 个答案:

答案 0 :(得分:0)

好吧,如果龙,可能是因为你把它放在那里。因为你正在使用R.string。有时它会弄乱资源ID,因此需要干净的项目,或者你的string.xml中的这些id有相同的字符串值。简单地说,在逻辑的某个地方你长期使用同一个键

P.S。我认为最佳做法是使用public static final String MY_PREFERENCE_KEY = "my_preference_key";