How to replace one string with another in whole application in android? - android

I have to change one text with another when user select option from settings,For example
I have to change Kilometers in to miles when user select it from option. And When i select it
i have to change kilometer into Miles thought the application , Please help me if anyone knows
how to do it?

Declare these globally for convenience:
SharedPreferences sharedPrefs;
Editor editor;
private static final String PRIVATE_PREF = "current_selection";
And then in the onCreate() or it's equivalent:
sharedPrefs = getApplicationContext().getSharedPreferences(PRIVATE_PREF, Context.MODE_PRIVATE);
// SET THE DEFAULT VALUE
editor = sharedPrefs.edit();
editor.putString("value", "kilometers");
// DONT SKIP THIS STEP
editor.commit();
Finally, wherever you need to check which of the two is the current selected value (Kilometers / Miles):
String strSetting = sharedPrefs.getString("value", null);
Now, you can use the String strSetting to check the value of the setting, and run the appropriate code. I am assuming it has something to do with conversion perhaps.
NOTE: If you are using the above (retrieving) in another Activity, you will need to instantiate this again:
SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences(PRIVATE_PREF, Context.MODE_PRIVATE);
String strSetting = sharedPrefs.getString("value", null);
Anytime you want to change the setting, just use the first piece of code. For example, if you change from Kilometers to Miles:
// SET THE A NEW VALUE
editor = sharedPrefs.edit();
editor.putString("value", "miles");
// DONT SKIP THIS STEP
editor.commit();
You can read more about SharedPreferences here

Declare a static String in your MainActivity (or elsewhere).
class MainActivity {
public static String distance = "kilometer";
}
You can change the String from anywhere with
MainActivity.distance = "miles";
Then you can use the distance String allover your app.

Related

Can't access sharedpreferences from other activity?

I have a fragment where I let set some SharedPreference values set.
In the fragment, everything works fine - I can get any value I want, saving, editing, deleting works fine.
Then I have an Activity, from where I want to get the value "savedValue1" - but it does not work
public static final String MyPref = "MyPreference";
static SharedPreferences sharedpreferences;
//onCreateView...
sharedpreferences = this.getActivity().getSharedPreferences(MyPref,
Context.MODE_PRIVATE);
editor.putString("savedValue1", someString);
editor.commit();
I tried it with in Fragment:
public static String getValue(){
return sharedpreferences.getString("savedValue1","");
}
in Activity:
String newValue = Fragment.getValue();
But that doesn't work - any hint?
You should not have a Fragment.getValue() method.
SharedPreferences are here to avoid that.
Use the same getSharedPreferences("whatever", Context.MODE_PRIVATE) code and you shall get/set the same values inside the same preferences.
That is how it is supposed to be used. From the official documentation:
For any particular set of preferences, there is a single instance of
this class that all clients share.
Use this code to save and retrieve values from SharedPreferences
//To save string
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putString("savedValue1", someString);
e.commit();
//Retrieve team score
String saved_value = settings.getString("savedValue1", "");

How do I set up a global variable to share among views in Android?

In one of my views the user makes a selection. I want to store that selection in a variable I can use across all views so it can be used for further database queries such as "bookId".
How can I make "bookId" a global variable that is set on one view and can be accessed across the other views when needed?
----- Edit: What I'm attempting to do based on comments and answers -----
On my main activity where the SharedPreference is stored I have this before the onCreate:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Integer bookId;
In my onCreate I've done this:
settings = getSharedPreferences(PREFS_NAME, 0);
bookId = settings.getInt("bookId", 0);
After the button press I'm storing a custom attribute and attempting to set bookId in the SharedPreference:
SharedPreferences.Editor editor = settings.edit();
editor.putInt("bookId",bookKey);
editor.commit();
In another view I'm attempting to get the bookId from the SharedPreference and, for testing purposes, I'm trying to set the stored value to a textView just to make sure it stored and carried over correctly.
Before the onCreate on the second view:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Inside the onCreate:
settings = getSharedPreferences(PREFS_NAME, 0);
Integer bookId = settings.getInt("bookId", (Integer) null);
tempBookTextView = (TextView) findViewById(R.id.tempBookTextView);
tempBookTextView.setText(bookId);
I have a two questions, how does this look so far? Any ideas why the app crashes when I use
Integer bookId = settings.getInt("bookId", (Integer) null);
Instead of using global variable to access variable value through out the app try using SharedPreferences.
sample activity:
public class Book extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
String mBookId = null;
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
mBookId = settings.getString("book_id", null);
// use book_id;
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("book_id", mBookId);
// Commit the edits!
editor.commit();
}
}
Preferences are typically created private and can be accessed via all over the application components. Sharing data with other application with world readable or writable preference file is rarely used, as the external component would need to know the exact filename and location of the file.
To kill the spirit of encapsulation,
public class Globals {
public static int x;
public static int y;
}
and later
if (Globals.x == 0) { ... }
But please don't do exactly that, any class can contain static variables, find a class responsible for the value you want to store.
OTOH, android processes may be restarted when you don't expect it, in which case all the variables will be reset. So it's better to use shared preferences and if they don't work as expected (which I have seen in at least one release of Android), store the instance of shared preferences in a static variable.
You can use Shared Preferences
Saved at once !
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ProjectAct.this).edit();
editor.putInteger(StaticVariable.BOOKID, "1");
p.get("contract_no"));
editor.commit();
Then call from anywhere like that
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int book_id = prefs.getInteger(StaticVariable.BOOKID,null);
See more at How to use SharedPreferences in Android to store, fetch and edit values

How to save app settings?

How can I save the the settings of my app? Right now, for example, I have a togglebutton to turn on/off. But if I restart my phone, the toggle button is turned back on. Its not saving the settings if I completely close the app. Can I like the save the settings to the phone as cookies?
Use Shared Preferences. Like so:
Put this at the top of your class: public static final String myPref = "preferenceName";
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPreferenceValue()
{
SharedPreferences sp = getSharedPreferences(myPref,0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPreference(String thePreference)
{
SharedPreferences.Editor editor = getSharedPreferences(myPref,0).edit();
editor.putString("myStore", thePreference);
editor.commit();
}
You could call them like this:
writeToPreference("on"); // stores that the preference is "on"
writeToPreference("off"); // stores that the preference is "off"
if (getPreferenceValue().equals("on"))
{
// turn the toggle button on
}
else if (getPreferenceValue().equals("off"))
{
// turn the toggle button off
}
else if (getPreferenceValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// a preference has not been created
}
Note: you can do this with boolean, integer, etc.
All you have to do is change the String storing and reading to boolean, or whatever type you want.
Here is a link to a pastie with the code above modified to store a boolean instead: http://pastie.org/8400737
You need to use SharedPreferences to save the settings of your app locally. Refer this link for more details : http://developer.android.com/reference/android/content/SharedPreferences.html
Use SharedPreferences as,
To Save:
SharedPreferences settings;
SharedPreferences.Editor editor;
public static final String PREFS_NAME = "app_pref";
public static final String KEY_p_id = "KEY_test";
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
editor.putString(Login_screen.KEY_test, values.get(0));
editor.commit();
To Remove:
editor.remove("KEY_test").commit();
You should check out SharedPreferences. It's Android's way of persisting simple values. Or you could create a full database.
Use SharedPreferences to save small chunk of app data.
Check the developer's website for this.
Also check out this Tutorial for step by step guide.
You can use local DB like SQlite for for your app.

I cannot get Mono for Android activity preference to work

In my mono for android app I want to save a user setting for an activity into the activities preference. I do this whenever the user changes this value:
ISharedPreferences prefs = GetPreferences(FileCreationMode.Append);
ISharedPreferencesEditor editor = prefs.Edit();
editor.PutInt(NO_PIXELS_PER_HOUR_KEY, m_noPixelsPerHour);
editor.Commit();
where NO_PIXELS_PER_HOUR_KEY is:
private const string NO_PIXELS_PER_HOUR_KEY = "PIXELS_PER_HOUR";
This value should then be loaded again in the actvity's OnCreate method:
ISharedPreferences preferences = GetPreferences(FileCreationMode.Append);
int tempNoPixelsPerHour = preferences.GetInt(NO_PIXELS_PER_HOUR_KEY, -1);
if (tempNoPixelsPerHour == -1)
m_noPixelsPerHour = (int)(m_deviceHeight * 0.25);
else
m_noPixelsPerHour = tempNoPixelsPerHour;
The problem is that the value does not seem to be persisting! Whenever I go out of the activity and back into it the default value of -1 is returned. I don't know whether it is not saving properly or not loading properly. Any help would be appreciated!
Thanks,
Dave
I dont know about mono for android but in android we call getsharedpreferences() in java. Here you're calling only the preferences which can be any preference but the settings preference. You can try something like getdefaultsharedpreference or something like that.
EDIT : I'm not sure but you can try this..
ISharedPreferences _preferences = PreferenceManager.GetDefaultSharedPreferences(your_context)

Can i use a button to save data in sharedPreferences and another to retrieve it?

Lets say i have an TextView that i want the user to view and then hit a save button. Then Hit display button and input the text into an editText field.
Here's what Im trying but its not working
To Save info from a TextView...
case R.id.save:
SharedPreferences firsttunesettings = getSharedPreferences("tune1", 0);
SharedPreferences.Editor editor = firsttunesettings.edit();
editor.putString("rh1", rh1.getText().toString());
editor.commit();
then to show the data in an EditText....
case R.id.display:
SharedPreferences firsttunesettings = getSharedPreferences("tune1", 0);
rh1.setText(firsttunesettings.getString("rh1", ""));
The code doesnt throw any errors, it just doesnt seem to do anything. Any help is appreciated. Thanks.
you need this:
SharedPreferences firsttunesettings = getApplicationContext().getSharedPreferences("tune1", 0);
and
SharedPreferences firsttunesettings = getApplicationContext().getSharedPreferences("tune1", 0);
rh1.setText(firsttunesettings.getString("rh1", ""));
the SharedPreferences needs the context of the aplication.
the rest of the code looks good to me.
edit:
try placing your values to save first on temporary variables like this:
String temp = firsttunesettings.getString("rh1", ""); and then:
rh1.setText(temp);
im running out off ideas since the code you posted should work fine.
edit#2:
also I declare the variables i use on shared preferences like this:
private static final String RH1 = "RH1";
and use it like this:
editor.putString(RH1, rh1.getText().toString());
and
String temp = firsttunesettings.getString(RH1, "");
this should do the trick.

Categories

Resources