I have set the Preferences in xml and I have the folowing Activity:
public class Preferencias extends PreferenceActivity {
//SharedPreferences prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
setContentView(R.layout.preferences);
Button bt=(Button)findViewById(R.id.selectPic);
TextView tv=(TextView) findViewById(R.id.textView1);
String def=getResources().getString(R.string.noDefinido);
tv.setText(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getString("logo", def));
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName(getApplicationContext(),
SDCardImagesActivity.class.getName());
startActivity(intent);
}
});
//habra que sacarlo de la red
String [] ofis ={"Venus", "Europa"};
ListPreference lp=new ListPreference(this);
lp.setValue("oficina");
lp.setEntries(ofis);
lp.setEntryValues(ofis);
lp.setTitle(R.string.oficina);
lp.setDefaultValue(ofis[1]);
getPreferenceScreen().addPreference(lp);
}
}
It works fine with the xml preferences but I also need to add a preference in code the reason of it is that the options of this ListPreference will come from the database (here I have the String array for now). The problem is the data changed for this preference is not persisted. When I make the changes I press back button I come back the value goes back to default value. How could I make sure this preference is saved too?
Thanks a lot
solved I included the preference without setting up its data then in code:
String [] ofis ={"Venus", "Europa"};
ListPreference lp=(ListPreference) getPreferenceManager().findPreference("oficina");
lp.setEntries(ofis);
lp.setEntryValues(ofis);
lp.setDefaultValue(ofis[1]);
works fine now
Related
I have a page in my application where the user can enter a product name and it's calorie count, which it then removes from a daily calorie count which comes from another class. This works perfectly I wanted to make it so that it doesn't reset to the original value each time the page is opened (unless its a fresh install / manual reset via a button).
I came across SharedPreferences and tried to implement this, but it always comes up with the default value in my onResume method and I am not too sure why and need some assistance to figure out what I am doing wrong and how to fix it, as I will need to use this in several other classes also.
My Class:
public class CalorieTracker extends AppCompatActivity {
protected String age, calorieCount;
protected EditText itemName, kCal;
protected TextView remainingCalories;
protected Button submitBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_tracker);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
calorieCount = extras.getString("calories");
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentCount = Integer.parseInt(remainingCalories.getText().toString());
int enteredAmount = Integer.parseInt(kCal.getText().toString());
calorieCount = String.valueOf(currentCount - enteredAmount);
remainingCalories.setText(calorieCount);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("sessionCalories",remainingCalories.getText().toString());
editor.commit();
}
});
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
}
http://prntscr.com/me99dp
Image of what it looks like when I boot the application, even though the initial calorieCount value should be 2100 which I get from the previous page using the Bundle extras.
If I change the
line remainingCalories.setText(mPrefs.getString("sessionCalories","")); in my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3")); then it shows 3 initially.
Make sure that your data is updated in shared preference correctly. In Activity life cycle after onviewCreated only onResume called .
so if your current activity will go to foreground or rotate then only onResume will call again.
so solution ,in button click after set the value and get value from sharedpreference and display like this
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// first time save data
setvalueFromSharedpreference()
}
});
public setvalueFromSharedpreference()
{
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
remainingCalories.setText(mPrefs.getString("sessionCalories",""));
}
when I boot the application, even though the initial calorieCount
value should be 2100 which I get from the previous page using the
Bundle extras.
If I change the line
remainingCalories.setText(mPrefs.getString("sessionCalories","")); in
my onResume method, to :
remainingCalories.setText(mPrefs.getString("sessionCalories","3"));
then it shows 3 initially.
Reason editText remainingCalories always have default (sharedpreference value) is because onResume method is called after onCreate in activity's lifecycle. Thats why, Bundle extras value is being overwritten by sharedpreference value.
You can achieve this in onCreate method by checking if Intent extras has value. If yes, then set that value otherwise set the sharedPrefrence's value as follows
#Override
protected void onCreate(Bundle savedInstanceState) {
...
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
calorieCount = mPrefs.getString("sessionCalories","");
Bundle extras = getIntent().getExtras();
age = extras.getString("age");
if(!calorieCount.isEmpty)
remainingCalories.setText(calorieCount);
else
{
calorieCount = extras.getString("calories");
}
System.out.println(age + ":" + calorieCount);
itemName = findViewById(R.id.productNameCalorieTracker);
kCal = findViewById(R.id.calorie_kcal);
submitBtn = findViewById(R.id.submit_calorie);
remainingCalories = findViewById(R.id.remainingCalorieCount);
remainingCalories.setText(calorieCount);
}
And remove the sharedPreference setting from onResume.
Hope it helps cheers:)
I am using Shared Preferences to store data which is came from EditText and set preferences data back to TextView but when i reopen my application textview shows default value. How can set changed data to the TextView and data should not be lost after reopening application. I tried onSaveInstanceState() and onSaveInstanceState() but this works when orientation change of application.
Here in my code i store data into shared Preferences and getting that data back to the TextView PRESET_MESSAGE_ONE i am storing value of EditText.
public void customDialogOne() {
mDialog = new Dialog(_con);
mDialog.setContentView(R.layout.custom_dialog_message);
mDialog.getWindow().setBackgroundDrawableResource(R.color.black);
mDialog.setTitle("Edit Preset Message");
btnPresetDialogCancel = (Button) mDialog
.findViewById(R.id.btnPrDialogCancel);
edtPresetDialogMessage = (EditText) mDialog
.findViewById(R.id.edtPrDialogMessage);
btnPresetDialogSave = (Button) mDialog
.findViewById(R.id.btnPrDialogSave);
btnPresetDialogSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPref.writeString(SharedPref.PRESET_MESSGE_ONE,
edtPresetDialogMessage.getText().toString());
msgOne = SharedPref.readString(SharedPref.PRESET_MESSGE_ONE);
tm.showToast(msgOne);
tvFrPresetMsgOne.setText(msgOne);
mDialog.dismiss();
}
});
btnPresetDialogCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
mDialog.show();
}
Have you commit your changes in the SharedPreference using SharedPref.commit(); ? Please check that one.
My issue has resolved my sequence was wrong to store value in shared Preferences, I used following code:
btnPresetDialogSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvFrPresetMsgOne.setText(edtPresetDialogMessage.getText()
.toString());
SharedPref.writeString(SharedPref.PRESET_MESSGE_ONE,
edtPresetDialogMessage.getText().toString());
msgOne = SharedPref.readString(SharedPref.PRESET_MESSGE_ONE);
tvFrPresetMsgOne.setText(msgOne);
mDialog.dismiss();
}
});
and read SharePreferences string in onResume method()
i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?
Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.
You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();
I'm struggling with using PreferenceFragments, can't seem to get it to work.
I have one preferences file, named at.package.preferences (without GUI) to save internal values - this works.
Now I wan't to create a preference screen for other (public) settings for the user, but here's where I fail.
My code:
public class ChartPreferences extends Activity {
private SharedPreferences prefs;
private Button btn;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chart_preferences);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
btn = (Button) findViewById(R.id.button1);
getFragmentManager().beginTransaction().replace(R.id.prefs_chart_content,
new ChartPrefsFragment()).commit();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(ChartPreferences.this, getLineSize(), Toast.LENGTH_SHORT).show();
}
});
}
public int getLineSize()
{
return Integer.valueOf(prefs.getString(getString(R.string.line_size_key), Helper.PREF_DEFAULT_LINE_SIZE));
}
public static class ChartPrefsFragment extends PreferenceFragment
{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.chart_prefs);
}
}
}
So the preference screen shows and when I select a value, let's say 5, from the preference list, it's also ok. When I open the preferences list again, the 5 is still selected (so the preferences get saved - somewhere...)
Now the problem occurs in the getLineSize() function, when I try to access the saved value. It gives me a android.content.res.Resources$NotFoundException.
I don't know where the values of the PreferenceScreen get saved, but it seems like it is not in the defaultSharedPreferences (?)
Here's my chart_prefs.xml, just in case:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="#string/chart" android:summary="#string/chart">
<ListPreference android:entries="#array/prefs_line_size" android:title="#string/line_size" android:summary="#string/line_size" android:key="#string/line_size_key" android:entryValues="#array/prefs_line_size"/>
</PreferenceCategory>
</PreferenceScreen>
It seems pretty weird to be using android:key="#string/line_size_key", ie the name of your preference is a resource lookup. I haven't looked at the code for Preference but perhaps it doesn't resolve the string but just uses '#string/line_size_key' as the token under which the preference is saved.
You don't really want the name of your preference to be a resource lookup do you? It means the preference would disappear as the user changed languages on their device.
i am new developer in android applications.i would like to save the data using shared preference concept.i am saving the data in one activity and get the same data in another activity.here i would like to send the String a[]={"one","two","three"} one activity to another activity.i have written code as follows
Main1.java
public class Main1 extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences shp=getSharedPreferences("TEXT", 0);
final Editor et=shp.edit();
((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String s1=((EditText)findViewById(R.id.editText1)).getText().toString();
et.putString("DATA", s1);
String s2[]={"one","two","three"};
//here i would like to save the string array
et.commit();
Intent it=new Intent(Main1.this,Main2.class);
startActivity(it);
}
});
}
Main2.java
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
String kk=getSharedPreferences("TEXT", 0).getString("DATA", null);
//here i would like to get the string array of Main1.java
((EditText)findViewById(R.id.editText1)).setText(kk);
}
can we get the string array values from Main1.java to Main2.java?
Put it into the starting intent:
Intent it = new Intent(Main1.this,Main2.class);
it.putExtra("MY_STRING_ARRAY", s2);
Get it back in the second activity:
String[] myStringArray = getIntent().getStringArrayExtra("MY_STRING_ARRAY");
If you want to send data from one activity to another then the best way would be send data using Intent object's putExtra method
Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtra("data1", "some data");
i.putExtra("data2", "another data");
i.putExtra("data3", "more data");
startActivity(i);
and you can get the data from receiving activity Activity2 like this
Object data1 = getIntent().getExtras().get("data1");
Hope that helps
If you want to save your information via SharedPreference not just pass it along activities, use some code like this:
SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString("string_preference", "some_string");
prefEditor.putInt("int_preference", 18);
prefEditor.commit();
The commit command is the responsable of actually saving data to SharedPreferences.