Android: Shared preferences not saving the state of the buttons - android

I have a tab-host with three activities and in each activity I have buttons.
On each button press I am changing the background drawable resource
So now How can I save the pressed state of each button in all three child activities so that when I move from one activity to the other, the button pressed state will be reflected on moving back. first activity -> all 2 buttons pressed -> go to 2nd activity -> come back to first activity -> all buttons in first activity should be in pressed state with the drawable resource changed
I have two background Images.
button press -> highlited background image -> second time press same button ->changes to normal background Image
For the first time when I run the application and If I press the button the background image is getting changed. If I go to 2nd child activity and coming back so the button is in pressed state with changed drawable resource. so Its fine
for the second time If I press the same button and coming back to the same activity from second activity. here its not working
First child activity -> press button ->high lighted background image changes ->go to second tabhost child activity -> come back to first child activity -> button is showing the same background image after pressing(this is fine)
the problem is
now you press the same button in first child activity -> background image changes to normal ->go to second tabhost child activity -> come back to first child activity -> but the button background resource is in highlighted instead of normal
and even If I run the application once again the button is showing the highligted background image
the below code I am using in my first child activity
EDITED
public void onResume() {
super.onResume();
SharedPreferences sharedPreferences = this.getSharedPreferences(
"sharedPreferences", MODE_PRIVATE);
int which = sharedPreferences.getInt("sharedPreferences", 1);
switch (which)
{
case 1:
seatdirnbtn.setBackgroundResource(R.drawable.icon4); break;
case 2:
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt); break;
default:
seatdirnbtn.setBackgroundResource(R.drawable.icon4); break;
}
}
public void onPause() {
super.onPause();
boolean isclick = false;
SharedPreferences sharedPreferences = this.getSharedPreferences(
"sharedPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
editor.putInt("sharedPreferences", 2).commit();
}
}
EDIT2
public static boolean isclick = false;
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
isclick = !isclick;
}
};

Try this change:
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
editor.clear();
editor.putInt("sharedPreferences", 2).commit();
}
else {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
editor.clear();
editor.putInt("sharedPreferences", 1).commit();
}

Here's what i meant:
boolean[] btnBool = new boolean[2]; // number of buttons
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
toggleBtn(0); //zero refers to which index of the array for button button
setDrawables();
}
};
public void onResume() {
super.onResume();
toggleAllBtns();
setDrawables();
}
private void toggleBtn(int index) {
if(btnBool[index]) {
btnBool[index] = false;
} else {
btnBool[index] = true;
}
}
private void toggleAllBtns() {
// first switch the values of the array
for (int i = 0; i < btnBool.length; i++) {
if(btnBool[i]) {
btnBool[i] = false;
} else {
btnBool[i] = true;
}
}
}
private void setDrawables() {
// then set drawables based on values
if (btnBool[0]) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
} else {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
}
}

Related

Showing results for a quiz app (Android Studio)

I have a quiz app that is working properly, but the thing is the user must answer all questions correctly in order to win the game(if the player gets it wrong the game will be over) .
What I wanted to do is have the questions answered and then at the end there will be an activity that will show how many the player has answered then there will be the options to retry and go back to menu
This is the code for the maingameactivity
public class MainGameActivity extends AppCompatActivity {
FButton buttonA, buttonB, buttonC, buttonD;
TextView questionText, triviaQuizText, timeText, resultText, coinText;
TriviaQuizHelper triviaQuizHelper;
TriviaQuestion currentQuestion;
List<TriviaQuestion> list;
int qid = 0;
int timeValue = 20;
int coinValue = 0;
CountDownTimer countDownTimer;
Typeface tb, sb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
//Initializing variables
questionText = (TextView) findViewById(R.id.triviaQuestion);
buttonA = (FButton) findViewById(R.id.buttonA);
buttonB = (FButton) findViewById(R.id.buttonB);
buttonC = (FButton) findViewById(R.id.buttonC);
buttonD = (FButton) findViewById(R.id.buttonD);
triviaQuizText = (TextView) findViewById(R.id.triviaQuizText);
timeText = (TextView) findViewById(R.id.timeText);
resultText = (TextView) findViewById(R.id.resultText);
coinText = (TextView) findViewById(R.id.coinText);
//Setting typefaces for textview and buttons - this will give stylish fonts on textview and button etc
tb = Typeface.createFromAsset(getAssets(), "fonts/TitilliumWeb-Bold.ttf");
sb = Typeface.createFromAsset(getAssets(), "fonts/shablagooital.ttf");
triviaQuizText.setTypeface(sb);
questionText.setTypeface(tb);
buttonA.setTypeface(tb);
buttonB.setTypeface(tb);
buttonC.setTypeface(tb);
buttonD.setTypeface(tb);
timeText.setTypeface(tb);
resultText.setTypeface(sb);
coinText.setTypeface(tb);
//Our database helper class
triviaQuizHelper = new TriviaQuizHelper(this);
//Make db writable
triviaQuizHelper.getWritableDatabase();
//It will check if the ques,options are already added in table or not
//If they are not added then the getAllOfTheQuestions() will return a list of size zero
if (triviaQuizHelper.getAllOfTheQuestions().size() == 0) {
//If not added then add the ques,options in table
triviaQuizHelper.allQuestion();
}
//This will return us a list of data type TriviaQuestion
list = triviaQuizHelper.getAllOfTheQuestions();
//Now we gonna shuffle the elements of the list so that we will get questions randomly
Collections.shuffle(list);
//currentQuestion will hold the que, 4 option and ans for particular id
currentQuestion = list.get(qid);
//countDownTimer
countDownTimer = new CountDownTimer(22000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic to set text to timeText
timeText.setText(String.valueOf(timeValue) + "\"");
//With each iteration decrement the time by 1 sec
timeValue -= 1;
//This means the user is out of time so onFinished will called after this iteration
if (timeValue == -1) {
//Since user is out of time setText as time up
resultText.setText(getString(R.string.timeup));
//Since user is out of time he won't be able to click any buttons
//therefore we will disable all four options buttons using this method
disableButton();
}
}
//Now user is out of time
public void onFinish() {
//We will navigate him to the time up activity using below method
timeUp();
}
}.start();
//This method will set the que and four options
updateQueAndOptions();
}
public void updateQueAndOptions() {
//This method will setText for que and options
questionText.setText(currentQuestion.getQuestion());
buttonA.setText(currentQuestion.getOptA());
buttonB.setText(currentQuestion.getOptB());
buttonC.setText(currentQuestion.getOptC());
buttonD.setText(currentQuestion.getOptD());
timeValue = 20;
//Now since the user has ans correct just reset timer back for another que- by cancel and start
countDownTimer.cancel();
countDownTimer.start();
//set the value of coin text
coinText.setText(String.valueOf(coinValue));
//Now since user has ans correct increment the coinvalue
coinValue++;
}
//Onclick listener for first button
public void buttonA(View view) {
//compare the option with the ans if yes then make button color green
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
//Check if user has not exceeds the que limit
if (qid < list.size() - 1) {
//Now disable all the option button since user ans is correct so
//user won't be able to press another option button after pressing one button
disableButton();
//Show the dialog that ans is correct
correctDialog();
}
//If user has exceeds the que limit just navigate him to GameWon activity
else {
gameWon();
}
}
//User ans is wrong then just navigate him to the PlayAgain activity
else {
gameLostPlayAgain();
}
}
//Onclick listener for sec button
public void buttonB(View view) {
if (currentQuestion.getOptB().equals(currentQuestion.getAnswer())) {
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for third button
public void buttonC(View view) {
if (currentQuestion.getOptC().equals(currentQuestion.getAnswer())) {
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//Onclick listener for fourth button
public void buttonD(View view) {
if (currentQuestion.getOptD().equals(currentQuestion.getAnswer())) {
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
correctDialog();
} else {
gameWon();
}
} else {
gameLostPlayAgain();
}
}
//This method will navigate from current activity to GameWon
public void gameWon() {
Intent intent = new Intent(this, GameWon.class);
startActivity(intent);
finish();
}
//This method is called when user ans is wrong
//this method will navigate user to the activity PlayAgain
public void gameLostPlayAgain() {
Intent intent = new Intent(this, PlayAgain.class);
startActivity(intent);
finish();
}
//This method is called when time is up
//this method will navigate user to the activity Time_Up
public void timeUp() {
Intent intent = new Intent(this, Time_Up.class);
startActivity(intent);
finish();
}
//If user press home button and come in the game from memory then this
//method will continue the timer from the previous time it left
#Override
protected void onRestart() {
super.onRestart();
countDownTimer.start();
}
//When activity is destroyed then this will cancel the timer
#Override
protected void onStop() {
super.onStop();
countDownTimer.cancel();
}
//This will pause the time
#Override
protected void onPause() {
super.onPause();
countDownTimer.cancel();
}
//On BackPressed
#Override
public void onBackPressed() {
Intent intent = new Intent(this, HomeScreen.class);
startActivity(intent);
finish();
}
//This dialog is show to the user after he ans correct
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(MainGameActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
//Since the dialog is show to user just pause the timer in background
onPause();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
FButton buttonNext = (FButton) dialogCorrect.findViewById(R.id.dialogNext);
//Setting type faces
correctText.setTypeface(sb);
buttonNext.setTypeface(sb);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//it will increment the question number
qid++;
//get the que and 4 option and store in the currentQuestion
currentQuestion = list.get(qid);
//Now this method will set the new que and 4 options
updateQueAndOptions();
//reset the color of buttons back to white
resetColor();
//Enable button - remember we had disable them when user ans was correct in there particular button methods
enableButton();
}
});
}
//This method will make button color white again since our one button color was turned green
public void resetColor() {
buttonA.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonB.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonC.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
buttonD.setButtonColor(ContextCompat.getColor(getApplicationContext(),R.color.white));
}
//This method will disable all the option button
public void disableButton() {
buttonA.setEnabled(false);
buttonB.setEnabled(false);
buttonC.setEnabled(false);
buttonD.setEnabled(false);
}
//This method will all enable the option buttons
public void enableButton() {
buttonA.setEnabled(true);
buttonB.setEnabled(true);
buttonC.setEnabled(true);
buttonD.setEnabled(true);
}
}
Edited
Just remove the wrapper if else inside all the buttons better to keep it as, don't repeat the code. I am assuming the screen that shows result is handled inside gameWon and you have implemented functionality for inCorrectDialog
public void buttonA(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonB(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonC(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonD(View view) {
Button button = (Button) view;
buttonPressed(button);
}
public void buttonPressed(Button button) {
button.setButtonColor(ContextCompat.getColor(getApplicationContext(), R.color.lightGreen));
if (qid < list.size() - 1) {
disableButton();
if (currentQuestion.getOptA().equals(currentQuestion.getAnswer())) {
correctDialog();
} else {
inCorrectDialog();
}
} else {
gameWon();
}
}

Perform action only if two buttons are clicked

This is the first time I'm ever dabbling in Android development so please bear with me.
My requirement is this:
I have two buttons on screen, A and B. If the user presses both buttons (order doesn't matter), I need another page to be displayed. Pressing either A or B should do nothing.
Is this possible? If so, how would I achieve this?
Thank you.
This is possible if you take a flag. (boolean)
You should set a flag in your button listeners.
public class Mtest extends Activity {
Button b1;
Button b2;
boolean flag_1 = false;
boolean flag_2 = false;
public void onCreate(Bundle savedInstanceState) {
...
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(myhandler1);
b2.setOnClickListener(myhandler2);
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 1st button
flag_1 = true;
doSomething();
}
};
View.OnClickListener myhandler2 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 2nd button
flag_2 = true;
doSomething();
}
};
}
public void doSomething(){
if(flag_1 && flag_2)
{
//DO SOMETHING
}
}
}
Create two boolean's like button1isClickedand button2isClicked,then set an onClickListener for each Button. When the the Button is clicked set the value of these two boolean's to true, then simply create an if() statement that will chekc to see if both buttons have been clicked, like this:
if(button1isClicked == true && button2isClicked == true){
//display your new page
}

Click a Button Just two times

I'm looking around internet to have the possibility to press a button just two times. I'm implementing the code for a poker game, then the player should press the button one time to show the card and the second time to change it. How can I do it. The only thing I found was to click it one time (that I don't need because it has also to change a card, but just one time). That's what I have for the first button:
backgroundA.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
int randomInt1 = random1.nextInt(Deck.length());
int drawableIDA = Deck.getResourceId(randomInt1, -1);
backgroundA.setBackgroundResource(drawableIDA);
}
});
You need to have a flag that will check for click, if you click it once the flag will be true and if you click it again your statement inside your OnClickListener will get executed.
sample:
boolean flag = false;
boolean flag2 = false;
backgroundA.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
if(!flag){ flag = true }
else
{
if(flag2) { flag = false; }
else
{
int randomInt1 = random1.nextInt(Deck.length());
int drawableIDA = Deck.getResourceId(randomInt1, -1);
backgroundA.setBackgroundResource(drawableIDA);
flag2 = true;
}
}
}
});

Android Save Spinner Selection

I have two activities. In the second activity I have a spinner. what I would like to happen is after the user selects an item from the spinner it will save via actionbar press and on back press which will load the previous activity. Based on my research my activity is supposed to look something like the following below but it's not working what am I doing wrong??
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
getActionBar().setDisplayHomeAsUpEnabled(true);
spin = (Spinner)findViewById(R.id.editspin);
Intent i = this.getIntent();
note = new ArgueItem();
note.setKey(i.getStringExtra("key"));
note.setText(i.getStringExtra("text"));
EditText et = (EditText)findViewById(R.id.argueEdit);
et.setText(note.getText());
et.setSelection(note.getText().length());
}private boolean saveState() {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor prefEditor = prefs.edit();
int daddy = spin.getSelectedItemPosition();
prefEditor.putInt("savedValue",daddy);
prefEditor.commit();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return false;
}
if (item.getItemId() == android.R.id.home) {
saveAndFinish();
}
return false;
}
#Override
public void onBackPressed() {
EditText et = (EditText)findViewById(R.id.argueEdit);
String argueText = et.getText().toString();
if(argueText.equals("")){
Toast.makeText(this, "Please Enter A New ", Toast.LENGTH_SHORT).show();
return;
}else{
saveAndFinish();
}
In your second activity, you have to override the onPause() and. Inside it write the saving process.
protected void onPause(){
super.onPause();
//Include the code which, save the data.
}
You should use a FragmentActivity and add/remove fragments within the same activity.
check these resources:
http://developer.android.com/guide/components/fragments.html
http://www.vogella.com/articles/AndroidFragments/article.html
This is how i'm initializing my spinner which is in the ActionBar. I'm not adding it as a custom view, but I'm using the drop down menu feature.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, new ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
//save in preferences
PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit().
putInt(SELECTED_DIARY_PREF, itemPosition).commit();
return true;
}
});
int selPosition = PreferenceManager.getDefaultSharedPreferences(this).getInt(SELECTED_DIARY_PREF, 0);
actionBar.setSelectedNavigationItem(selPosition);
What this code does is: saving the preference when an item of the menu is clicked, and restoring that preference when the activity is launched. Hope it helps.

Android : Shared preferences inside tabhost not working

I have a tabhost with three activities and I want to save the pressed state of the buttons of each activity
So now How can I save the pressed state of each button in all three child activities so that when I move from one activity to the other the button pressed state will be reflected on moving back. first activity -> all 4 buttons pressed -> go to 2nd activity -> come back to first activity -> all buttons in first activity should be in pressed state
When I go to second child tab and come to the first child tab the change(The buttons which I pressed are not in pressed state) is not reflecting
Help is always appreciated , Thanks
this is my code in first tabhost child activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
seatdirnbtn.setOnClickListener(listner1);
seatdirnbtn1.setOnClickListener(listner2);
seatdirnbtn.setPressed(true);
seatdirnbtn1.setPressed(true);
this.LoadPreferences();
}
private void SavePreferences() {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("sharedPreferences",MODE_WORLD_READABLE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", seatdirnbtn.isEnabled());
editor.putBoolean("state1", seatdirnbtn1.isEnabled());
editor.commit();
}
private void LoadPreferences() {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("sharedPreferences",MODE_WORLD_READABLE);
Boolean state = sharedPreferences.getBoolean("state", false);
Boolean state1 = sharedPreferences.getBoolean("state1", false);
seatdirnbtn.setPressed(state);
seatdirnbtn1.setPressed(state1);
}
#Override
protected void onStart() {
super.onStart();
LoadPreferences();
}
#Override
protected void onPause() {
SavePreferences();
super.onPause();
}
public static boolean isclick = false;
private View.OnClickListener listner1 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn.setBackgroundResource(R.drawable.icon4hlt);
} else {
seatdirnbtn.setBackgroundResource(R.drawable.icon4);
}
isclick = !isclick;
}
};
private View.OnClickListener listner2 = new View.OnClickListener() {
public void onClick(View v) {
if (isclick) {
seatdirnbtn1.setBackgroundResource(R.drawable.icon2hlt);
} else {
seatdirnbtn1.setBackgroundResource(R.drawable.icon2);
}
isclick = !isclick;
}
};
probably you should override onResume() method in which you should set buttons states. this method is called after onCreate() and even the activity is already created. If you have activities in tabHost they are not created each time you switch between tabs so onCreate() method will be called only once but onResume() every time you switch to tab with particular activity.
your code which is loading preferences is in onStart() method. Look here on activity lifecycle. You can see that this method is called only if your activity was stopped before but will never called if it was just paused.
EDIT:
if you have just 2 states like in your code from question it could be better to use ToggleButton which also generally have 2 states. You can style it to have different backgrounds for each state. This tutorial could be helpfull.
Than you will have a little bit different Listener:
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(checked) {
//do sth if it's checked
} else {
//do sth if it's not checked;
}
}
});
to change states for them programatically:
toggleButton.setChecked(true); //or false
so finally you can save this state to SharedPreferences:
editor.putBoolean("toggleButton1",toggleButton.isChecked());
and when you will need this state:
boolean isChecked = sharedPreferences.getBoolean("toggleButton1",false);
toggleButton.setChecked(isChecked);
selector will take care of switching button backgrounds for each state.

Categories

Resources