Shared Preference values - android

I want to use the value of shared preferences from one activity to another activity, like if my pin from pin_activity is set on, the pattern from another activity should be disabled, and show the Toast that "PinService is ON, You can't Make PatternService ON" and vice versa. i am not getting how to use shared preference values. Please help me out in doing this
here is my code for both activities.
pin_activity.java
s2 = (Switch) findViewById(R.id.switch2);
spref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
s2.setChecked(spref.getBoolean("SwitchButton", false));
s2.setOnClickListener(new ToggleButton.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("SwitchButton", s2.isChecked());
// editor.putString("switch_state", "value");
//switch_state=editor.putBoolean("SwitchButton", s2.isChecked());
editor.commit();
// Toast.makeText(getApplicationContext(), "Switch is ON", Toast.LENGTH_SHORT).show();
}
});
Pattern_activity.java
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
s1.setChecked(sharedPreferences.getBoolean("toggleButton", false));
switch1= sharedPreferences.getBoolean("editor",s1.isChecked() );
if (switch1== true)
{
s1.setEnabled(false);
Toast.makeText(getApplicationContext(), "PinService is ON, You can't Make PatternService ON", Toast.LENGTH_SHORT).show();
}
else
{
s1.setEnabled(true);
}
s1.setOnClickListener(new ToggleButton.OnClickListener() {
public void onClick(View v) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
//switch1= sharedPreferences.getString("switch_state", null);
editor.commit();
// Toast.makeText(getApplicationContext(), "Switch is ON", Toast.LENGTH_SHORT).show();
}
});

You need to use the same key for your setting.
In your example you use "SwitchButton" to read/write the state of the switch in pin_activity and "editor" to read (supposedly) that same value. Which cannot work.
So extract a key string to a constant like public static String PIN_STATE = "PIN_STATE";.
in pin_activity:
s2 = (Switch) findViewById(R.id.switch2);
spref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
s2.setChecked(spref.getBoolean(PIN_STATE, false));
s2.setOnClickListener(new ToggleButton.OnClickListener() {
public void onClick(View v) {
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean(PIN_STATE, s2.isChecked());
// editor.putString("switch_state", "value");
//switch_state=editor.putBoolean(PIN_STATE, s2.isChecked());
editor.commit();
// Toast.makeText(getApplicationContext(), "Switch is ON", Toast.LENGTH_SHORT).show();
}
});
in Pattern_activity:
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
s1.setChecked(sharedPreferences.getBoolean("toggleButton", false));
switch1= sharedPreferences.getBoolean(PIN_STATE, s1.isChecked() );
if (switch1== true)
{
s1.setEnabled(false);
Toast.makeText(getApplicationContext(), "PinService is ON, You can't Make PatternService ON", Toast.LENGTH_SHORT).show();
}
else
{
s1.setEnabled(true);
}
And from that on you probably need to do something similar for PATTERN_STATE and in general straighten out you button states, as they seem a bit jumbled.

Related

Android WebView Set Login Status to True after Successful Login

I’m using Shared Preferences to store user data and set Login Status in a web view app for eCommerce Website. The user can either login via Login URL or at the Checkout Page. The issue I’m facing I can’t set Login status to “True” after the user successfully logged in so I can retrieve the username it keeps showing as "False".
EDIT: After posting the question I was able to find part of the solution for the Login URL to set the status to true however the CARTURL isn't working. I defined isRedirected = true; and set the condition to get the right status.
I'm reposting the code after edit:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.e(TAG, "should override url loading" + url);
view.loadUrl(url);
isRedirected = true;
return true;
}
public void onPageFinished(WebView view, String url) {
//webView.setClickable(true);menuBtn.setClickable(true);cartImg.setClickable(true);logoImg.setClickable(true);
Log.e(TAG, "on page finished" + url);
Log.e(TAG, "is logged in==" + isLoggedin);
isRedirected = true;
String isLoggedin = "false";
if(url.equals(Constants.ACCOUNTURL) && isRedirected && isLoggedin.equals("false")) {
Log.e(TAG, "reload");
//webView.loadUrl(Constants.ACCOUNTEDITURL);
SharedPreferences pref = getApplicationContext().getSharedPreferences("Login", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("isLogedin", "true");
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have signed in", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
};
if(url.equals(Constants.CARTURL) && isRedirected && isLoggedin.equals("false")) {
Log.e(TAG, "Cart Login");
//webView.loadUrl(Constants.ACCOUNTEDITURL);
SharedPreferences pref = getApplicationContext().getSharedPreferences("Login", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("isLogedin", "true");
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have signed in", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
};
//if(url.equals(Constants.LOGOUTURL) && isLoggedin.equals("true")) {
if(url.equals(Constants.LOGOUTURL)) {
Log.e(TAG, "logging out-----------------");
SharedPreferences pref = getApplicationContext().getSharedPreferences("Login", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("isLogedin", "false");
//editor.clear();
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have logged out", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
//return;
}
if(isLoggedin.equals("true")) {
Log.e(TAG, "in get name-----------------");
mainView.addJavascriptInterface(new myJavaScriptInterface(), "CallToAnAndroidFunction");
//String getnamejs = "(document.getElementById('input-firstname').value);";
String getnamejs = "(document.getElementById('app_customer_name').innerHTML);";
mainView.loadUrl("javascript: window.CallToAnAndroidFunction.getUserName" + getnamejs);
}
Your help is highly appreciated, thank you in advanced.
Do you mean that the string variable isLoggedin is always false? could you mention where are you assigning the value for the variable isLoggedin.
Please try the below code, I have modified the putString with boolean.
boolean isLoggedin;
SharedPreferences pref =
getApplicationContext().getSharedPreferences("Login", MODE_PRIVATE);
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.e(TAG, "should override url loading" + url);
view.loadUrl(url);
isRedirected = true;
return true;
}
public void onPageFinished(WebView view, String url) {
Log.e(TAG, "on page finished" + url);
isLoggedin = pref.getBoolean(“isLoggedin”, false);
if (url.equals(Constants.ACCOUNTURL) && url.equals(Constants.CARTURL) && !isLoggedin) {
Log.e(TAG, "reload");
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(“isLoggedin", true);
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have signed in", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Log.e(TAG, "in get name-----------------");
mainView.addJavascriptInterface(new myJavaScriptInterface(), "CallToAnAndroidFunction");
//String getnamejs = "(document.getElementById('input-firstname').value);";
String getnamejs = "(document.getElementById('app_customer_name')[0].innerHTML);";
mainView.loadUrl("javascript: window.CallToAnAndroidFunction.getUserName" + getnamejs);
}
//if(url.equals(Constants.LOGOUTURL) && isLoggedin) {
if (url.equals(Constants.LOGOUTURL)) {
Log.e(TAG, "logging out-----------------");
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("isLoggedin", false);
//editor.clear();
editor.commit();
setWelcome();
Toast toast = Toast.makeText(MainActivity.this, "You have logged out", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
//return;
}
Let me know if that helps!

SharedPreferences always shows the same thing

So I'm trying to save a value to sharedpreferences by a click of a button, and then see which value it is in another activity. (to basically set a background for activity2 based on which button they pressed in activity1)
Saving code:
public void onClick(View v) {
SharedPreferences.Editor background = getSharedPreferences("Background", MODE_PRIVATE).edit();
if(btn1 == v)
{
background.remove("selectedBG");
Toast.makeText(this, "btn1", Toast.LENGTH_SHORT).show();
background.putInt("selectedBG", 1);
background.commit();
}
if(btn2 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 2);
Toast.makeText(this, "btn2", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn3 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 3);
Toast.makeText(this, "btn3", Toast.LENGTH_SHORT).show();
background.commit();
}
if(btn4 == v)
{
background.remove("selectedBG");
background.putInt("selectedBG", 4);
Toast.makeText(this, "btn4", Toast.LENGTH_SHORT).show();
background.commit();
}
}
And then, the Toast here always shows "chosenbackground:0":
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
LLayout=(LinearLayout)findViewById(R.id.llayout);
SharedPreferences background2 = getSharedPreferences("Background", MODE_PRIVATE);
int chosenBackground = background2.getInt("selectedBg", 0);
Toast.makeText(this,"chosenBackground:" + chosenBackground, Toast.LENGTH_SHORT).show();
if (chosenBackground != 0) {
if(chosenBackground==1)
{
LLayout.setBackgroundColor(Color.WHITE);
}
if(chosenBackground==2)
{
LLayout.setBackgroundColor(Color.rgb(34,34,34));
}
if(chosenBackground==3)
{
LLayout.setBackgroundColor(Color.rgb(51,68,85));
}
if(chosenBackground==4)
{
LLayout.setBackgroundColor(Color.rgb(68,34,17));
}
}
}
Answer for your question is that you have misspelled the key in second activity, in first one you are using "selectedBG" but in the second one "selectedBg". It is not the same, it's case sensitive. Correct in the second one for "selectedBG" and it should work.
Using the SharedPreferences here it's really bad idea, if u only want to pass a background or rather a color if I see it correctly. Just pass it in intent:
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("EXTRA_BACKGROUND_ID", background);
startActivity(intent);
Access that intent on next activity for eg. in onCreate()
String s = getIntent().getStringExtra("EXTRA_SESSION_ID");
#Updated
public class PreferencesUtils {
private SharedPreferences sharedPrefs;
private SharedPreferences.Editor prefsEditor;
public static final String KEY_BACKGROUND = "BACKGROUND";
public PreferencesUtils(Context context) {
this(context, PREFS_DEFAULT);
}
public PreferencesUtils(Context context, String prefs) {
this.sharedPrefs = context.getSharedPreferences(prefs, Activity.MODE_PRIVATE);
this.prefsEditor = sharedPrefs.edit();
}
public int getValue(String key, int defaultValue){
return sharedPrefs.getInt(key, defaultValue);
}
public boolean saveValue(String key, int value){
prefsEditor.putInt(key, value);
return prefsEditor.commit();
}
}
PreferencesUtils preferencesUtils = new PreferencesUtils(this);
preferencesUtils.saveValue(PreferencesUtils.KEY_BACKGROUND, 1); //saveValue
preferencesUtils.getValue(PreferencesUtils.KEY_BACKGROUND, 0); //getValue,
second arg is defult if not found
Use if (!background2.contains("selectedBg"))
to check ,first whether the key exists and if not getInt is not able to create a key and hence always returns default value 0.Also you can use apply() instead of commit to check whether commit has taken place successfully.Debug the code more to see all possibilities
int chosenBackground=0;
if (!background2.contains("selectedBg"))
{
//is called once when after you freshly install the app
background2.putInt("selectedBG", 0);
}
else
chosenBackground = background2.getInt("selectedBg", 0);

How can save state into SharedPreferences in Android

I want save isClickedState for imageButton, if clicked on this imageButton save this state and change color and when not clicked show default color and save false state!
I write below codes, but when click on button not save this state and when back to other activity and go to again this activity see not save state!
MyActivityCodes:
private ShineButton postShow_favPost;
private String favData = "FavPrefsList";
private Boolean favState;
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post_show_page);
bindActivity();
//Give Data
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString("title");
image = bundle.getString("image");
content = bundle.getString("content");
dateTime = bundle.getString("dateTime");
author = bundle.getString("author");
category = bundle.getString("category");
categoryID = bundle.getString("categoryID");
}
mAppBarLayout.addOnOffsetChangedListener(this);
//// Save Fav state
final SharedPreferences saveFavPrefs = getSharedPreferences(favData, MODE_PRIVATE);
final SharedPreferences.Editor editor = saveFavPrefs.edit();
favState = saveFavPrefs.getBoolean("isChecked", false);
postShow_favPost = (ShineButton) mToolbar.findViewById(R.id.po_image1);
postShow_favPost.init(this);
postShow_favPost.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(View view, boolean checked) {
if (favState == true) {
editor.putBoolean("isChecked", true);
editor.commit();
Toast.makeText(context, "Checked True", Toast.LENGTH_SHORT).show();
} else {
editor.putBoolean("isChecked", false);
editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
}
});
How can i fix this issue?
Make the following changes to your code. In the else part make the value false again. Its important because if your isChecked value was previously true, then the else part will be able to make it false:
I changed if(favState == true) to if(checked ==true)
if (checked == true) {
editor.putBoolean("isChecked", true);
editor.commit();
Toast.makeText(context, "Checked True", Toast.LENGTH_SHORT).show();
} else {
editor.putBoolean("isChecked", false);
editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
Boolean can be check by if(favState) not need to do this if(favState == true) boolean itself is true or false.
and save alternative state as i commented in else section.
if (favState) {
editor.putBoolean("isChecked", checked);
editor.commit();
Toast.makeText(context, "Checked True", Toast.LENGTH_SHORT).show();
} else {
//editor.putBoolean("isChecked", False);
//editor.commit();
Toast.makeText(context, "Checked False", Toast.LENGTH_SHORT).show();
}
If you haven't defined default value of checked as true then you need do following as default value of boolean is false:
//change this
editor.putBoolean("isChecked", checked);
//to this
editor.putBoolean("isChecked", true);
Let me know if this changes anything for you.

SharedPreference cannot save data across activities

I'm working on a splash screen where it will determine whether the user has previously registered or not based on SharedPreference stored values.
Please allow me to ask this question one more time, as I've gone through so many help / tutorials and examples, it didn't help a bit. I've been stuck here for 2 days now... Any help is really really appreciated.
There are 2 activities involved. The app starts with SplashScreen activity, then if sharepreference file return non-null (means user registered before), it will start mainactivity. Else if sharepreference file return null (means first time user, it brings user to the registration activity)...
PROBLEM: whenever the app restart (even with user registered), it always go to registration page !! PLEASE HELP !!
code for SPLASHSCREEN activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
}
}
};
timerThread.start();
}
protected void onStart() {
super.onStart();
openNextActivity();
}
public void openNextActivity(){
SharedPreferences sp = getSharedPreferences("pref", 0);
if (sp.contains("Name")) {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(SplashScreen.this, Registration.class);
startActivity(intent);
}
}
#Override
protected void onPause() {
super.onPause();
finish();
}
below is the code for REGISTRATION activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etMobilePhone = (EditText) findViewById(R.id.etMobilePhone);
tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); // imei
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmit:
writePref();
break;
}
finish();
}
private void writePref() {
String userName = etName.getText().toString(); //prepare variables values for write
String userPhone = etMobilePhone.getText().toString(); //prepare variables values for write
String userEmail = etEmail.getText().toString(); //prepare variables values for write
String userImei = tel.getDeviceId().toString(); //prepare variables values for write
SharedPreferences sp = getSharedPreferences("pref", 0); //sharepreference
SharedPreferences.Editor editor = sp.edit(); //sharepreference
editor.putString(Name, userName); //write sharepreferences
editor.putString(Phone, userPhone); //write sharepreferences
editor.putString(Email, userEmail); //write sharepreferences
editor.putString(Imei, userImei); //write sharepreferences
editor.commit(); //sharepreference
Toast toast = Toast.makeText(getApplicationContext(), "updated sharepreferences", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL,0,50);
toast.show();
}
Please guide me to the right directions. Thank you for reading and responding.
Change your openNextActivity() method to this:
public void openNextActivity(){
SharedPreferences sp = getSharedPreferences("pref", 0);
String defaultValue = "na";
String storedValue = sp.getString("Name", defaultValue);
if (!storedValue.equalsIgnoreCase("na")) {
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
} else { //if you get default value i.e. "na"
Intent intent = new Intent(SplashScreen.this, Registration.class);
startActivity(intent);
}
}
Instead of checking if the key exists, check for its value. If key not found return a default value and and check against the returned value.
Update (From Jelle's comment below): Also change your RegistrationActivity. Change editor.putString(Name, userName); into editor.putString("Name", userName);
Thanks guys... wanted to share the solution...
SharedPreferences sp = getSharedPreferences("pref", 0); //sharepreference
SharedPreferences.Editor editor = sp.edit(); //sharepreference
editor.putString("Name", userName); //write sharepreferences
editor.putString("Phone", userPhone); //write sharepreferences
editor.putString("Email", userEmail); //write sharepreferences
editor.putString("Imei", userImei); //write sharepreferences
editor.commit(); //sharepreference
Apparently, the solution is the ""... thanks for all the wonderful people...

Using SharedPreferences with more activities

I would like to save a given that then has to be shared between the main and secondary activity. I can not understand why my app does not work.
This is the Second activity:
switch (find)
{
case 0:
lunedi1.setBackgroundColor(getResources().getColor(R.color.green));
Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
pref=0;
SharedPreferences prefs = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("pref", pref);
editor.commit();
break;
And this is the MainActivity:
SharedPreferences prefs = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
int pref=100;
// Leggiamo l'informazione associata alla proprieta TEXT_DATA
int dato = prefs.getInt("pref", pref);
// Lo impostiamo alla TextView
if(pref==0)
{
lunedi1.setBackgroundColor(getResources().getColor(R.color.green));
}
lunedi1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int a=0;
final Intent intent = new Intent(MainActivity.this, Second.class);
intent.putExtra("info1", info1);
intent.putExtra("a", a);
intent.putExtra("id",id);
startActivity(intent);
}
in this way it should pass the data, and then the background should turn green but this does not happen.
You declare and initialize a new variable pref here
int pref=100;
so here
if(pref==0)
pref == 100 not 0
Not positive but I think you mean
if(dato == 0)
For storing data using SharedPreferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Tag","value");
editor.commit();
For retrieving data from SharedPreferences:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Tag","");

Categories

Resources