I make a setup class with shared preferences and in the first open apk the user use the default value and after edit if he want it with update value. My problem is when re open the apk and no create preference apk display default value else if there is old preference display this. I want update preferences onCreate with old save preferences if preferences exist(no with default value). How I create this? I want something if pref exist go to share preference...and read value...else use the default
String strValue ="http://www.power7.net/LEDstate.txt";//default value
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
/* SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
String strValue = preferences.getString("Url","");
text = (TextView) findViewById(R.id.textUrl);
text.setText(strValue);
*/
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
}
public void Save(View view) {
SharedPreferences preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit(); // Put the values from the UI
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
editor.putString("Url", strUrl); // value to store
// Commit to storage
editor.commit();
Change your code as for setting default value in TextView when user start your Application or any value not exist in SharedPreferences
SharedPreferences preferences;
String strValue="";
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ioweb_bt);
text = (TextView) findViewById(R.id.textUrl);
preferences = getSharedPreferences("dataioweb" , MODE_PRIVATE);
strValue = preferences.getString("Url","");
if(!strValue.equals("")){
text.setText(strValue);
}
else{
text.setText("Set Default value here");
}
// your code here
In this way, you can get default value from preference if no value is their corresponding to your preference key
SharedPreferences preferences=getSharedPreferences(preferencename, MODE_PRIVATE);
String str=preferences.getString(key, defaultValue);
Related
I'm trying to get integer Value from Second activity and save in the main activity
and its succeed
i tried to save that value in SharedPreferences
the problem every time im re-open the app
and check saved date in SharedPreferences I found the default value ( in this case LanguageSelected,1 )
What is the problem?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
languageCheck = intent.getIntExtra(Language.LanguageSelected,1);
// saving data
SharedPreferences sharedPreferences = getSharedPreferences("whatsappfastmessage",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("languageValue", languageCheck);
editor.commit();
sharedPreferences = getSharedPreferences("whatsappfastmessage",MODE_PRIVATE);
savedValue = sharedPreferences.getInt("languageValue", languageCheck);
i Solved the issue ,
i didn't know that SharedPreferences file can be access from any activities
just write the code of retrieve
best regards
I'm learning android and for this project I need to save user's data - color change of buttons, in this case -. During the program the change occurs (onClick), but when I restart the app, nothing happens - the change has not been saved (or read...) Can someone help me? Code:
final String paintKey = "paint";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCreate();
preferences();
togglePlay();
}
public void preferences(){ //the issue in this method?
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
settings.getBoolean(paintKey,false);
String backGround = settings.getString("stage", "Indoors");
if (backGround.equals("Indoors")) {
Picasso.with(this).load(R.drawable.shocked_crowd).fit().centerCrop().into(stage);
}
if (backGround.equals("Street")) {
Picasso.with(this).load(R.drawable.coins).fit().centerCrop().into(stage);
}
}
public void changeColor(){
if(!paint) { //paint variable has global scope and it is set to false
c1.setBackgroundColor(Color.YELLOW);
paint = true;
}else{
c1.setBackgroundColor(Color.BLUE);
paint = false;
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("paint", paint);
editor.commit();
}
EDIT: the onClick method:
public void onClick(View v) {
if(v==color){
changeColor();
}
EDIT: this is how I have it now:
public void preferences(){
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
data = settings.getString("stage", "Indoors");
final String paintKey = "paint";
settings.getBoolean(paintKey,false);
Wrong? if I put editor instead of settings i get red underlined
In order to work with SharedPreferences you need a global key
final String paintKey = "paint"
To write boolean value info SharedPreferences use
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(paintKey, paint).commit();
To read that data later
paint = settings.getBoolean(paintKey, false);
settings.getBoolean(paintKey,false);
This line gets a value from the SharedPreferences and promptly ignores it. You must save the return value in a variable in order to use it later:
boolean paint = settings.getBoolean(paintKey,false);
This will create a local variable that can only be used in the same method. If you need to use the value in other methods, create a field instead.
This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 8 years ago.
I shared the preference value A after I run a calculation with B you can write directly the result of AB in the shared preference by replacing A with the new value
public class Stats extends Activity {
private final static String MY_PREFERENCES = "MyPref";
private final static String GIORNISPETT = "giornispett";
public void indietro (View view){
}
#Override
public void onCreate(Bundle savedInstanceState) {
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
int giornispett = Integer.parseInt(prefs.getString(GIORNISPETT, "24"));
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
Intent intent=getIntent();
String trn=getPackageName();
int Giorni=intent.getIntExtra(trn+".Intgiorni", 0);
int Giorniresidui=giornispett-Giorni;
TextView tvgiorni=(TextView)findViewById(R.id.txtgiorni);
tvgiorni.append(+Giorni+"");
TextView tvGiorni_rest=(TextView)findViewById(R.id.txtGiorni_rest);
tvGiorni_rest.setText(""+Giorniresidue);
}
}
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = prefs.edit();
editor.put("key", value);
editor.commit();
The most easiest way it is to use SharedPreferences.Editor API with set of put API:
//update application settings based on check box state
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(activityContext);
Editor editor = sharedPrefs.edit();
editor.putBoolean("optionName", !checkBox.isChecked());
editor.commit();
Adding values to shared preferences works in key - value mode. If you use the same key twice the first value will be overwritten.
I am trying to save a date in one activity and then have that date put in a textView in another activity. I am not sure about how to get the two activities to communicate with each other.
In file called report.java I have this method that gets the date and save it in sharedPrefernces.
private void updateLabel() {
date.setText(fmtDate.format(dateAndTime.getTime()));
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("date", date.getText().toString()); // value to store
editor.commit();
}
I am trying to figure out how to get my file called inspection use this to populate a textView
The problem I think I am having is with getting the correct name for the report file.
public static final String PREF_FILE_NAME = "report";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
then I have this code on a method called onResume()
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String strDate=preferences.getString("date", date.getText().toString());
date.setText(strDate);
}
You are saving the value to two seperate preference files.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
Use only one.
Why not use the default preference file that is accessible by all classes/activities of your app?
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(yourContext);
preferences.edit().putString(YOURKEY, yourStrValue);
This way you are not creating extra preference files in your app that you have to remember which values are stored in which files. Definately makes life easier.
my app crashes with a null pointer exception on the code below.
i have an xml preference file under res/xml/defaults.xml
Any idea why it's crashing?
public class Preference extends Activity {
public Preference()
{
}
public String getPreference(String key)
{
//it still crashes here
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
String result = settings.getString(key, null);
return result;
}
}
Preference files are not storead in project's /res/xml/defaults.xml
They are stored on the device in your application folder something like
/data/data/com.your.pkg/default.prefs
Try do not specify the file name, as you will have some problems with the preference files, like this OP had here
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Then you will probably have to query
preferences.getString('weightPref', null);
Here's a sample code which shows how to save and retrieve Preferences. Here I am saving username and password in SharedPreferences.
SharedPreferences uPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor; = uPreferences.edit(); //Instantiating editor object
protected void storeSharedPrefs(String username, String password) {
/*
* Storing in Shared Preferences
*/
editor.putString("username", username);
editor.putString("password", password);
editor.commit(); //Commiting changes
}
Retrieving username and password in another activity from SharedPreferences.
private SharedPreferences mSP;
mSP = getSharedPreferences("CurrentUser", MODE_PRIVATE);
String username = mSP.getString("username", null);
String password = mSP.getString("password", null);
Hope it helps..
Setting a value in the shared preferences:
Editor prefs = getSharedPreferences("Application_name", MODE_PRIVATE).edit();
prefs.putString("key", accountKey);
prefs.commit();
Getting the value from another activity:
String accountKey =
this.getSharedPreferences("Application_name", MODE_PRIVATE).
getString("key", null);
It would be nice if you access the variable by using some predefined handler, such as getString(R.string._key), instead of the hardcoded string "key".
Your Preferences should extend PreferenceActivity. Then you need to create a resource xml file for preferences, and reference that in your PreferenceActivity like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
etc.
}
The preferences xml should have a PreferenceScreen as the top level element, and you can take advantage of all the different preference views Android makes available to you for setting preferences. This would be the most common, and elegant way to do it.