I am Having an Alert Dialog which has a edit text box and a password box.
On pressing positive button of Alert Dialog I want to save data once entered in it to my Preference login_prefs,xml. Can anyone please help me to call onSharedPreferencesChanged method so that I can save my values in it.
I tried many ways but I failed to achieve it.
Also can any one help me to retrieve the default value from the same
Thanks
Code:
public class LoginCredsHandlerDialog extends SherlockDialogFragment {
String Tag = getClass().getSimpleName(), idString, passString , idKey = "loginId", passKey = "pass";
View view;
EditText id, pass;
SharedPreferences loginPrefs;
OnSharedPreferenceChangeListener listen;
final Context context = getSherlockActivity();
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder loginMenu = new AlertDialog.Builder(getSherlockActivity());
LayoutInflater inflate = getSherlockActivity().getLayoutInflater();
view = inflate.inflate(R.layout.prefs_layout, null);
loginMenu.setView(view);
id = (EditText) view.findViewById(R.id.loginId);
pass = (EditText) view.findViewById(R.id.loginPass);
Log.i(Tag, "before prefreneces class");
new SaveData();
loginPrefs = PreferenceManager.getDefaultSharedPreferences(getSherlockActivity());
Log.i(Tag, "linked to prefrences class");
Log.i(Tag, "Got String Value");
loginMenu.setTitle("Login Prefrences Menu");
loginMenu.setCancelable(false);
loginMenu.setPositiveButton("Save", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.i(Tag, "Save Key Pressed");
new SaveData().onSharedPreferenceChanged(loginPrefs, idKey);
Log.i(Tag, "Values Saved");
}
});
loginMenu.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
LoginCredsHandlerDialog.this.getDialog().cancel();
}
});
return loginMenu.create();
}
public class SaveData extends SherlockPreferenceActivity implements OnSharedPreferenceChangeListener {
SharedPreferences spf;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.log_prefs);
loginPrefs = PreferenceManager.getDefaultSharedPreferences(getSherlockActivity());
idString = loginPrefs.getString(idKey, "");
passString = loginPrefs.getString(passKey, "");
if(idString.equals("") || passString.equals("")){
idString = id.toString();
passString = pass.toString();
}
id.setText(idString);
pass.setText(passString);
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key==idKey){
Log.i(Tag, "saver");
Preference pref = findPreference(key);
pref.setDefaultValue(sharedPreferences.getString(key, ""));
}
}
}
}
You do not call onSharedPreferencesChanged() function, it is call back function will be called when somebody change preference.
When you commit you login preference onSharedPreferencesChanged() will get called.
You can save value in preference like this:
loginPrefs.edit().putString("login_prefs", VALUE).commit();
Related
I am working on project, which simply validates through username and password.
I made some progress with using DialogFragments and AlertDialog. AlertDialog appears after starting the app over the mainactivity asking for username and password.
I must set the Alertdialog's setCanceledOnTouchOutside(false) and DialogFragment's setCancelable(false) because I don't want the users to dismiss it with pressing android's back button.
The problem is, after dismissing it programatically on successful login, if the activity becomes invisible and visible again , the Alertdialog's OnShowListener called, showing this AlertDialog again.
Can I somehow "detach" this AlertDialog from Activity? This popups also happen after unlocking the screen and getting back to activity which makes it very annoying...
Here is the code of interest:
MainActivity
public class MainActivity extends AppCompatActivity implements NoticeDialogFragment.NoticeDialogListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(GlobalInformations.getInstance().getUsername()==null){
shownoticeDialog();
}
}
public void shownoticeDialog(){
DialogFragment dialogFragment = new NoticeDialogFragment();
dialogFragment.show(getFragmentManager(), "NoticeDialogFragment");
}
#Override
public void onDismiss(DialogFragment dialog) {
//set the username on a TextView instance, etc...
}
NoticeDialogFragment extends DialogFragment
public class NoticeDialogFragment extends DialogFragment {
public interface NoticeDialogListener{
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
public void onDismiss(DialogFragment dialog);
}
NoticeDialogListener mListener;
static Activity activity = null;
//static String username;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activity = (Activity) context;
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e){
throw new ClassCastException(activity.toString() + "must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_signin, null);
final AutoCompleteTextView actv_username = (AutoCompleteTextView) view.findViewById(R.id.username);
final EditText password = (EditText) view.findViewById(R.id.password);
getavailableusernames(actv_username);
final AlertDialog dialog = new AlertDialog.Builder(new ContextThemeWrapper(getContext(), R.style.AlertDialogCustom))
.setView(view)
.setTitle("Login")
.setPositiveButton("OK", null)
//.setNegativeButton("Cancel", null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
final Button button =((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String passw = password.getText().toString();
String user = actv_username.getText().toString();
try{
if(user.length()<4 || passw.length()<4){
Toast.makeText(getContext(), "Username/password too short", Toast.LENGTH_SHORT).show();
dialog.show();
}
else {
//login to account, if success dismiss.
login(user, passw,dialog);
}
} catch(Exception e){
}
// dialog.dismiss();
}
});
}
});
dialog.setCanceledOnTouchOutside(false);
// set the DialogFragment to make the dialog unable to dismiss with back button
// (because not working if called on the dialog directly)
this.setCancelable(false);
return dialog;
}
public void login(final String username, String password, final AlertDialog dialog){
boolean login_success = false;
//query the credentials
login_success = dosomesqlquery(username, password);
if(login_success){
dialog.dismiss();
}
}
//passing the handling to activity...
#Override
public void onDismiss(DialogInterface dialog) {
mListener.onDismiss(NoticeDialogFragment.this);
}
}
Thank you for your help and patience.
Well this is that kind of situation where I end up heading my desk continously.
The source of the problem was I called dialog.dismiss() which dismisses the dialog, BUT not the dialogfragment itself, so will never, ever dismissed, even if the dialog disappeared from screen. Placing this.dismiss() in NoticeDialogFragment's onDismiss or anywhere else after login succeded will let the application act as it should.
#Override
public void onDismiss(DialogInterface dialog) {
mListener.onDismiss(NoticeDialogFragment.this);
this.dismiss(); //will dismiss the DialogFragment. Yeeey!
}
Thank you for your time and answers as they helped me point out the real problem. I will modify the code based on your suggestions.
An easier way is to use a static variable in your activity using two steps.
Declare a global static boolean
private static boolean session = false;
Check if the boolean has changed and if not, set the boolean to true when the dialog is shown
public void shownoticeDialog(){
if(session)return;
DialogFragment dialogFragment = new NoticeDialogFragment();
dialogFragment.show(getFragmentManager(), "NoticeDialogFragment");
session = true;
}
Set the value when the activity goes background
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("authUser", GlobalInformations.getInstance().getUsername()==null)
}
and read it when it comes back
#Override
protected void onCreate(Bundle savedInstanceState) {
if(savedInstanceState != null && savedInstanceState.containsKey("authUser")) {
boolean authUser = savedInstanceState.getBoolean("authUser", false);
if(authUser) {
//show or don't show dialog
}
}
}
I show a dialog where the user can enter a String value in an edittext and I want to display this value in an textview in the main layout after the dialog is dismissed. When the user clicks on the button "Ok" of the dialog, the textview is well refreshed, but I tried to do the same from the dismiss listener on the dialog it isn't, but I know the rest of the code is run. I tried to make it run on the mainthread but it didn't solve the problem. Here is the code, thanks for your help.
final Dialog dialogStatus = new Dialog(Activity.this);
dialogStatus.setContentView(R.layout.dialog_layout);
Button Bok = (Button) dialogStatus.findViewById(R.id.bt_dialog_ok);
final EditText ETname = (EditText) dialogStatus.findViewById(R.id.et_dialog);
Bok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
update(String.valueOf(ETname.getText()));
dialogStatus.dismiss();
}
});
dialogStatus.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
update(String.valueOf(ETname.getText()));
}
});
}
});
dialogStatus.show();
}
public void update(String etValue){
final SharedPreferences sharedPrefUnit = getSharedPreferences(SHARED_PREFS, 0);
SharedPreferences.Editor settings = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit();
settings.putString(STRING_VALUE, etValue);
TextView.setText(sharedPrefUnitScore.getString(STRING_VALUE, etValue, ""));
settings.commit();
}
public void update(String etValue){
final SharedPreferences sharedPrefUnit = getSharedPreferences(SHARED_PREFS, 0);
SharedPreferences.Editor settings = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit();
settings.putString(STRING_VALUE, etValue);
settings.commit();
TextView.setText(etValue);
}
Because you were trying to get the value from shared preference before committing it.
If you won't commit it then it won't save.
I get a Set from a sharedPreference, I add a value to it, it saves fine. But when I completely close down the app and reopen... that value is gone. THis problem does not happen while I am doing it in an activity, but only in my Spinner listener code.
Here is what I have tried: I passed in the preference and editor object from the activity to the listener class through it's constructor. Therefore, no need to initilize anything. I still get the same error.
Also, I tried to start a instance of the Activity and save do my saving there... but that didnt work either.
I was not able to provide you any code, because it is on a different computer... but the code is not the problem, because that same code works great in an activity
update: code added
public class SpinnerListener1 extends Activity
implements AdapterView.OnItemSelectedListener {
SpinnerAdpter spinnerAdapter1;
Spinner addCtAvail;
String type;
Context c;
SharedPreferences.Editor edit;
SharedPreferences prefs;
// String value;
public SpinnerListener1(SpinnerAdpter vSpinnerAdpter, Spinner vaddCtAvail, String type, Context ctx,SharedPreferences prefs ,SharedPreferences.Editor edit ){
this.spinnerAdapter1 = vSpinnerAdpter;
this.addCtAvail = vaddCtAvail;
this.type = type;
this.c = ctx;
this.prefs = prefs;
this.edit = edit;
}//SpinnerListener1
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String selection = ((TextView) view).getText().toString();
if (selection.equals("new")) {
AlertDialog.Builder builder11 = new AlertDialog.Builder(c);
builder11.setTitle("Add a new value to List");
builder11.setMessage("Please Enter a Value");
builder11.setCancelable(true);
builder11.setIcon(R.drawable.ic_launcher);
final EditText input = new EditText(c);
input.setId(0);
builder11.setView(input);
builder11.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Tabs1 tabInstance = new Tabs1();
String newCTvalue = input.getText().toString();
// have the new entry appear in spinner:
spinnerAdapter1.remove("new");
spinnerAdapter1.add(newCTvalue);
spinnerAdapter1.add("new");
addCtAvail.setAdapter(spinnerAdapter1);
addCtAvail.setSelection(spinnerAdapter1.getCount());
saveNewValue(newCTvalue, type);
}
})
.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder11.create().show();
}
}//onItemSelected
public void saveNewValue(String value, String prefname){
Set set = prefs.getStringSet(prefname,null);
set.add(value);
edit.putStringSet(prefname , set);
edit.commit();
}//saveNewValue
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}//SpinnerListener
here is the code for my TabActivity which launches this listner:
public void createSpinner(View view, String type, String texttoShow , Spinner addLoadType){
//prefs = PreferenceManager.getDefaultSharedPreferences(Tabs1.this);
prefs = getApplicationContext().getSharedPreferences("SpinnerPrefs", 0);
edit = prefs.edit();
getSpinnerSharedPref(type);
final SpinnerAdpter spinnerAdapterLoadType = new SpinnerAdpter(this);
spinnerAdapterLoadType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerListener1 spinnerlistenerLoadType = new SpinnerListener1(spinnerAdapterLoadType, addLoadType,type, Tabs1.this, prefs, editor);
addLoadType.setOnItemSelectedListener(spinnerlistenerLoadType);
getSpinnerPrefandPopulate(type,spinnerAdapterLoadType );
spinnerAdapterLoadType.add(texttoShow);
addLoadType.setAdapter(spinnerAdapterLoadType);
addLoadType.setSelection(spinnerAdapterLoadType.getCount()); //display hint
I'm trying to display preference screen and with a text box and doesn't show but in another screen it has no problem? It shows a negative 1 or null.
StatsActivity
public class StatsActivity extends Activity {
static final String TAG = "StatsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats_settings_layout);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\n" + sharedPrefs.getString("time_usage_key", "-1"));
TextView settingsTextViewStats = (TextView) findViewById(R.id.stats_settings_text_view);
settingsTextViewStats.setText(builder.toString());
}
}
StatsPrefsActivity
public class StatsPrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
static final String TAG = "StatsPrefsActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_stats);
PreferenceManager.setDefaultValues(this,R.xml.preferences_stats, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu.add(Menu.NONE, 0, 0, "Show current settings");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, StatsActivity.class));
return true;
}
return false;
}
#Override
public void onStart(){
super.onStart();
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(StatsPrefsActivity.this);
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences s = getSharedPreferences("MY_PREFS", 0);
// Create a editor to edit the preferences:
SharedPreferences.Editor editor = s.edit();
}
}
preference_stats.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Settings"
android:key="first_category">
<EditTextPreference
android:id="#+id/text_pref_box"
android:key="time_usage_key"
android:title="7 Day Usage"
android:summary="A total of usage of 7 days." />
</PreferenceCategory>
</PreferenceScreen>
if you want an inital value then set one. right now you have "-1" set as the default value. so if the preference has never been used before your going to get "-1" as the default. Try changing that to a blank string "" or something if you want better presentation.
How to make a preference activity where contain listpreference, where the summary will change based on selected listpreference item, and when certain list item is taped, it will show a edit text dialog which it will also become the the summary string value.
Thank in advance.
as requested, here my current code
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="#string/pref_category_general"
android:key="pref_category_general">
<CheckBoxPreference
android:key="pref_debug_mode"
android:title="#string/pref_debug_mode"
android:summary="#string/pref_debug_mode_summary"
android:defaultValue="false" />
<ListPreference
android:dependency="pref_debug_mode"
android:key="pref_remotehost"
android:title="#string/pref_remotehost"
android:dialogTitle="#string/pref_remotehost_dialog_title"
android:entries="#array/pref_remotehost_entries"
android:entryValues="#array/pref_remotehost_entries_values"
android:defaultValue="#string/pref_remotehost_default" />
</PreferenceCategory>
</PreferenceScreen>
and my activity
public class SettingActivity extends SherlockPreferenceActivity implements View.OnClickListener {
private MainApplication G;
private SherlockPreferenceActivity me;
private Intent intent;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.G = ((MainApplication) getApplicationContext());
assert this.G != null;
super.onCreate(bundle);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
// Add a button to the header list.
if (hasHeaders()) {
Button button = new Button(this);
button.setText("Some action");
setListFooter(button);
button.setOnClickListener(this);
}
PreferenceFragment prefFragment = new PreferenceGeneralFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, prefFragment);
fragmentTransaction.commit();
this.intent = getIntent();
this.me = this;
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onClick(View v) {
/*
switch (element.getId()) {
default:
return;
case R.id.setting_cancel_config:
onBackPressed();
return;
case R.id.setting_save_config:
int i = this.modeSpinner.getSelectedItemPosition();
boolean flag = true;
if (i == 1) {
flag = false;
};
MainApplication.setDeveloperMode(flag);
MainApplication.setRemoteHost(this.remoteHostEdittext.getText().toString());
SettingActivity.this.finish();
onBackPressed();
return;
}
*/
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
/**
* This fragment shows the preferences for the first header.
*/
public static class PreferenceGeneralFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure default values are applied. In a real app, you would
// want this in a shared function that is used to retrieve the
// SharedPreferences wherever they are needed.
//PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences_general, false);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences_general);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updatePrefSummary(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
}
}
i don't know where to start