I have two buttons, Now how I can know the last button clicked using sharedpreference when start the activity again ?
the code:
private SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
init in onCreate:
sharedPreferences = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
I tried to do this but absolutely wrong way
if (sharedPreferences.getString("lamp", "on")) {
Toast.makeText(this, "onnnn", Toast.LENGTH_SHORT).show();
}
if (sharedPreferences.getString("lamp", "off")){
Toast.makeText(this, "offfff", Toast.LENGTH_SHORT).show();
}
first button
public void lampOff(View view) {
Log.d(tag, "lampOFF");
lamp_notConnected_Image.setVisibility(View.INVISIBLE);
lamp_Connected_Image.setVisibility(View.VISIBLE);
editor.putString("lamp", "off");
editor.commit();
}
seconde button:
public void lampOn(View view) {
Log.d(tag, "lampO");
lamp_notConnected_Image.setVisibility(View.VISIBLE);
lamp_Connected_Image.setVisibility(View.INVISIBLE);
editor.putString("lamp", "on");
editor.commit();
}
The problem lies in your condition if (sharedPreferences.getString("lamp", "on")), you aren't comparing this string to anything, either use
if (sharedPreferences.getString("lamp", "on").equals("on"))
or
save the value as boolean editor.putBoolean("lamp", true);, then you can compare the way you were doing: if (sharedPreferences.getString("lamp", true))
Note that here ("lamp", "on") the fist parameter is the identification, and the second is the default value, in case nothing is stored there yet.
See more in SharedPreferences
You need to check the shared preference value in onCreate method like:
if (sharedPreferences.getString("lamp", "off").equals("on")) { //assumed "off" as default
Toast.makeText(this, "onnnn", Toast.LENGTH_SHORT).show();
// on button is pressed last time
}
else{
Toast.makeText(this, "offfff", Toast.LENGTH_SHORT).show();
// off button is pressed last time or no button press so far
}
Related
I want when the user start the app for the first time, a dialog appears to tell the user that the application will collect some data about his/her usage, and if he/she press accept, the main activity starts, and never ask the user again.
let's break your problem to smaller ones. You will need to activities: MainActivity and PermissionsActivity (add a button with id 'yes' and a button with id 'no'.
A) Launch an activity just one time. We will do so using SharedPreferences and storing a boolean which, if true, means that the dialogue had been previously shown and, otherwise, that it has not been shown.
// In MainActivity.class
String MY_PREFS_NAME = "my_prefs"; // can be changed, but it must be done so everywhere
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Boolean bool = prefs.getBoolean("hasbeenshown", false);
if (!bool){
// Go to the request dialogue activity
Intent myIntent = new Intent(MainActivity.this, PermissionsActivity.class);
startActivity(myIntent);
}
// otherwise, if bool = true, activity has been shown and there is no need to redirect
B) If the user answers, redirect to MainActivity and store the answer.
// In PermissionsActivity.class
String MY_PREFS_NAME = "my_prefs"; // can be changed, but it must be done so everywhere
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
Button yes = (Button) findViewById(R.id.button1);
yes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Do stuff when they accept
// ...
// Store the answer
store(true); // true means that user said yes
}
});
Button no = (Button) findViewById(R.id.button1);
no.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Do stuff when they !accept
// ...
// Store the answer
store(false); // false means that user said no
}
});
void store(Boolean answer){
// Store the answer
editor.putBoolean("answer", answer);
// Don't show the message again
editor.putBoolean("hasbeenshown", true);
// Store the previous edits
editor.commit();
// Redirect to MainActivity
Intent myIntent = new Intent(PermissionsActivity.this, MainActivity.class);
startActivity(myIntent);
}
C) APPENDIX: You can always get what the user answered from any activity with the following code.
String MY_PREFS_NAME = "my_prefs"; // can be changed, but it must be done so everywhere
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Boolean yesorno = prefs.getBoolean("answer", false); // false will be returned if user didn't answer or answered no; true will be returned if user answered yes
I changed shared preferences value but it still returns old one. What am I missing?
This code executed when the user clicks on the item in RecyclerView. So on the first click, I get message " this true" as expected. But on second click I also get " this true", but expect "this false".
SharedPreferences prefs = context.getSharedPreferences(MY_PREF, Context.MODE_PRIVATE);
boolean value = prefs.getBoolean(KEY_PREF, true);
if (value) {
Log.v(LOG_TAG, "this true");
Log.v(LOG_TAG, "editing value..");
SharedPreferences.Editor prefs = context.getSharedPreferences(MY_PREF, MODE_PRIVATE).edit();
prefs.putBoolean(KEY_PREF, new_value);
prefs.apply();
} else {
Log.v(LOG_TAG, "this false");
}
All you store is true, always, so there's no way to show this false as it never gonna happen. In fact, your code will not compile as new_value is never declared not assigned.
PS: there's no sense to call getSharedPreferences() second time. You got it already in prefs prior entering your if() block.
The call prefs.apply is asynchronously. You may not see the immediate change. Instead you could use prefs.commit which is synchronously.
so I'm basically trying to set a BG image for activity2 with a button press in activity1.
I am using sharedpreference so the option will always stay.
The thing is, after the button press, I am saving a string to a SharedPreference:
public void onClick(View v) {
SharedPreferences.Editor background = getSharedPreferences("Background", MODE_PRIVATE).edit();
if(btn1 == v)
{
Toast.makeText(this, "btn1", Toast.LENGTH_SHORT).show();
background.putString("selectedBG", "White");
background.commit();
}
if(btn2 == v)
{
background.putString("selectedBG", "Black");
background.commit();
}
if(btn3 == v)
{
background.putString("selectedBG", "Blue");
background.commit();
}
if(btn4 == v)
{
background.putString("selectedBG", "Brown");
background.commit();
}
}
And then, in the onCreate of activity2:
SharedPreferences background = getSharedPreferences("Background", MODE_PRIVATE);
String chosenBackground = background.getString("SelectedBg", null);
Toast.makeText(this,"chosenBackground:" + chosenBackground, Toast.LENGTH_SHORT).show();
The last Toast, prints out chosenBackground:null, no matter what button I press.
What am I doing wrong?
Thank you.
SharedPreferences Ids are case sensitive
Change this:
String chosenBackground = background.getString("SelectedBg", null);
To this:
String chosenBackground = background.getString("selectedBG", null);
String chosenBackground = background.getString("selectedBG", null);
You can use defaultSharedPreferences for simply adding and changing data from any point of app:
Put any value example :
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(KEY, "value")
.apply();
Get value :
PreferenceManager.getDefaultSharedPreferences(context)
.getString(KEY, "Default value"
);
I'm developing a mobile app using ApacheCordova/Phonegap.
I need a function that sends a SMS to me once per install. If I put my function on "DeviceReady" it will be run each time the app opens.
Is there any solution for a function to be run when app is installed OR when it runs for first time?
Any suggestion would be appreciated.
Check if it is the first time with a method and then perform the action if that method determines that it is the first time.
Ex:
isFirstTime() Method
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
// Send the SMS
}
return ranBefore;
}
You may want to add it to your onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
topLevelLayout = findViewById(R.id.top_layout);
if (isFirstTime()) {
topLevelLayout.setVisibility(View.INVISIBLE);
}
I added a field to the localstorage and on startup just check if that field exists. So something like this:
if (window.localStorage.getItem("installed") == undefined) {
/* run function */
window.localStorage.setItem("installed", true);
}
Edit: The reason I prefer this over the other methods is that this works on iOS, WP, etc as well, and not only on android
This should be what u are searching for:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("firstTime", false))
{
// run your one time code
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Use some boolean value if its true don't call that function other wise call that function example is here
if(smssent!=true)
{
//call sms sending method
}
else
{
//just leave blank or else notify user using some toast message
}
Note:-the boolean value store in some database like sharedprefernce or sqllite, files....
Quite new to coding for android but this issue has me tearing my hair out because it seems to make no sense at all...
I have an activity with four form elements in the layout: a CheckBox, two EditTexts and a Button.
When the user presses the button, it saves the content of the EditTexts as two preference values.
When the user presses the checkbox, it does the following:
If the checkbox is checked, load the preferences and store them into two variables.
Check if either of those variables contain empty strings after trimming them.
If so, show an error message, otherwise show a success message.
Essentially, the two text fields are used to set a pair of preferences which must not be empty when the checkbox is clicked.
It seems to work fine if I click the checkbox before pressing the button - error message or success message shown as appropriate.
If I press the save button and then click the checkbox, it always shows the success message regardless of the preferences.
Code follows (trimmed from the program as a whole)...
layout.xml
<CheckBox android:id="#+id/cboxActive" android:text="Click me!" android:onClick="toggleActive" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<EditText android:id="#+id/editFrom" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone"><requestFocus /></EditText>
<EditText android:id="#+id/editTo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone"></EditText>
<Button android:id="#+id/btnSave" android:onClick="savePrefs" android:text="Save" android:layout_width="120dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" />
</LinearLayout>
main class:
public class AutoMessengerActivity extends Activity
{
SharedPreferences settings;
CheckBox cboxActive;
EditText editFrom, editTo;
boolean active;
String from, to;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editFrom = (EditText) findViewById(R.id.editFrom);
editTo = (EditText) findViewById(R.id.editTo);
showPrefsInUI();
}
private void loadPrefs()
{
//Load preferences
settings = getPreferences(MODE_PRIVATE);
from = settings.getString("from", "");
to = settings.getString("to", "");
}
private void showPrefsInUI()
{
loadPrefs();
//Set UI elements to preference values
editFrom.setText(from);
editTo.setText(to);
}
public void savePrefs(View view)
{
SharedPreferences.Editor editor = settings.edit();
editor.putString("from", editFrom.getText().toString());
editor.putString("to", editTo.getText().toString());
editor.commit();
Toast.makeText(this, "Prefs saved!", Toast.LENGTH_SHORT).show();
}
public void toggleActive(View view)
{
if (cboxActive.isChecked())
{
loadPrefs();
//This toast is for debugging
//It shows the correct data in all circumstances...
Toast.makeText(this, "F: " + from + " T: " + to, Toast.LENGTH_SHORT).show();
//This is the part that seems to fail if you save then click checkbox
if (from.trim() == "" || to.trim() == "")
{
Toast.makeText(this, "Error - Prefs not saved", Toast.LENGTH_LONG).show();
cboxActive.setChecked(false);
}
else
{
Toast.makeText(this, "Success!", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(this, "Unchecked!", Toast.LENGTH_SHORT).show();
}
}
}
Hopefully that code gives an idea of the problem and allows it to be replicated...
Oh god, how silly of me - Urban and jcxavier hit the nail on the head... I forgot about that damn annoying quirk of Java! Changed the line to
from.trim().equals("") || to.trim().equals("")
And it works fine!
For what it's worth, that HAD actually crossed my mind briefly, but it was 2am when I tried equals and I got confused about requiring an Object as the parameter and ended up specifying null rather than "" - which didn't work...