Excuse me because 3 of my simple question, but I need your help. I want to have a counter (with using shared preference) in my app like this:
At the first, there are 2 buttons, START and RESET. If RESET is
clicked, the counter starts from 0.
Also if START is clicked, the counter starts from shared preference data.
Start counting
At last time, I want to save counter in share preference. (but I don't know its better to save it in BACK btn or CLICK btn)
My problem is in share preference part. Please help me how can I do this? Thanks a lot!
Edit: this is my code
public class CountActivity extends Activity {
private Button click;
private int count,savedCount;
private String count_text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counting);
click= (Button) findViewById(R.id.vow_counting);
final Typeface typeface = Typeface.createFromAsset(getAssets(),"fonts/Far_Homa.ttf");
final SharedPreferences sharedPreferences=getSharedPreferences("counters", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor=sharedPreferences.edit();
AlertDialog.Builder fBuilder=new AlertDialog.Builder(VowCountActivity.this);
fBuilder.setMessage("please choose");
fBuilder.setCancelable(false);
fBuilder.setPositiveButton("start from beging", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
count = sharedPreferences.getInt("counter", 0);
click.setText("0");
click.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/Far_Homa.ttf"));
dialogInterface.cancel();
}
});
fBuilder.setNegativeButton("countinue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
count = sharedPreferences.getInt("counter",savedCount);
editor.putInt("counter",savedCount).commit();
dialogInterface.cancel();
}
});
fBuilder.show();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count++;
count_text=Integer.toString(count);
click.setText(count_text);
click.setTypeface(typeface);
savedCount = sharedPreferences.getInt("savedCounter", count);
vibrate(500);
}
});
}
// vibrate
public void vibrate(int duration) {
Vibrator vibs = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibs.vibrate(duration);
}
To get value on start button you can define this function and have value for shared preferences
public static int getIntPreferences(String key) {
SharedPreferences settings = context.getSharedPreferences(SP_FILE_NAME, 0);
return settings.getInt(key, 0);
}
Now to reset your shared preferences value you can use the following function
public static void updatePreferences(String key, int value) {
SharedPreferences settings = context.getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt(key, value);
editor.commit();
}
Use
SharedPreferences preferences = getSharedPreferences("PROFILE", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
edit.putString("yourPreferenceName", yourPreferenceObject);
edit.commit();
for saving preference
and
SharedPreferences preferences = this.getSharedPreferences("PROFILE", Context.MODE_PRIVATE);
String string = preferences.getString("yourPreferenceName", "defaultReturn");
for receiving your sharedPreferences
.get and .put with return type
Try this:
SharedPreferences preferences = getSharedPreferences("counterStat", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = preferences.edit();
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int counter = preferences.getInt("counter", 0);
// counter = counter + 1; start counting
edit.putInt("counter", counter).commit();
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putInt("counter", 0).commit();
}
});
Dialog back:
int counter = preferences.getInt("counter", 0);
edit.putInt("savedCounter", counter).commit();
Dialog cancel:
int counter = preferences.getInt("counter", 0);
edit.putInt("savedCounter", counter).commit();
edit.putInt("counter", 0).commit();
Then you can use: int savedCounter = preferences.getInt("savedCounter", 0); anywhere
Here is how to add an entry to SharedPrefs, and save to disk.
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", "Adam");
editor.commit();
Here is how to read a saved value from SharedPrefs.
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
String name = settings.getString("name", null);
Related
Iam not able to store values in shared prefernces.As soon as the activity is closed the no value remains saved. On starting the activity again the ids used to store and fetch data have null values.
Heres is my code.i am not attaching the layout as they will be of no significance.
As I am new to android.There might be some simple thing i a missing.Please help
public class enter_db extends AppCompatActivity
{
String field;
EditText usrtext,idtxt,bananatxt,coconuttxt,timbertxt,bambootxt,goldtxt,garage1txt,garage2txt,garage3txt,garage4txt,garage5txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_entry);
usrtext=(EditText)findViewById(R.id.username);
idtxt=(EditText)findViewById(R.id.UserID);
bananatxt=(EditText)findViewById(R.id.banana_count);
coconuttxt=(EditText)findViewById(R.id.coconut_count);
bambootxt=(EditText)findViewById(R.id.banana_count);
timbertxt=(EditText)findViewById(R.id.Timber_count);
goldtxt=(EditText)findViewById(R.id.gold_count);
garage1txt=(EditText)findViewById(R.id.garage_1);
garage2txt=(EditText)findViewById(R.id.garage_2);
garage3txt=(EditText)findViewById(R.id.garage_3);
garage4txt=(EditText)findViewById(R.id.garage_4);
garage5txt=(EditText)findViewById(R.id.garage_5);
SharedPreferences pref=getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final SharedPreferences.Editor editor = pref.edit();
if(pref.getString("Username",null)!="")
{
field=pref.getString("Username",null);
usrtext.setHint("Username"+field);
}
if(pref.getString("UserID",null)!=null)
{
field=pref.getString("UserID",null);
idtxt.setHint("UserID: "+field);
}
if(pref.getString("Banana",null)!=null)
{
field=pref.getString("Banana",null);
bananatxt.setHint("Banana: "+field);
}
if(pref.getString("Coconut",null)!=null)
{
field=pref.getString("Coconut",null);
coconuttxt.setHint("Cococnut: "+field);
}
if(pref.getString("Timber",null)!=null)
{
field=pref.getString("Timber",null);
timbertxt.setHint("Timber: "+field);
}
if(pref.getString("Bamboo",null)!=null)
{
field=pref.getString("Bamboo",null);
bambootxt.setHint("Bamboo"+field);
}
if(pref.getString("Gold",null)!=null)
{
field=pref.getString("Gold",null);
goldtxt.setHint("Gold: "+field);
}
if(pref.getString("Garage1",null)!=null)
{
field=pref.getString("Garage1",null);
garage1txt.setHint("Garage1 :"+field);
}
if(pref.getString("Garage2",null)!=null)
{
field=pref.getString("Garage2",null);
garage2txt.setHint("Garage2 :"+field);
}
if(pref.getString("Garage3",null)!=null)
{
field=pref.getString("Garage3",null);
garage3txt.setHint("Garage3 :"+field);
}
if(pref.getString("Garage4",null)!=null)
{
field=pref.getString("Garage4",null);
garage4txt.setHint("Garage4 :"+field);
}
if(pref.getString("Garage5",null)!=null)
{
field=pref.getString("Garage5",null);
garage5txt.setHint("Garage5 :"+field);
}
editor.putString("Username",usrtext.getText().toString());
editor.putString("UserID",idtxt.getText().toString());
editor.putString("Banana",bananatxt.getText().toString());
editor.putString("Coconut",coconuttxt.getText().toString());
editor.putString("Timber",timbertxt.getText().toString());
editor.putString("Bamboo",bambootxt.getText().toString());
editor.putString("Gold",goldtxt.getText().toString());
editor.putString("Garage1",garage1txt.getText().toString());
editor.putString("Garage2",garage2txt.getText().toString());
editor.putString("Garage3",garage3txt.getText().toString());
editor.putString("Garage4",garage4txt.getText().toString());
editor.putString("Garage5",garage5txt.getText().toString());
ImageButton ok=(ImageButton)findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
// Start new list activity
public void onClick(View v)
{
editor.apply();
Intent i=new Intent(getApplicationContext(),Garage.class);
startActivity(i);
}
});
}
}
U missed the apply() / commit() to save chanegs.
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply(); // editor.commit()
apply() is faster and async while commit() is synchronous.
Save value in shared preferences:
SharedPreferences settings =getSharedPreferences("AppName", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor. putBoolean(key, value);
editor.commit();
get value from shared preferences:
SharedPreferences settings = getSharedPreferences("AppName", 0);
String value=settings.getString(key, "");
boolean value=settings.getBoolean(key,false);
As in above code you are not saving value of edit text in shared preference on button click,try this way
ok.setOnClickListener(new View.OnClickListener() {
// Start new list activity
public void onClick(View v)
{
editor.putString("Username",usrtext.getText().toString());
editor.putString("UserID",idtxt.getText().toString());
editor.putString("Banana",bananatxt.getText().toString());
editor.putString("Coconut",coconuttxt.getText().toString());
editor.putString("Timber",timbertxt.getText().toString());
editor.putString("Bamboo",bambootxt.getText().toString());
editor.putString("Gold",goldtxt.getText().toString());
editor.putString("Garage1",garage1txt.getText().toString());
editor.putString("Garage2",garage2txt.getText().toString());
editor.putString("Garage3",garage3txt.getText().toString());
editor.putString("Garage4",garage4txt.getText().toString());
editor.putString("Garage5",garage5txt.getText().toString());
editor.apply();
Intent i=new Intent(getApplicationContext(),Garage.class);
startActivity(i);
}
});
editor.putString("Garage5",garage5txt.getText().toString());
editor.commit();
I am using SharedPreferences to keep the information about user's weight, which I need in my application. The problem is, how to set a default value (eg. 75 kg) automatically after installation? I know how to do it via .xml, but how to do this programmatically?
My code:
public class SettingsDialogFragment extends DialogFragment{
public static final String PREFS_NAME = "settings";
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Data.weight = weight;
SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_NAME, 0);
Editor editor = prefs.edit();
editor.putInt("key_weight", weight);
editor.commit();
Data.ifMale = ifMale;
checkedRadio = rg.getCheckedRadioButtonId();
System.out.println("numer radio" +checkedRadio);
}
});
return builder.create();
}
}
Try this way, please.
SharedPreferences prefs = getActivity().getSharedPreferences(
PREFS_NAME, 0);
if (prefs.getInt("key_weight", null) == null) {
Editor editor = prefs.edit();
editor.putInt("key_weight", 75);
editor.commit();
}
For first time use this, or else use your code only(means without if condition).
getInt takes a default value.
prefs.getInt("key_weight", 75)
Or in a more mainstream style....
public class AppPreferences {
private SharedPreferences mPreferences;
Public AppPreferences(SharedPreferences preferences)
{
this.mPreferences = preferences;
}
private static final String KEY_WEIGHT_KEY = "key_weight";
private static final int DEFAULT_KEY_WEIGHT = 75;
public static int getKeyWeight()
{
return mPreferences.getInt(KEY_WEIGHT_KEY,DEFAULT_KEY_WEIGHT);
}
}
I want to save boolean values and then compare them in an if-else block. but when run my application, nothing is displayed.
my Code is here:
prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = prefs.edit();
boolean init = false;
if (init) {
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor.putBoolean("init", true).commit();
}
});
} else {
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
So my question is why shared preferences is not working? please help me.
This is how you need to work with shared preferences.
The senerio I am about to show is to check if this particular activity is running for the first time or not.
Here is what you do in your on create method:
//SharePrefernces
SharedPreferences appIntro = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Check if the Application is Running for the First time
appIntro = getSharedPreferences("hasRunBefore_appIntro", 0); //load the preferences
Boolean hasRun = appIntro.getBoolean("hasRun_appIntro", false); //see if it's run before, default no
//If FirstTime
if (!hasRun) {
//code for if this is the first time the application is Running
//Display Activity
super.onCreate(savedInstanceState);
setContentView(R.layout.app_intro_activity);
//Button to send Confirmation back
Button btn_ok = (Button) findViewById(R.id.appintro_btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Save information that this application has run for the first time
SharedPreferences settings = getSharedPreferences("hasRunBefore_appIntro", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean("hasRun_appIntro", true);
edit.commit(); //apply
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
});
}//End of if(firstTime)
else {
//code if the Application has run before
super.onCreate(savedInstanceState);
//Navigate Directly to MainActivity
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
}//End of OnCreate()
you are checking always false value of init and it does not enter into your if statement,So prefs will not updated.instead do it as
boolean init = prefs.getBoolean("init",false);
and check it as
if(!init)
i.e. change
boolean init = false;
if (init) {
to
boolean init = prefs.getBoolean("init",false);
if(!init)
You are not using SharedPreferences values in above code . You might need to do like this :
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean prefValue = prefs.getBoolean("init", false);
if(!prefValue)
{
// add value in SharedPreferences
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor = prefs.edit();
editor.putBoolean("init", true).commit();
}
});
}
else{
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
The key is : You need to check the preference values first and accordingly code
You can also use SharedPreferences like this:
/* In your onCreate method */
SharedPreferences sp = getSharedPreferences(MyPrefs, Context.MODE_PRIVATE);
if (!sp.getBoolean("first", false)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("first", true);
editor.apply();
Intent intent = new Intent(this, IntroActivity.class); // Call the one tie launch java class
startActivity(intent);
}
I have created an activity that should be displayed only once. In this Activity, I added a button, and click its close and will not reopen anymore when the application is started again. I thought of using SharedPreferences, but I do not get the desired result.
I memorize a data in Shared:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString( "entrato", "entra" );
edit.commit();
this.finish();
break;
}
}
then, in OnCreate() of the previous activity call the Shared and if the data is present do not open the activity:
//remember click
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
String valore = userDetails.getString("entrato", "");
if (valore.equals("entra")){
return;
}else{
Intent intent = null;
intent = new Intent(this, Benvenuto.class);
startActivity(intent);
create share preference class like this:
public class MyPreference {
private static final String APP_SHARED_PREFS = "myPref";
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public MyPreference(Context context) {
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public boolean loadServices(String servicName) {
return appSharedPrefs.getBoolean(servicName, false);
}
public void saveServices(String servicName, boolean isActivated) {
prefsEditor.putBoolean(servicName, isActivated);
prefsEditor.commit();
}
}
then On Oncreate activity check if service exist so wont show and exit.
public static MyPreference myPref = new MyPreference(this);
if(myPref.loadService("this is not first time")){
thisActivity.finish();
}else {
// so it's first time and you can do what ever you want to do
}
and go on you click events and save service like this.
public static MyPreference myPref = new MyPreference(this);
myPref.saveService("this is not first time");
Try this code instead
// save string
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
// retrieve String
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
String value = settings.getString(key, "");
return value;
}
I have Four activities
Splash
Have 2 Buttons And 1 CheckBox ( Remember Me)
3 & 4. Another Activity
If I check the remember me option using checkbox, then I have to remember the button I have clicked and then start the 3rd or 4th activity directly whenever next start.
I'm creating a Quiz App, I ask some questions and give options in the form of radio buttons, now I want to store value of of answer (plus on right answer and minus on wrong one) in SharedPreferences and show that result in other activity. I have searched and found this answer here
I used that but still I'm unable to get my desired results
My code Looks Like :
Main Activity which saves some value in SharedPreferences:
public class MainActivity extends Activity {
private SharedPreferences saveScore;
private SharedPreferences.Editor editor;
RadioGroup group;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
radioButton = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
saveScore = getPreferences(MODE_PRIVATE);
}
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
editor = saveScore.edit();
editor.putInt("score", -1);
editor.commit();
}else{
editor = saveScore.edit();
editor.putInt("score", 1);
editor.commit();
}
Intent intent = new Intent (MainActivity.this, NextActivity.class);
startActivity(intent);
}}
this is the Next Activity which tries to get values from SharedPreferences:
public class NextActivity extends Activity{
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
preferences = this.getSharedPreferences("score", MODE_WORLD_WRITEABLE);
int value = preferences.getInt("score", 0);
String score = "Your Score is : " + value;
UIHelper.displayScore(this, R.id.tvScore, score );
}}
does any one know how to that?
You should change the line
saveScore = getPreferences(MODE_PRIVATE);
To
saveScore = getSharedPreferences("score",Context.MODE_PRIVATE);
Store the value when navigating to nextActivity during onPause() as below:
#Override
protected void onPause()
{
super.onPause();
// Store values between instances here
SharedPreferences preferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourStringKeyValue", "StringValue"); // value to store
// Commit to storage
editor.commit();
}
and get the data with that key in next Activity's onCreate as below:
SharedPreferences preferences = getSharedPreferences("sharedPrefs", 0);
String name= preferences.getString("YourStringKeyValue","");
try this,
public class DataStorage {
private static String KEY;
public static SharedPreferences savedSession;
public void saveID(Context context, String msessionid) {
// TODO Auto-generated method stub
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("SESSION_UID", msessionid);
editor.commit();
}
public String getID(Context context) {
savedSession = context.getSharedPreferences(KEY, Activity.MODE_PRIVATE);
return savedSession.getString("SESSION_UID", "");
}
}
Edit:
DataStorage mdata = new DataStorage();
public void gotoNextAndSaveScore(View view) {
if(group.getCheckedRadioButtonId() != R.id.radio3){
mdata.saveId(Mainactivity.this,1);
}else{
mdata.saveId(Mainactivity.this,-1);
}
And then get value from NextActivity.
DataStorage mdata = new DataStorage();
mdata.getId(NextActivity.this);
You're using the wrong preference file, the getPreference function on Activity returns a file private to that Activity. You need to use the named file version- getSharedPreferences(name, mode)