This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 5 years ago.
I have a setting activity with a TextView and a set off buttons.
I Want each button to changes the background of textviews in other activities.
I need example codes on how to do this.
Thank you all in advance.
Code:
btn.setOnClickListener( new
View .OnClickListener () {
public boolean stateChanged;
public void onClick(View view) {
if (stateChanged) {
// reset background to default;
tv.setBackgroundResource
(R.drawable.favon);
} else {
tv.setBackgroundResource
(R.drawable.favoff);
}
stateChanged = !stateChanged;
In a nutshell, you would start by initializing it.
Use get to grab any saved value or default if nothing was found.
Or use edit and put to store the data.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getInt("key", defaultValue);
sharedPreferences.edit().putInt("key", value).apply()
More
EDIT:
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set up how the background was before
if (sharedPreferences.getBoolean("textViewBackground", true)) {
// Default background
tv.setBackgroundResource(R.drawable.favon);
} else {
// Other background
tv.setBackgroundResource(R.drawable.favoff);
}
btn.setOnClickListener(new View.OnClickListener() {
public boolean stateChanged;
public void onClick(View view) {
if (stateChanged) {
// reset background to default;
tv.setBackgroundResource(R.drawable.favon);
} else {
tv.setBackgroundResource(R.drawable.favoff);
}
stateChanged = !stateChanged;
sharedPreferences.edit().putBoolean("textViewBackground", stateChanged).apply();
}
});
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
In my application I have a booking system which allows users to book tee times for specific times during the day. When a booking has been completed the details are saved to my Firebase and the user can then close the alert dialog. When the alert dialog is then closed the button which was clicked is then made unusable. Problem is that when the user leaves the booking activity and comes back the button is then useable, and if a different user then accesses the page the button is also able to be clicked as well.
How do I solve this problem?
Should I be saving the UID of the user in the 9am child ?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
findViewById(R.id.profilebtn).setOnClickListener(this);
findViewById(R.id.booking9am).setOnClickListener(this);
book9am = (Button)findViewById(R.id.booking9am);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.profilebtn:
finish();
startActivity(new Intent(Booking.this, ProfileActivity.class));
break;
case R.id.booking9am:
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(Booking.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_booking,null);
final EditText mPlayer1 = (EditText) mView.findViewById(R.id.player1);
final EditText mPlayer2= (EditText) mView.findViewById(R.id.player2);
final EditText mPlayer3 = (EditText) mView.findViewById(R.id.player3);
final EditText mPlayer4 = (EditText) mView.findViewById(R.id.player4);
final EditText mTime = (EditText) mView.findViewById(R.id.timeedit);
final Button mBookingbtn = (Button) mView.findViewById(R.id.bookingbtn);
mBookingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String player1= mPlayer1.getText().toString().trim();
String player2= mPlayer2.getText().toString().trim();
String player4= mPlayer4.getText().toString().trim();
String player3= mPlayer3.getText().toString().trim();
if (player1.isEmpty()) {
mPlayer1.setError("Please enter player 1");
mPlayer1.requestFocus();
return;
}
if (player2.isEmpty()) {
mPlayer2.setError("Please enter player 2");
mPlayer2.requestFocus();
return;
}
if (player3.isEmpty()) {
mPlayer3.setError("Please enter player 2");
mPlayer3.requestFocus();
return;
}if (player2.isEmpty()) {
mPlayer4.setError("Please enter player 2");
mPlayer4.requestFocus();
return;
}
String playerone = mPlayer1.getText().toString();
String playertwo = mPlayer2.getText().toString();
String playerthree = mPlayer3.getText().toString();
String playerfour = mPlayer4.getText().toString();
String teetime= mTime.getText().toString().trim();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Booking").child("9am");
Map newPost = new HashMap();
newPost.put("playerone",playerone);
newPost.put("playertwo",playertwo);
newPost.put("playerthree",playerthree);
newPost.put("playerfour",playerfour);
newPost.put("teetime",teetime);
current_user_db.setValue(newPost);
Toast.makeText(Booking.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
book9am.setClickable(false);
}
});
mBuilder.setNeutralButton("Close ", new DialogInterface.OnClickListener() { // define the 'Cancel' button
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
}
In your onCreate method -
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Booking").child("9am");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
book9am.setClickable(false);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
well there could be multiple approaches to this problem.
One is to set a Boolean variable in local storage Shared preference against every user....
Once your click the button set the value to true and when u come back in app check if variable is true then disable button..
Second solution Store the varible against every user on firebase and check(recommended since user can change phone)
Before showing the activity you will have to make a request to your firebase to check if the booking has been completed and depending on the result make the button enabled or not.
findViewById(R.id.booking9am).setOnClickListener(this) instead of this use:-
book9am = (Button)findViewById(R.id.booking9am);
book9am.setOnClickListener(this);
and instead of book9am.setClickable(false) set book9am.setEnable(false);
OR
If you want button disable on some conditions then it can be managed at server side also.
There are two approaches to your problem, depending on your needs.
First, is saving the button's state locally (on the client side), which means that after removing and re-installing the app for example, the state will be reset as well.
In order to save the button's state "forever", you should save the wanted state on the device, and this is what SharedPreferences is made for.
This is a good example of using it.
Here is how you should implement it in your code:
public static void set_isButtonClickable(Context ctx, Boolean bool) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean("BUTTON_CLICKABLE_STATE", bool);
editor.commit();
}
public static boolean getPrefIsFirstLaunch(Context ctx) {
return getSharedPreferences(ctx).getBoolean("BUTTON_CLICKABLE_STATE",false);
}
Second, is saving the button's state on the server side. Removing and re-installing the app obviously won't change its state. Make each user a variable which called "button_state" and change it as needed:
I made an app whos purpose is to download and set wallpaper in set intervals.
User can choose to do that only when connected to wifi or not.
Relevant code:
mWallpaperButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSwitchWifi.isChecked()) {
mConnectivity = mConnectionDetector.isConnectedToWifi();
} else {
mConnectivity = mConnectionDetector.isConnectedToInternet();
}
if (mConnectivity) {
my code here
}
The code above works fine for setting the wallpaper the first time.
My problem is, I need the Service to check if the user wants to update wallpaper only over WIFI before doing so. At the moment, wallpaper is updated regardless of mSwitchWifi state. (which is bad, because it can use mobile data and user sometimes doesn't want that.)
I tried running similar Switch code in Service but I can't because it must be called in a UI Thread.
I also tried couple of workarounds and Intent.putExtra but I get exception:
NullPointerException: Attempt to invoke virtual method on a null object reference
Any idea how to check network state in service?
My service code atm:
public static class Service extends IntentService {
public Service() {
super("wallpaperchanger-download");
}
#Override
protected void onHandleIntent(Intent intent) {
if (url == null) {
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String getUrl = sharedPreferences.getString(pref_urlKey, null);
if (getUrl != null) {
url = getUrl;
}
}
wm = WallpaperManager.getInstance(this);
try {
InputStream input = new URL(url).openStream();
Log.v(TAG, url);
wm.setStream(input);
input.close();
} catch (Exception e) {
e.printStackTrace();
}
loading = false;
Log.v(TAG, "Service Running Url " + url);
}
}
If you question is how to access the user selection inside a service/runnable/thread then you can use shared preferences to achieve this. So in your case when the user selects the choice for the first time you want to do something like this:
if(mSwitchWifi.isChecked()) { // i guess this is no wifi
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
Editor editor = sharedPeredences.edit()
editor.putBoolean("isWifi", false)
} else { // guessing this is wifi
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
Editor editor = sharedPeredences.edit()
editor.putBoolean("isWifi", true)
}
This is this code to check if it is true or false:
mWallpaperButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Boolean isWifi = isWifi()
if (!isWifi) { // i guess this is if not wifi
mConnectivity = mConnectionDetector.isConnectedToWifi();
} else if (isWifi) { // guessing this is wifi
mConnectivity = mConnectionDetector.isConnectedToInternet();
}
}
}
public Boolean isWifi() { // you can call this inside your service
SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
Boolean wifiState = sharedPreferences.getBoolean("isWifi", true)
return wifiState;
}
This is just a very rough implementation to give an idea of how you can do it, you can improve this many ways. For example you could put the if statement thats inside the onClickListener in the isWifi() function and just call isWifi() inside your runnable/thread...
you can set list preferences to auto update functions based on the network ....
You can create separate class to check the connectivity and from that class you can select the preferences like auto update only on wifi or when connected to network or do not auto update ....
This question already exists:
why "setContentView" can't work in " if " ??? thx [closed]
Closed 9 years ago.
the code is in onCreate! when setContentView(R.layout.manual); is outside the if it works. But I moved setContentView(R.layout.manual); into if can’t work!
The followign:
if (settings.getBoolean("my_first_time", true)) {
setContentView(R.layout.manual); // can not work
}
But Log.d("Comments1", "First time"); always works
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getBoolean("my_first_time", true)) {
//the app is being launched for first time, do something
Log.d("Comments1", "First time");//this can be showed on logCat!
setContentView(R.layout.manual);// this can not work
// record the fact that the app has been started at least once
settings.edit().putBoolean("my_first_time", false).commit();
}
}
Your condition is not getting satisfied because
settings.getBoolean("my_first_time", true)
is not returning true.
Hence your
setContentView(R.layout.manual)
is not called inside the “if” block.
You need to know what you are doing if you set a if-else loop, because no matter what is the outcome setContentView() must be supplied with a valid layout id. If you have a condition to check before setting the layout, you can just check the id:
int layoutId=0;
if(condition) {
layoutId = R.layout.manual;
} else {
layoutId = R.layout.other;
}
setContentView(layoutId);
I'm writing a flash card app in Android, and I tried to add the ability to add a word to a review list by having a checkbox. When the user goes to the next word, I see whether the checkbox is checked. If it is, I add the word to the review list, and if it isn't, I remove the word. When I tested it on my phone and the emulator, I got a forced close every time I try to go to the next word or to the home page when the checkbox is checked. I don't know what's causing the error because in the LogCat page, it doesn't show the line number or what error happened.
I can flip through the words without a problem when I don't have them checked; checking it and going to another word is what causes a problem, so I'm guessing it has to do with the SharedPreferences.
Here are the important methods I have:
public void onCreate(Bundle savedInstanceState)
{
//other code
reviewCheckBox = (CheckBox) findViewById(R.id.reviewCheckBox);
prefs = getPreferences(MODE_PRIVATE);
editor = prefs.edit();
reviewCards = prefs.getAll().keySet();
}
public void home(View v)
{
if (flashCardPage.getVisibility() == View.VISIBLE)
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
updateReviewCards();
}
//other code
}
public void nextWord(View v)
{
currentPosition++;
if (currentPosition == flashCards.size())
{
home(wordTV);
}
else
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
//other code
if (reviewCards.contains(currentCard.getTerm()))
reviewCheckBox.setChecked(true);
else
reviewCheckBox.setChecked(false);
}
}
public void previousWord(View v)
{
if (currentPosition > 0)
{
if (reviewCheckBox.isChecked())
reviewCards.add(currentCard.getTerm());
else
reviewCards.remove(currentCard.getTerm());
//other code
if (reviewCards.contains(currentCard.getTerm()))
reviewCheckBox.setChecked(true);
else
reviewCheckBox.setChecked(false);
}
}
public void updateReviewCards()
{
editor.clear();
for (String card : reviewCards)
editor.putString(card, card);
editor.commit();
}
The set returned by getPreferences().getAll().keySet() does not support adding.