SharedPreferences Settings issue

I have Settings retrieval issue in SettingsActivity.it is always giving me the last saved value.
Though MainActivity giving me the correct value as soon as Settings Activity is closed.

For Example:-

  1. Main Activity is launched first
  2. Clicked Settings menu button
  3. SettingsActivity is launched
  4. Select preference “Set username”
  5. Opens dialog and fill name say “test”, hit ok
  6. while retrieving “Set username” value in SettingsActivity, it gives the me the last value(blank if nothing was there or last valid value)
  7. Exit settings, MainActivity is launched. Now valid value of “Set username” is appeared as “test”

ISSUE:- Why SettingsActivity is not giving me lastest value of “Set username” as “test”

I am very new to this, Please help …

Following are my source/xml files

MainActivity.java


package com.example.settingsexample;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static final int RESULT_SETTINGS = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		TextView settingsTextView1 = (TextView) findViewById(R.id.textUserSettings1); 
        settingsTextView1.setText("    Settings:- ");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_settings, menu);
		return true;
	}
	
	
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	
        switch (item.getItemId()) 
        {
        case R.id.menu_settings:	
	        Intent i = new Intent(this, UserSettingActivity.class);
            startActivityForResult(i, RESULT_SETTINGS);
        return true;
        
        default:
        	Toast.makeText(getApplicationContext(), "nothing", Toast.LENGTH_SHORT).show();
        return super.onOptionsItemSelected(item);
        }
        
    }
    
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
 
        switch (requestCode) {
        case RESULT_SETTINGS:
            showUserSettings();
            break;
 
        } 
    }
 
    private void showUserSettings() {
        SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this);
 
        StringBuilder builder = new StringBuilder();
 
        builder.append("Username:     "
                + sharedPrefs.getString("prefUsername", "NULL"));
          
        Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
        
        TextView settingsTextView = (TextView) findViewById(R.id.textUserSettings); 
        settingsTextView.setText(builder.toString());
    }

}



SettingsActivity.java


package com.example.settingsexample;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;
 
public class UserSettingActivity extends PreferenceActivity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
         addPreferencesFromResource(R.xml.preference_settings);
         
         final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); 
         
 		//----------------------------user name-----------------------------------------
 		this.findPreference("prefUsername").setOnPreferenceChangeListener(
 	            new OnPreferenceChangeListener() {
 	            	
 					@Override
 	                public boolean onPreferenceChange(Preference preference,Object newValue) 
 	                {
 	                    Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_SHORT).show();
 	                    
 	                    SharedPreferences.Editor editor = sharedPrefs.edit();		                                        
 	                    String Username = sharedPrefs.getString("prefUsername", "NULL");
 	                    Toast.makeText(getApplicationContext(), "Value before:- "+Username, Toast.LENGTH_SHORT).show();
 	                    
 	                    editor.putString("prefUsername",Username); 
 	                    editor.commit();
 	                    
 	                    Username = sharedPrefs.getString("prefUsername", "NULL");
 	                    Toast.makeText(getApplicationContext(), "Value after:- "+Username, Toast.LENGTH_SHORT).show();
 	                    
 	                    return true;
 	                }

 	            });
 		//---------------------------- user name-----------------------------------------
 		
    }
}



My Apology, i have posted the SettingsActivity.java code correctly now (earlier it was same as MainActivity.java).

Please reply me now. Thanks in advance

did i post in the wrong area?

please suggest me the correct place or any other forum where i can expect the answers.

thought like this forum is filled with rich experienced developers.

Your 2 activities above are the same. Please post the SettingsActivity.java code.

mrBruce,
My Apology, i have posted the SettingsActivity.java code correctly now (earlier it was same as MainActivity.java).

Please reply me now. Thanks in advance

Please suggest something on this OR give me some initial pointer to solve this problem.

I am new and do not know any other Android Forum. i came to know about this forum recently.

Please direct me some where.

Hi,

You have 2 mistakes:

  1. you are getting the old value and committing the old value back, so you changed nothing:

String Username = sharedPrefs.getString(“prefUsername”, “NULL”);
Toast.makeText(getApplicationContext(), "Value before:- "+Username, Toast.LENGTH_SHORT).show();

editor.putString(“prefUsername”,Username);
editor.commit();

  1. Even if the above code was corrected, it’s irrelevant because the new pref value hasn’t been committed by the system yet. The new pref value is available to you in the parameter “Object newValue”

The system commits the value after the function returns true, so anything you commit will be overridden unless you make it return false.

String Username = newValue.toString();

// do something with Username if needed

sharedPrefs.edit().putString(“prefUsername”,Username).commit();

return false;

Or just leave the function empty and return true and the value will set itself.

mrBruce,
Many Many Thanks to the needful solution.

You explained what i was really missing. thanks a lot. I understood it literally now.

I hope i could contribute to this forum soon.

No problemo.

i came to know about this forum recently.