After Changing text in setting activity,it is not getting reflected - android

Am making my first android application with the help of Udacity's tutorial(Weather App).
For setting activity, I have one text box,which holds the location value.
For example say, Texas.
But when am changing that to any other value,it's not reflecting the same in the app. Though,the value in that text box is getting changed.
In the app's SettingActivity I have following code,
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
But as of today addPreferencesFromResource is deprecated,so am not really sure how to proceed in this regard. What do I change it with?
My goal is to change the value in Location's text and when I go on my mainActivity,the weather data should reflect the changed location's data.
Thanks.
Edit:
public class MainActivityFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
private void updateWeather()
{
FetchWeatherTask weatherTask = new FetchWeatherTask();
SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(getActivity());
String location=prefs.getString(getString(R.string.pref_location_key),getString(R.string.pref_location_default));
weatherTask.execute(location);
}
#Override
public void onStart()
{
super.onStart();
updateWeather();
}
Above is the code through which I update the value.
public class SettingsActivity extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
setupActionBar();
}
Above is the code from settingActivity. But as I said, addPreferencesFromResource is deprecated. So this part of code is not really working.

Create a separate class as below to handle all the prefs related operations, storing and restoring...
public class MyPrefs {
Context context;
SharedPreferences systemPrefs;
SharedPreferences.Editor editor;
static MyPrefs prefs;
public static final String DEFAULT_LOCATION = "DEFAULT_LOCATION";
public static final String SOME_DEFAULT_LOCATION = "London";
public static MyPrefs getInstance(Context context){
if(prefs == null){
prefs = new MyPrefs(context);
}
return prefs;
}
private MyPrefs(Context context) {
this.context = context;
this.systemPrefs = context.getSharedPreferences(Constants.USER_PREFS, Activity.MODE_PRIVATE);
this.editor = systemPrefs.edit();
}
public String getDefaultLocation(){
return systemPrefs.getString(DEFAULT_LOCATION, SOME_DEFAULT_LOCATION);
}
public void setDefaultLocation(String newLocation){
editor.putString(DEFAULT_LOCATION, newLocation);
editor.commit();
}
public void clear() {
editor.clear();
editor.commit();
}
}
And to use this in any activity class...
MyPrefs myPrefs = MyPrefs.getInstance(this);
//To get the location stored in prefs
String locationFromPrefs = myPrefs.getDefaultLocation();
//To store the location in prefs
myPrefs.setDefaultLocation("New York");

Related

Don't read sharedPreferences from another class

I'm trying to get my app to look first if shared preferences is set. If not it must open a page where you type them in, and then hopefully save them which I will use later. It looks like it either finds some shared preferences or my code is wrong because the main activity opens (the else statement executes).
Here is my Mainactivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean check = sharedPreferences.getBoolean("Check",false);
if(check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
And here is the SharedPrefs:
public class SharedPrefs extends MainActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
I must be honest I'm not quite sure where I want Java to look for Shared preferences, "this makes the app run at least.
Inside the SharedPrefs{} class, declare the variable
public static boolean CHECK_VALUE = false;
In the same class inside onClick(View v) method after editor.commit();, set
CHECK_VALUE = true;
And in MainActivity{} class inside OnCreate() method
if(!SharedPrefs.CHECK_VALUE){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}
Actually you don't need a SharedPreference to check here. If you really do, then put
editor.putBoolean("check", true);
insideOnClick() method of SharedPrefs{} class and to get it from or to use it in MainActivity
SharedPreferences sharedPreferences = getSharedPreferences(SharedPrefs.MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Check = sharedPreferences.getBoolean("check", false);
if(!check){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}

Save the state of a ToggleButton using SharedPreferences

I have seen other similar questions, but none are working out! I have a toggle button. I want to save the state of the ToggleButton (checked true or false) even when the app is closed/reopened.
My code looks like this below, but it will not run
public class MainActivity extends AppCompatActivity {
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void savePreference(Context context)
{
SharedPreferences.Editor editor = context.getSharedPreferences("toggleState1", 0).edit();
editor.putBoolean("toggleState1", toggle1.isChecked());
editor.commit();
}
private void loadPreference (Context context)
{
SharedPreferences prefs = context.getSharedPreferences("toggleState1", 0);
toggle1.setChecked(prefs.getBoolean("toggleState1", false));
}};
Thanks for the help!
ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);
should be INSIDE onCreate(), make it the last statement.
Also, it's easier to use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
Alright I have the answer for future reference. My original attempt did not use shared preferences properly. You must create a "key" and a "name" for the shared preference object. Then call it in code as follows:
public class MainActivity extends AppCompatActivity {
private static final String APP_SHARED_PREFERENCE_NAME = "AppSharedPref";
private final static String TOGGLE_STATE_KEY1 = "TB_KEY1";
ToggleButton toggle1;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences(APP_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
toggle1 = (ToggleButton) findViewById(R.id.toggle1);
toggle1.setChecked(GetState());
toggle1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
SaveState(isChecked);
}
});
}
private void SaveState(boolean isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(TOGGLE_STATE_KEY1, isChecked);
editor.commit();
}
public boolean GetState() {
return sharedPreferences.getBoolean(TOGGLE_STATE_KEY1, false);
}
}

EditTextPreference validate data before saving

I have a method to validate a EditTextPreference. My method is executed after the confirmation of data by implementing the onSharedPreferenceChanged class.
However, only occurs after you confirm the information. I would perform the check without closing the dialog box. And if ok then close or keep open for user to enter the data correctly.
If it's not possible, I would reopen the dialog box if the validation is false.
SettingsActivity.java
class SettingsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
protected static final String TAG = "SettingsActivity";
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
SharedPreferences.Editor prefEditor = prefs.edit();
if(key.equals("pref_Url")){
String url = prefs.getString(key, "");
boolean response = (!new ConnectUtils().isConnected(this, url));
if(!response){
prefEditor.putString(key, Config.SERVER_URL_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(this,R.string.msgToast_server_url_invalid,Toast.LENGTH_SHORT).show();
}
}else if (key.equals("pref_Id")){
String url = Config.SERVER_URL_ID;
boolean reponse = (!new ConnectUtils().isConnected(this,url));
if(!reponse){
prefEditor.putString(key,Config.ID_DEF_VALUE);
prefEditor.commit();
reload();
Toast.makeText(Config.getContext(), R.string.msgToast_Id_invalid, Toast.LENGTH_SHORT).show();
}
}
}
private void reload(){
startActivity(getIntent());
finish();
}
}
'onPreferenceChangeListener' is a listener that is executed every time a preference is changed by the user. You can return true if data complains validation or false otherwise.
For example:
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference("pre_mail").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return Pattern.matches(Constants.MAILPATTERN, (String) newValue);
}
});
}
}
Hope this help!

IllegalArgumentException, path separatos. The application takes .xml.xml

I have an activity which needs to modify the SharedPreferences.
public class AddingEmail extends ListActivity implements OnClickListener{
private String newMail;
private SharedPreferences prefs;
private PreferenceManager prefMan;
private EditText emailAdd;
private EditText emailDel;
private ArrayList<String> prefList;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.addingemail);
Log.d("On Addig EMAIL ACTIVITY","on Create");
String name = "com.example.daemon3_preferences";
prefs = this.getSharedPreferences(name, MODE_PRIVATE);
And this is the PreferenceScreen..
public class PreferencesScreen extends PreferenceFragment{
private final String TAG = "PreferencesScreen";
private Set<String> emails;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate");
addPreferencesFromResource(R.xml.prefs);
And I have this error:
java.lang.IllegalArgumentException: File /data/data/com.example.daemon3/shared_prefs/com.example.daemon3_preferences.xml.xml contains a path separator
Why it takes .xml.xml instead of .xml?
Breaking out the comment thread into a formal answer here.
Instead of calling
String name = "com.example.daemon3_preferences";
prefs = this.getSharedPreferences(name, MODE_PRIVATE);
call this:
prefs = PreferenceManager.getDefaultSharedPreferences(this);
PreferenceFragment saves your settings with the PreferenceManager so by attempting to open the default preferences with getSharedPreferences, you might be interfering with the PreferenceManager which could be causing that particular exception.

SharedPreference problem in android

public class WordDisplay extends Activity {
private int level;
private int group;
private int set;
private WordDisplay mContext=this;
private int l;
private int g;
private int s;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wordset);
set_Word_Display_Event();
loadPreferences();
}
protected void loadPreferences() {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
// preferences = getSharedPreferences("one", Context.MODE_PRIVATE);
l= preferences.getInt("Level", 0);
g=preferences.getInt("Group", 0);
s= preferences.getInt("Set", 0);
// Log.d("lll"," - "+preferences.getInt("level",0));
}
#Override
protected void onStop() {
super.onStop();
savePreferences(this.level,this.group,this.set);
}
protected void savePreferences(int level, int group, int set) {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
//preferences = getSharedPreferences("one", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("Level", l);
editor.putInt("Group", g);
editor.putInt("Set", s);
editor.commit();
//return getPreferences(s).getInt("Set", 0);
}
}
Here, my data could not persist properly. what is the wrong my code. please give good convenience.
Comments of the above code, Also checking but could not any effect.
First, onStop() "might" never be called (see Activity life cycle), practice is to save your data in the onPause() method.
Maybe try to add more logs to see what's going on?
is onStop() called?
what are the saved / loaded values?
etc.
Try it with a final string constant in your class:
public static final String PREFS_NAME = "MyPreferences";
and then always use the member function:
getSharedPreferences(PREFS_NAME, 0);
normally there is no magic to do.
http://developer.android.com/guide/topics/data/data-storage.html#pref

Categories

Resources