SharedPreference not working- can't see why - android

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"
);

Related

Hide activity on button click with shared preferences, android studio

How can I use shared preference in android studio to achieve this?
On my app, Splash Screen redirects to Activity A.
There is a button on Activity A, When this button on Activity A is clicked, next time when user opens app, Activity A will not show again, Activity B must open next.
The logic here is, Activity A is my welcome screen, after user clicks get started on this activity, I don't want this Activity to open again. Activity B is my Main Activity
NB: I have checked all questions and answers on stackoverflow, they did not help, the ones available where showing activity only on first run and this not a duplicate question, any help provided is appreciated.
You can store boolean by shared preference to do that. Here your AcitivityA class.
public class ActivityA extends AppCompatActivity {
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
try {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean firsttimeLoad = prefs.getBoolean("first_time_load", true);
if (!firsttimeLoad) {
sendToB();
}
} catch (Exception e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time_load", false);
editor.commit();
sendToB();
}
});
}
private void sendToB() {
Intent mainIntent = new Intent(ActivityA.this, ActivityB.class);
startActivity(mainIntent);
finish();
}}
This is the code im using for save the sigin details from firebase you can check this out and try this
private fun handleSignInResult(task: Task<GoogleSignInAccount>?) {
try {
if (task!!.isSuccessful) {
val account = task.getResult(ApiException::class.java)
PreferenceHelper.writeBooleanToPreference(KEY_LOGIN_WITH_OAUTH, true)
updatePreference(account!!)
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("UserName", account.displayName)
intent.putExtra("UserEmail", account.email)
intent.putExtra("UserPhoto", account.photoUrl?.toString())
intent.putExtra("uid", account.id)
saveUser(account)
startActivity(intent)
finish()
} else {
Toast.makeText(
this,
"Login Error " + task.exception?.message,
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
}
}
private fun updatePreference(account: GoogleSignInAccount) {
PreferenceHelper.writeBooleanToPreference(KEY_USER_LOGGED_IN, true)
PreferenceHelper.writeStringToPreference(KEY_USER_GOOGLE_ID, account.id)
PreferenceHelper.writeStringToPreference(
KEY_DISPLAY_NAME,
account.displayName
)
PreferenceHelper.writeStringToPreference(
KEY_USER_GOOGLE_GMAIL,
account.email
)
}
When the user selects the button on Activity A, add a value to the shared preferences. What the value is does not really matter. Every time your app is launched, check if this value exists in the shared preferences, if it does launch Activity B, if it doesn't, launch Activiy A.
In onCreate of Activity A
SharedPreferences sharedPref = MainActivity.this.getPreferences(Context.MODE_PRIVATE);
if (sharedPref.contains("notFirstLaunch")) {
// Launch Activity B
}
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("notFirstLaunch", true);
editor.apply();
}
});

How to know the last button clicked in android using sharedpreference?

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
}

Shared Preferences and android toggle button won't work as expected

I would like to set up a toggle button for my android app, but I have to keep the button state for later use. I was trying to do it using sharedPreferences, my values return fine form the pref file, but the text of my button is the same, it wont change.
I have tested by putting the: tb.setChecked(false); on the end of my on create which changes the text from "on" to "off". But I can't get the same effect via my code.
What could be wrong?
Thanks!
main code:
public SharedPreferences spref;
final String PREF_NAME = "prefrences";
public String STATE = "state_value";
ToggleButton tb;
boolean on;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tour_detail);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
Bundle b = getIntent().getExtras();
tour = b.getParcelable(".Tour");
isMyTours = b.getBoolean("isMyTours");
isFollowed = b.getBoolean("isFollowed");
Log.i(LOGTAG, "Extra passed by notif is: " + tour);
refreshDisplay();
datasource = new ToursDataSource(this);
spref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.buttonFollow);
on = spref.getBoolean("On", true); //default is true
Log.i(LOGTAG, "VALUE for On is: " + on);
if (on = true) {
tb.setChecked(true);
} else {
tb.setChecked(false);
}
}
public void onToggleClicked(View view) {
on = ((ToggleButton) view).isChecked();
if (on) {
Toast.makeText(this, "On : Notification will be Enabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
boolean test_on = spref.getBoolean("On", true);
Log.i(LOGTAG, "VALUE for On is: " + test_on);
} else {
Toast.makeText(this, "Off : Notification will be Disabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
boolean test_on = spref.getBoolean("On", true);
Log.i(LOGTAG, "VALUE for On is: " + test_on);
}
}
and button inside XML:
<ToggleButton
android:id="#+id/buttonFollow"
style="?android:attr/buttonStyleSmall"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#dedede"
android:textSize="12sp"
android:paddingTop="7dp"
android:paddingBottom="5dp"
android:drawableTop="#drawable/urmarire_detail_ico"
android:drawablePadding="-1sp"
android:textOn="Vibrate on"
android:textOff="Vibrate off"
android:onClick="onToggleClicked"/>
You have a bug in the condition check:
if (on = true) {
tb.setChecked(true);
} else {
tb.setChecked(false);
}
In Java, the comparison is done with == - in your code, value of on is set to true in the condition part of the if, so onCreate always sets the ToggleButton checked.
As a side note, it is a bad habit to compare a boolean to true - it is generally more readable code if you simply test if (on). However in your case this test is not even needed - you can simply replace the block with tb.setChecked(on)

comparing two strings in Android ( if-else statemente)

I am working on a login page in an Android App.
As you know, the app must check if the username and password are valid, and then grant the user access to the application.
I have used the following code:
...
EditText un = (EditText) findViewById(R.id.username1);
EditText pw = (EditText) findViewById(R.id.password1);
String u = un.getText().toString();
String p = pw.getText().toString();
//////// Now on the click of the Login Button:
public void onClickL (View view){
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
else ///////Display a warning message: Try again
}
when I run this code this only executes the else part. why its not executing the if part? what should I do ?
The reason is that you are fetching the EditText's value while declaring the EditText. Actually you nee to fetch the Text from EditText while clicking on the button, hence you need to move you code to onClick() method like below,
#Override
public void onClick (View view)
{
String u = un.getText().toString();
String p = pw.getText().toString();
if ( (u.equals("Android")) && (p.equals("1234"))) /////// move to a new activity
{
....
}
else ///////Display a warning message: Try again
{
....
}
}
please try this:
public void onClickL (View view){
u = un.getText().toString();
p = pw.getText().toString();
if ( u.equals("Android") && p.equals("1234") ) /////// move to a new activity
{
}
else ///////Display a warning message: Try again
{
}
}
try Following code
need to clear space in username if it is available.
public void onClick (View view){
String username = un.getText().toString().trim();
String password = pw.getText().toString();
if ((username.equals("Android")) && (password.equals("1234"))) {
//do something
} else{
//do something
}
}
Try this..
get the text inside Click function like below
public void onClick (View view){
String u = un.getText().toString().trim();
String p = pw.getText().toString().trim();
if ((u.equals("Android")) && (p.equals("1234"))) {
//do something
}
else{
//do something
}
}

SharedPreferences lost on force quit?

I've added the SharedPreferences functionality to my App to launch a specific activity once the App starts after it has been quited.
I use the following code to save the string:
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("Stringval", "view1");
editor.commit();
Then the following to load the last used activity, this code is below OnCreate
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences pref1 = getSharedPreferences("myapp", MODE_PRIVATE);
String str1= pref1.getString("Stringval", null);
if(str1 == "view0")
{
setContentView(R.layout.activity_view0);
}
else if(str1 == "view1")
{
setContentView(R.layout.activity_view1);
}
else
{
setContentView(R.layout.activity_no_setup);
}
}
The code works if the user just quits the App, then relaunches it (Only tested it in the Simulator so far) but whenever I use the task manager to force quit the app like this:
The App just relaunches without using the SharedPreferences.
What's the reason for the App to not load the SharedPreferences or is this just a simulator bug?
You can write
if(str1 != null && str1.equals("view0"))
{
setContentView(R.layout.activity_view0);
}
else if(str1 != null && str1.equals("view1"))
{
setContentView(R.layout.activity_view1);
}
else
{
setContentView(R.layout.activity_no_setup);
}
try this, May be helpful for you......

Categories

Resources