Guardar en SharedPreferences desde DialogPreference personalizado

Actualmente tengo una pantalla de preferencias y he creado una clase personalizada que extiende DialogPreference y se llama desde mis preferencias. Mis datos de preferencias parece almacenar / recuperar de SharedPreferences sin un problema, pero estoy tratando de agregar 2 conjuntos más de configuración de DialogPreference .

Básicamente tengo dos problemas que no he podido encontrar. Cada sitio que he visto me da la misma información estándar para guardar / restaurar datos y sigo teniendo problemas. En primer lugar estoy tratando de guardar un nombre de usuario y contraseña a mi SharedPreferences (visible en el último bloque de código) y si posiblemente me gustaría ser capaz de hacerlo en el onClick() .

Mis preferencias XML que llama a mi DialogPreference :

 <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory> <com.rone.optusmon.AccDialog android:key="AccSettings" android:title="Account Settings" android:negativeButtonText="Cancel" android:positiveButtonText="Save" /> </PreferenceCategory> </PreferenceScreen> 

Mi archivo de clase de DialogPreference personalizado:

 package com.rone.optusmon; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.preference.DialogPreference; import android.preference.PreferenceManager; import android.text.method.PasswordTransformationMethod; import android.util.AttributeSet; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class AccDialog extends DialogPreference implements DialogInterface.OnClickListener { private TextView mUsername, mPassword; private EditText mUserbox, mPassbox; CharSequence mPassboxdata, mUserboxdata; private CheckBox mShowchar; private Context mContext; private int mWhichButtonClicked; public AccDialog(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; } @Override protected View onCreateDialogView() { // Access default SharedPreferences @SuppressWarnings("unused") SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext); @SuppressWarnings("unused") LinearLayout.LayoutParams params; LinearLayout layout = new LinearLayout(mContext); layout.setOrientation(LinearLayout.VERTICAL); layout.setPadding(10, 10, 10, 10); layout.setBackgroundColor(0xFF000000); mUsername = new TextView(mContext); mUsername.setText("Username:"); mUsername.setTextColor(0xFFFFFFFF); mUsername.setPadding(0, 8, 0, 3); mUserbox = new EditText(mContext); mUserbox.setSingleLine(true); mUserbox.setSelectAllOnFocus(true); mPassword = new TextView(mContext); mPassword.setText("Password:"); mPassword.setTextColor(0xFFFFFFFF); mPassbox = new EditText(mContext); mPassbox.setSingleLine(true); mPassbox.setSelectAllOnFocus(true); mShowchar = new CheckBox(mContext); mShowchar.setOnCheckedChangeListener(mShowchar_listener); mShowchar.setText("Show Characters"); mShowchar.setTextColor(0xFFFFFFFF); mShowchar.setChecked(false); if(!mShowchar.isChecked()) { mPassbox.setTransformationMethod(new PasswordTransformationMethod()); } layout.addView(mUsername); layout.addView(mUserbox); layout.addView(mPassword); layout.addView(mPassbox); layout.addView(mShowchar); return layout; } public void onClick(DialogInterface dialog, int which) { mWhichButtonClicked = which; // if statement to set save/cancel button roles if (mWhichButtonClicked == -1) { Toast.makeText(mContext, "Save was clicked\nUsername: " + mUserbox.getText().toString() +"\nPassword is: " + mPassbox.getText().toString(), Toast.LENGTH_SHORT).show(); // Save user preferences SharedPreferences settings = getDefaultSharedPreferences(this); SharedPreferences.Editor editor = settings.edit(); editor.putString("usernamekey", mUserbox.getText().toString()); editor.putString("passwordkey", mPassbox.getText().toString()); editor.commit(); } else { Toast.makeText(mContext, "Cancel was clicked", Toast.LENGTH_SHORT).show(); } } } 

Mi código de prueba de actividad principal:

 public void onResume() { super.onResume(); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); StringBuilder builder = new StringBuilder(); builder.append("\nThe monitor will refresh every "+ pref.getString("refreshfreq", "30 minutes")); builder.append("\nThe skin chosen is "+ pref.getString("skinkey", "null")); builder.append("\nThe style chosen is "+ pref.getString("stylekey", "% used")); builder.append("\nThe font chosen is "+ pref.getString("fontkey", "Calibri")); builder.append("\nThe font color is "+ pref.getString("fontcolkey", "White")); builder.append("\nYour username is "+ pref.getString("usernamekey", "not set yet")); builder.append("\nYour password is "+ pref.getString("passwordkey", "not set yet")); Toast.makeText(Optusmon.this, builder.toString(), Toast.LENGTH_LONG).show(); } 

En mis SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); Line, Eclipse dice "El método getDefaultSharedPreferences (AccDialog) no está definido para el tipo AccDialog". He intentado cambiar el contexto a mi clase de preferencias, utilizar un contexto vacío y también he intentado nombrar mis SharedPrefs y usar getSharedPreferences() también. No sé exactamente qué estoy haciendo aquí.

Como soy bastante nuevo en Java / Android / codificación en general, podría por favor ser tan detallado como sea posible con cualquier ayuda, por ejemplo. Que de mis archivos necesito escribir el código en y el paradero en ese archivo debo escribirlo (es decir onCreate() , onClick() , etc)

En el onCreate() que volvió antes de ejecutar esta línea, por lo que Eclipse dice que es inalcanzable. En su onClick() pruebe:

 SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext); 

debería estar bien

 SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext); 
  • ¿Cuál es la diferencia entre las entradas y los valores de entrada en android listPreferences xml?
  • ¿Cómo usar SharedPreferences como LocalStore, de manera más genérica?
  • ¿Qué pasará con SharedPreferences al actualizar una aplicación de Android?
  • SharedPreferences no se actualiza
  • No se puede poner doble SharedPreferences
  • Cómo evitar que una preferencia compartida sea clara al establecer
  • Android SharedPreferences, cómo guardar una variable int simple
  • SharedPreferences Valor largo
  • SharedPreferences y PreferenceFragment
  • ¿Restablecer SharedPreferences?
  • Android se niega a escribir / crear archivos de preferencias compartidas
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.