I made a switch button for something like "dark mode",basically it should change the app color, and it does, but only in the first activity, then, when i try to pass the boolean value to the 2nd activity it doesn't change the color of anything.
Main activity :
public void nightview(View view) {
Intent intent4 = new Intent(this, DisplayResultActivit.class);
Switch sw1 = findViewById(R.id.nightview);
boolean switchstate = sw1.isChecked();
intent4.putExtra("state", switchstate);
if (switchstate) {
//nightview
View lay = findViewById(R.id.layout);
...
2nd activity :
boolean state = getIntent().getExtras().getBoolean("state");
if (state) {
//nightview
View lay2 = findViewById(R.id.layout2);
lay2.setBackgroundColor(Color.BLACK);
TextView tv1 = findViewById(R.id.textView);
tv1.setTextColor(Color.WHITE);
tv.setTextColor(Color.WHITE);
} else {
//dayview
View lay2 = findViewById(R.id.layout2);
lay2.setBackgroundColor(Color.WHITE);
TextView tv1 = findViewById(R.id.textView);
tv1.setTextColor(Color.BLACK);
tv.setTextColor(Color.BLACK);
}
you can create a class AppPreference like this:-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static boolean getSwitchValue(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getBoolean("switch", false);
}
public static void setSwitchValue(Context ctx, Boolean value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putBoolean("switch", value);
mPrefsEditor.commit();
}
}
and set values from all the activities like this:-
to set switch value in preference:-
setSwitchValue(MainActivity.this, true);
to get switch value in all activites:-
getSwitchValue(MainActvity2.class);
Related
I'm having trouble getting my sharedpreferences to work. I'm trying to load in data from a textbox in another activity into a textview. I don't get any errors, but it keeps returning the default value of "nameKey".
Here is where the data is being entered and saved
public class ActivitySettings extends AppCompatActivity {
SharedPreferences sharedPreferences;
final String MyPREFERENCES = "MyPrefs";
final String Name = "nameKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final EditText enterName1 = (EditText) findViewById(R.id.enterName1);
final EditText enterName2 = (EditText) findViewById(R.id.enterName2);
Button btnOK = (Button) findViewById(R.id.btnOK);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
btnOK.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String n = enterName1.getText().toString();
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Name, n);
editor.commit();
}
});
and here's a different activity where i'm trying to read in the data and set it to a textview
public class ActivityDuel extends AppCompatActivity {
public String getPrefs(String n, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString(n, "nameKey");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duel);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView txtD1 = (TextView) findViewById(R.id.txtD1);
txtD1.setText(getPrefs("name", this));
}
}
Call like this
txtD1.setText(getPrefs("nameKey", this));
And your getPrefs() function should like below
public String getPrefs(String n, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
return preferences.getString(n, "");
}
I think it's better to create a class for handle your SharedPreferences and add your key as static string to it and use methods for insert and read. here an example:
SettingProvider.class
public class SettingProvider {
private static final String SETTING_PROVIDER_NAME = "setting";
public static final String NAME = "name"
private SharedPreferences sharedPreferences;
private static SettingProvider ourInstance;
private SharedPreferences sharedPreferences;
private SettingProvider(Context context) {
if (context == null)
throw new RuntimeException("context must be valid!");
this.sharedPreferences = context.getSharedPreferences(SETTING_PROVIDER_NAME, 0);
}
public static SettingProvider getInstance(Context context) {
if (ourInstance == null) {
ourInstance = new SettingProvider(context);
}
return ourInstance;
}
public void setName(String name) {
return this.sharedPreferences.edit().setString(NAME, name).apply();
}
public String getName() {
return this.sharedPreferences.getString(NAME, "");
}
}
now for use in activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duel);
SettingProvider.getInstance(this).setName("the name");
String name = SettingProvider.getInstance(this).getName();
}
I think the issue is that you are saving a shared preferences key of 'Name', so from the field final String Name = "nameKey"; the preferences key is 'nameKey'
Then when you try and get the string out you are using "name" as the lookup key value and as it doesn't exist it gets set to the default of 'nameKey' so I think you need to change this txtD1.setText(getPrefs("name", this)); to txtD1.setText(getPrefs(Name, this));
I have a notes app that whereby i implemented two types of views: List and Grid Views.
A user can switch between listView and gridView depending on his choice. The issue i have is that i have been trying to save the state of the view persistently such that the selected view is opened up at start up. Am trying to use SharedPreferences to achieve this. what am doing getting wrong in my code?
private static final String KEY_NAME = "viewState";
private ListView mListNotes;
private GridView mGridNotes;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
private boolean mViewIsChanged = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the layouts for list/grid
mListNotes = (ListView) findViewById(R.id.main_listview);
mGridNotes = (GridView) findViewById(R.id.main_gridview);
// Retrieve value from Shared Preferences.
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
mViewIsChanged = sharedPreferences.getBoolean(KEY_NAME, false);
if (!mViewIsChanged){
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);}
else {
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View customTitleView = inflater.inflate(R.layout.dialog_menu, null);
LinearLayout mListViewSelect = (LinearLayout) customTitleView.findViewById(R.id.list_select);
LinearLayout mGridViewSelect = (LinearLayout) customTitleView.findViewById(R.id.grid_select);
switch (item.getItemId()) {
case R.id.addItem:
// start NoteActivity
startActivity(new Intent(this, NoteActivity.class));
break;
case R.id.changeView:
final AlertDialog alertbox = new AlertDialog.Builder(this).create();
alertbox.setCancelable(true);
alertbox.setView(customTitleView);
alertbox.show();
mListViewSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Saving Data
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(KEY_NAME, mViewIsChanged);
editor.apply();
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);
alertbox.dismiss();
}
});
mGridViewSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// saving Data in SharedPreferences
mViewIsChanged = true;
sharedPreferences = getPreferences(Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putBoolean(KEY_NAME, mViewIsChanged);
editor.apply();
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
alertbox.dismiss();
}
});
After this in your onCreate ()
mViewIsChanged = sharedPreferences.getBoolean(KEY_NAME, false);
mListNotes = (ListView) findViewById(R.id.main_listview);
mGridNotes = (GridView) findViewById(R.id.main_gridview);
Add this
If (!mViewIsChanged){
mListNotes.setVisibility(View.VISIBLE);
mGridNotes.setVisibility(View.GONE);}
else {
mListNotes.setVisibility(View.GONE);
mGridNotes.setVisibility(View.VISIBLE);
}
Or put the logic provided by me after setting the adapter in your onResume()
Hope that helps.
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
editText.setText(nm);
editText1.setText(ps);
Toast.makeText(Page1.this,"Checkbox Remember me is " + String.valueOf(b),Toast.LENGTH_LONG).show();
}
}
});
I am trying to make a login page which has two EditTexts and a CheckBox. I am trying to save login details in sharedprefrences when the CheckBox is checked. In my code, I set the OnCheckedListner to know whether it is checked or not. But the boolean value b is always true...WHY?
Please Help me!
Full Code on Page1 activity :
public class Page1 extends AppCompatActivity {
Button button;
EditText editText,editText1;
CheckBox checkBox;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
button = (Button)findViewById(R.id.bt1);
editText = (EditText)findViewById(R.id.et1);
editText1 = (EditText)findViewById(R.id.et2);
checkBox = (CheckBox)findViewById(R.id.cb1);
sharedPreferences = getSharedPreferences("MYSP", MODE_PRIVATE);
final String nm = sharedPreferences.getString("uname", "");
final String ps = sharedPreferences.getString("upass", "");
final boolean saveLogin = sharedPreferences.getBoolean("save",false);
final boolean logout = sharedPreferences.getBoolean("logout", false);
if (!logout){
Intent intent = new Intent(Page1.this, ProfilePage.class);
startActivity(intent);
}
final boolean[] isChecked = new boolean[1];
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
editText.setText(nm);
editText1.setText(ps);
Toast.makeText(Page1.this,"Checkbox Remember me is "+ String.valueOf(b) ,Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(Page1.this,"Checkbox Remember me is "+ String.valueOf(b),Toast.LENGTH_LONG).show();
}
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editText.getText().toString();
String pass = editText1.getText().toString();
SharedPreferences.Editor editor = sharedPreferences.edit();
if (isChecked[0]) {
editor.putString("uname", name);
editor.putString("upass", pass);
editor.putBoolean("save", true);
editor.putBoolean("logout", false);
editor.commit();
}
else {
editor.putString("uname", name);
editor.putString("upass", pass);
editor.putBoolean("logout", false);
editor.commit();
}
Intent intent = new Intent(Page1.this, ProfilePage.class);
startActivity(intent);
}
});
}
}
ProfilePage Activity code :
public class ProfilePage extends AppCompatActivity {
Button button;
TextView textView;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_page);
button = (Button)findViewById(R.id.btn1);
textView = (TextView)findViewById(R.id.tv1);
sharedPreferences = getSharedPreferences("MYSP", MODE_PRIVATE);
final String n = sharedPreferences.getString("uname", "");
final String p = sharedPreferences.getString("upass", "");
textView.setText("Welcome "+ n + " ");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences.Editor editor = sharedPreferences.edit();
if (sharedPreferences.getBoolean("save", false)) {
editor.putString("uname", n);
editor.putString("upass", p);
editor.putBoolean("logout", true);
editor.commit();
}
else {
editor.clear();
editor.putBoolean("logout", true);
editor.commit();
}
textView.setText("Logout Success!");
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
}
Your code handles only the case b = true. Modify your code to include an else part like
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
editText.setText(nm);
editText1.setText(ps);
Toast.makeText(Page1.this,"Checkbox Remember me is true",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Page1.this,"Checkbox Remember me is false",Toast.LENGTH_LONG).show();
}
}
});
This is your checkbox in xml:
<CheckBox
android:id="#+id/remember_me_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:buttonTint="#color/white"
android:gravity="left" />
This is your java code:
private CheckBox remember_me_checkbox;
private boolean isRemembered; //false by default
remember_me_checkbox = (CheckBox) findViewById(R.id.remember_me_checkbox);
remember_me_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isRemembered = isChecked;
}
});
Whenever user successfully logged in, you just save it in the preference. At the same time you have to save username and password as per your requirement.
SharedPreferences pref
=getApplicationContext().getSharedPreferences(AppPreferences.PREF_FIREBASE_TOKEN, 0);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("remembered", isRemembered);
editor.commit();
And, next time when you come to this screen in case of logout. You will check whether isRemembered is true or not, if it is true then you get the username and password and set them to respective editTexts.
SharedPreferences pref = getApplicationContext().getSharedPreferences(AppPreferences.PREF_FIREBASE_TOKEN, 0);
boolean remembered = pref.getBoolean("remembered", false);
if(remembered ){
//get the username and password from pereference and set to editTexts.
}
You shouldn't have added OnCheckChangeListener in first place. You should have saved the credentials in SharedPreference when Login button is clicked by checking all the validation of email and password and checked status of your remember me checkbox.
Also in onCreate you must checked for isRemember value from SharedPreference and show put the values in Edittext accordingly.
I'm new to java. I've made a counter which goes up as user holds on a button. I want the app to start with int value of where it left. I know SharedPreference is the way to go but I've no idea how to use it. I'm not sure where to put which part of SharedPreference. Thank you.
public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
text.setText(String.valueOf(count));
return false;
}
});
}
}
Add the following function to your activity
public int getValue(String key) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int value = sharedPref.getInt(key, 0);
return value;
}
public void saveValue(String key, int value) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, value);
editor.commit();
}
Some code added in your onCreate() method
final String key = "somekey";
count = getValue(key); //get value from sharedPreference
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
text.setText(String.valueOf(count)); // set it first
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
saveValue(key,count);
text.setText(String.valueOf(count));
return false;
}
});
You can do it like this,save count in SharedPreference when destroy the activity and read value from SharedPreference when you create it:
public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;
SharedPreferences sh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
sh = getSharedPreferences("sh_name", MODE_PRIVATE);
count = sh.getInt("count", 1);
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
count++;
text.setText(String.valueOf(count));
return false;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
sh.edit().putInt("count", count).apply();
}
}
Try turning
int count = 1;
into
static int count = 1;
I'm also somewhat a Java noobie so this may or may not work.
here I have three buttons Yes no maybe for three buttons I have changed the colour when the button clicked and store the value of clicked button in shared preference for hold the colour when ever I back to the button
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.invitation, null);
eventNameTxtV = (TextView) convertView.findViewById(R.id.invitation_title);
eventPlaceTxtV = (TextView) convertView.findViewById(R.id.invitation_place);
eventNameTxtV.setText(eventMOs.get(position).getText());
eventPlaceTxtV.setText(eventMOs.get(position).getPlace());
convertView.setTag(position);
View v = convertView.findViewById(R.id.invitation_single);
final Button yesBtn = (Button) convertView.findViewById(R.id.yesbutton);
final Button noBtn = (Button) convertView.findViewById(R.id.nobutton);
final Button maybeBtn = (Button) convertView.findViewById(R.id.buttonmaybe);
final LinearLayout eventLayout = (LinearLayout) convertView.findViewById(R.id.invitation_single);
final LinearLayout responseLayout = (LinearLayout) convertView.findViewById(R.id.hidden);
//Based on the user click, response will be stored
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// highlight the button when clicked
yesBtn.setBackgroundColor(Color.YELLOW);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks yes button in invitation response layout,response would be stored as 1 for event user
final int response = 1;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
//create shared preferences here
prefs =getActivity().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =prefs.edit();
editor.putString("buttonClicked","true");
editor.commit();
/*SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 1);
editor.commit();*/
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.YELLOW);
maybeBtn.setBackgroundColor(Color.BLUE);
responseLayout.setVisibility(View.GONE);
//If user clicks no button in invitation response layout,response would be stored as 0 for event user
final int response = 0;
final long eventId = eventMOs.get(position).getEventId();
userMO.setIsAttending(response);
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn", 0);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
maybeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yesBtn.setBackgroundColor(Color.BLUE);
noBtn.setBackgroundColor(Color.BLUE);
maybeBtn.setBackgroundColor(Color.YELLOW);
responseLayout.setVisibility(View.GONE);
//If user clicks maybe button in invitation response layout,response would be stored as for event user
final int response = 2;
userMO.setIsAttending(response);
final long eventId = eventMOs.get(position).getEventId();
SharedPreferences sharedpreferences = getActivity().getSharedPreferences("PREFERENCE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("clicked_btn",2);
editor.commit();
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... arg0) {
return userDelegate.updateEventUserRelationShipMapping(userMO, eventId);
}
}.execute(null, null, null);
}
});
here I have to hold the colour change of button whenever I return back to the app if I selected any of the button .so how to use and retrieve the shared preference value
this is the code for show the yes no maybe buttons together when I clicked the event
eventLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.invitation_single:
responseLayout.setVisibility(View.VISIBLE);
break;
}
}
});
SharedPreferences gives you the ability to store different kind of data, such as boolean or int.
To accomplish your task, you could store the color of each button in SharedPreferences; something like:
editor.putInt("button_one", R.color.buttone_one_selected);
Remember, when you'll retrieve that color, you have to resolve it with:
int buttonOneColor = sharedPrefs.getInt("button_one", default_value);
int colorBackground = getResources().getColor(buttonOneColor);
You can change color of your button using this...
In onCreate:
SharedPreferences prefs = getSharedPreferences("myPrefs",
Context.MODE_PRIVATE);
now check for the boolean value stored in the preferences :
boolean b1_pressed = prefs.getBoolean("button1_pressed",false);
if(b1_pressed){
//code to change color of button to pressed state
}
else{
//code to change color of button to normal state
}
Now in your button's onClick method:
if(b1_pressed){
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",false);
editor.commit();
}
else{
SharedPreferences.editor editor = prefs.edit();
editor.putBoolean("button1_pressed",true);
editor.commit();
}