@Override
  public void onClick(DialogInterface dialog, int button) {
    if (button == DialogInterface.BUTTON_POSITIVE) {
      // Always save the profile.
      VpnProfile profile = mDialog.getProfile();
      mKeyStore.put(Credentials.VPN + profile.key, profile.encode());

      // Update the preference.
      VpnPreference preference = mPreferences.get(profile.key);
      if (preference != null) {
        disconnect(profile.key);
        preference.update(profile);
      } else {
        preference = new VpnPreference(getActivity(), profile);
        preference.setOnPreferenceClickListener(this);
        mPreferences.put(profile.key, preference);
        getPreferenceScreen().addPreference(preference);
      }

      // If we are not editing, connect!
      if (!mDialog.isEditing()) {
        try {
          connect(profile);
        } catch (Exception e) {
          Log.e(TAG, "connect", e);
        }
      }
    }
  }
 @Override
 public void onSaveInstanceState(Bundle savedState) {
   // We do not save view hierarchy, as they are just profiles.
   if (mDialog != null) {
     VpnProfile profile = mDialog.getProfile();
     savedState.putString("VpnKey", profile.key);
     savedState.putByteArray("VpnProfile", profile.encode());
     savedState.putBoolean("VpnEditing", mDialog.isEditing());
   }
   // else?
 }
 private static List<VpnProfile> loadVpnProfiles(KeyStore keyStore, int... excludeTypes) {
   final ArrayList<VpnProfile> result = Lists.newArrayList();
   final String[] keys = keyStore.saw(Credentials.VPN);
   if (keys != null) {
     for (String key : keys) {
       final VpnProfile profile = VpnProfile.decode(key, keyStore.get(Credentials.VPN + key));
       if (profile != null && !ArrayUtils.contains(excludeTypes, profile.type)) {
         result.add(profile);
       }
     }
   }
   return result;
 }
  @Override
  public void onCreate(Bundle savedState) {
    super.onCreate(savedState);

    setHasOptionsMenu(true);
    addPreferencesFromResource(R.xml.vpn_settings2);

    if (savedState != null) {
      VpnProfile profile =
          VpnProfile.decode(savedState.getString("VpnKey"), savedState.getByteArray("VpnProfile"));
      if (profile != null) {
        mDialog = new VpnDialog(getActivity(), this, profile, savedState.getBoolean("VpnEditing"));
      }
    }
  }