I pass the text through Intent to another activity, through which it is determined what will be shown to the user, dialog window with victory/defeat.
Everything seems to work well, but the problem is that when the phone screen turns off, the actions are repeated. For example, after winning, I received a dialog about what I won, after that, closing the dialog box, turned off the screen while still in the same activity, then turned the screen back on and I get the dialog box again. It seems that I put the code for showing the dialog in onResume, but I didn't.
I tried turning off the re-show of the dialog box in the following ways, which I will show below:
getIntent().removeExtra("TEXT");
boolean
By the way, about boolean, when I created a variable with this code: boolean offScreen = false, then in onCreate I checked in the if condition, and in the action set boolean to true, the dialog box again appeared, it seems that the activity doesn't pay attention to the boolean.
Please tell me how should I.
Just in case, here's the whole code:
String win_lose_select;
String text = getIntent().getStringExtra("TEXT");
win_lose_select = text;
Handler handler4 = new Handler();
handler4.postDelayed(() -> {
if (Objects.equals(win_lose_select, "win")){
youWin_DIALOG();
soundPlay(star_sound);
}
if (Objects.equals(win_lose_select, "lose")){
youWin_DIALOG();
TextView textView = you_win_dia.findViewById(R.id.textWin);
textView.setText("You lost, don't be discouraged, maybe you'll be lucky next time!\nThe defeat is counted.");
soundPlay(lose_sound);
}
if (Objects.equals(win_lose_select, "winNetwork")){
youWin_DIALOG();
TextView textView = you_win_dia.findViewById(R.id.textWin);
textView.setText("You have won, congratulations, your opponent has surrendered!\nVictory counted.");
soundPlay(star_sound);
}
},2000);
public void youWin_DIALOG() {
you_win_dia = new Dialog(this);
you_win_dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
you_win_dia.setContentView(R.layout.you_win);
you_win_dia.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
you_win_dia.setCancelable(true);
getIntent().removeExtra("TEXT");
win_lose_select = "no";
Button go_to_rooms_win = (Button) you_win_dia.findViewById(R.id.go_to_rooms_win);
go_to_rooms_win.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
soundPlay (tuck);
you_win_dia.dismiss();
}
});
you_win_dia.show();
Window window = you_win_dia.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
}
Related
What I need is for the textview to be added onto a linear layout where it will look organised and nice. Whenever the button is clicked again, it should replace the old textview and update it again.
At the moment, the button onclick listener will produce a textview, but I don't like it because it looks messy and unorganised.
I tried doing this:
varlinear.addView(varkebabTotal);
but it caused an error.
I have looked at other examples but they didn't explain how it will work with an onlick listener.
Here's the code for what happens when the button is clicked:
varKebab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = "Kebab Wrap";
if (menu.containsKey(name)) {
kebabquantity = list.get(name);
if (kebabquantity == null) {
kebabquantity = 0;
}
kebabquantity++;
list.put(name, kebabquantity);
//kebab qty calc
double kebabTotal = kebabquantity * menu.get(name);
overallTotal = overallTotal + menu.get(name);
varkebabTotal.setText(String.format("%s %s # £%s = £%.2f", kebabquantity.toString(), name, menu.get(name), kebabTotal));
varTotalPrice.setText(String.format("Total = £%.2f", overallTotal));
varlinear.addView(varkebabTotal); // this line caused an error
}
}
});
Edit:
The error I received is when I tested the app, and when I click the button, the app stops. It shuts itself down due to that one line: varlinear.addView(varkebabTotal);
The variables are as follows:
varkebabTotal = (TextView) findViewById(R.id.kebabTotal);
varTotal = (TextView) findViewById(R.id.TotalPrice);
varlinear = (LinearLayout) findViewById(R.id.myLinear);
one method you can try is to set varkebabTotal.setVisibility(View.GONE); when you initialize the TextView, and then on your onClick event, you can change it to varkebabTotal.setVisibility(View.VISIBLE);
I am trying to display a dialog based on the number of clicks that have occurred. I have two little issues with it which I will explain below:
So I clear the data on my app so that the number of clicks starts on 0. Basically what I am trying to do is that when I access the class below, if the number of clicks = 4, 8 or 12, then output the relevant message associated to them in my if else statements. If it doesn't equal any of those numbers then for every 4 clicks (16, 20, 24 ,28 etc) display the default message of 'You are rewarded with a video.
So starting from fresh on zero clicks, when I navigate to this page I notice for each click (1,2,3,4 etc) it displays the default dialog message which is not what I require. I want it to display the messages for 4, 8, 12 which have their own specific messages and then there after (16, 20, 24, 28 etc) should display the general message.
What I have also noticed is that if I come out of the page by selecting the back button and then access the page again, every time the dialog appears it takes me many taps on the ok button for the dialog to close. Initially before I went back from the page it only took me one tap to close the dialog but when I re-enter the page then it takes many taps and I am not sure why.
How can these 2 issues be fixed?
Code below:
import java.util.Random;
public class Content extends AppCompatActivity {
Button backButton;
Button selectAnotherButton;
TextView clickCountText;
int getClickCountInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(Content.this);
clickCountText = findViewById(R.id.click_count);
clickCountText.setText(Integer.toString(prefManager.getClicks()));
getClickCountInt = Integer.parseInt(clickCountText.getText().toString());
backButton = findViewById(R.id.button_back);
selectAnotherButton = findViewById(R.id.button_select_another);
setContent();
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
if (getClickCountInt == 4){
ShowRewardDialog("You are rewarded with a the yellow smiley face in the homepage");
} else if (getClickCountInt == 8) {
ShowRewardDialog("You are rewarded with a the green smiley face in the homepage");
} else if (getClickCountInt == 12) {
ShowRewardDialog("You are rewarded with a the red smiley face in the homepage");
} else {
for(int i = 0; i <= getClickCountInt; i+=4) {
ShowRewardDialog("You are rewarded with a video\"");
}
}
setContent();
}
});
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void ShowRewardDialog(String message) {
final Dialog dialog = new Dialog(Content.this);
dialog.setContentView(R.layout.custom_dialog);
SpannableString title = new SpannableString("YOU GAINED A REWARD");
title.setSpan(new ForegroundColorSpan(Content.this.getResources().getColor(R.color.purple))
, 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// set the custom dialog components - text, image and button
TextView text = dialog.findViewById(R.id.dialog_text);
dialog.setTitle(title);
text.setText(message);
Button dialogButton = dialog.findViewById(R.id.dialog_button_OK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
UPDATE
Ok to make it easier I will say what is the current problem and how I want it to work.
I have disabled the else statement for now in the Content class where it displays a generic message in the dialog box.
Ok so I have created a class for my Shared Preferences and I can get an instance of it from both the MainActivity class (this is my homepage) and Content class (this is second page).
Lets say the click counts starts on 0 (and I display this as a text) and I am on the homepage. When I select the jokes button from the homepage, I will navigate to the second page and the count starts at 1. If I select 'Select Another' button which is displayed in second page, then the count goes to 2 (as I can see by the text displayed), click again then three and click again it will go to 4 and the dialog box for count 4 is displayed. This works for when I go to 8 and 12 as well.
When I select the 'Back' button to go from second page to front page, I can see the count remains the same as the count displayed in the second page. E.g if count was set to 8 on page 2 and I click back, the homepage displays the count of 8 as well when I view the text.
This seems all well and good. However lets start again from 0. If I click on the jokes button then I am on 1, I select 'Select Another' button twice so the count is on 3 and then click back button. Count is currently on 3 when I view the homepage. If I click on the jokes button again then the count is on 4 which is correct, however the dialog for if count equals to 4 does not appear. However if I click on the 'Select Another' button 3 more times then it will display the dialog for 4. So it seems like the dialog will only appear for 4 if the 'Select Another' button is clicked four in a row, rather than how I want it which is if the total number of clicks count equals 4 then show the dialog.
What will I need to do to fix this?
Below is the code:
SharedPreferencesManager class:
public class SharedPreferencesManager{
private static final String APP_PREFS = "AppPrefsFile";
private static final String NUMBER_OF_CLICKS = "numberOfClicks";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs = context.getApplicationContext().getSharedPreferences(APP_PREFS, MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public int increaseClickCount() {
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
clickCount++;
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, clickCount);
editor.apply();
return clickCount;
}
public int getClicks(){
return sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
}
}
MainActivity class (page 1)
public class MainActivity extends AppCompatActivity {
SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button jokesButton = findViewById(R.id.button_jokes);;
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("jokes");
}
});
TextView clickCountText = findViewById(R.id.click_count);
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
}
private void openContentPage(String v) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intentContentPage.putExtra("keyPage", v);
startActivity(intentContentPage);
}
}
Content class (page 2):
public class Content extends AppCompatActivity {
Button backButton;
Button selectAnotherButton;
TextView clickCountText;
int getClickCountInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(Content.this);
clickCountText = findViewById(R.id.click_count);
clickCountText.setText(Integer.toString(prefManager.getClicks()));
getClickCountInt = Integer.parseInt(clickCountText.getText().toString());
backButton = findViewById(R.id.button_back);
selectAnotherButton = findViewById(R.id.button_select_another);
setContent();
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getClickCountInt++;
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
if (getClickCountInt == 4){
ShowRewardDialog("You are rewarded with a the yellow smiley face in the homepage");
} else if (getClickCountInt == 8) {
ShowRewardDialog("You are rewarded with a the green smiley face in the homepage");
} else if (getClickCountInt == 12) {
ShowRewardDialog("You are rewarded with a the red smiley face in the homepage");
} //else {
//for(int i = 0; i <= getClickCountInt; i+=4) {
//ShowRewardDialog("You are rewarded with a video\"");
//}
//}
}
});
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void ShowRewardDialog(String message) {
final Dialog dialog = new Dialog(Content.this);
dialog.setContentView(R.layout.custom_dialog);
SpannableString title = new SpannableString("YOU GAINED A REWARD");
title.setSpan(new ForegroundColorSpan(Content.this.getResources().getColor(R.color.purple))
, 0, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// set the custom dialog components - text, image and button
TextView text = dialog.findViewById(R.id.dialog_text);
dialog.setTitle(title);
text.setText(message);
Button dialogButton = dialog.findViewById(R.id.dialog_button_OK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
The first problem with your algorithm is that you're not adding the current clicks to your click count.
Inside the onClick of selectAnotherButton.setOnClickListener you should add a getClickCountInt++ (and dont forget to update clickCountText with this new value).
Also, on your onCreate you should get the value for getClickCountInt from SharedPreferences, and then use it to set the value on clickCountText, not the other way around.
This answear shows how to read/store data in SharedPreferences.
// Custom Dialog Box
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this, R.style.Theme_AppCompat_Dialog_Alert);
final View mView = getLayoutInflater().inflate(R.layout.completed, null);
ImageButton imgForm = (ImageButton) mView.findViewById(R.id.RateButton);
mBuilder.setCancelable(false);
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show(); // Dialogbox appears
// Interest Rating
final AlertDialog.Builder nBuilder = new AlertDialog.Builder( MainActivity.this, R.style.Theme_AppCompat_Light_Dialog_Alert);
final View nView = getLayoutInflater().inflate(R.layout.intrst, null);
Save_Intrst = (Button) nView.findViewById(R.id.SaveIntrst);
nBuilder.setCancelable(false);
nBuilder.setView(nView);
final AlertDialog dilog = nBuilder.create();
// LongPress Image Button
imgForm.setOnLongClickListener(new View.OnLongClickListener(){
#Override
public boolean onLongClick(View view){
dialog.dismiss();
dilog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dilog.show(); // Dialogbox appears
return true;
}
});
Save_Intrst.setOnClickListener(new View.OnClickListener(){
String IntrstLvl;
#Override
public void onClick(View v){
RatingBar rBar = (RatingBar)nView.findViewById(R.id.ratingStar);
IntrstLvl = Integer.toString(rBar.getNumStars());
addData(IntrstLvl);
dilog.dismiss();
Log.d(TAG,"Dismissed");
}
});
Whenever I select "save" within the Save_Intrst it saves 5 stars regardless of what I choose. I'm still fairly new to Android development and have been java coding for a bit now.
This is just a snippet of code of the project and I believe it will be enough, it shows my submit button, the submit button will launch a dialog box that will have a secret button in an image (ImgForm) the image doesn't show but that's not the problem, after long pressing it will launch another dialog that has a 5 Star Rating Bar and a Save button, this is used for rating after the person completes the previous requirements. The rating will always save "5" regardless of what was inserted, even after a reinstall of app onto the device.
getNumStars() will tell you the maximum number of stars shown and will always be 5 as you have defined it. If you want the actual selected rating, you will need getRating(). See this documentation.
You need to use the rBar.getRating()
RatingBar rBar = (RatingBar)nView.findViewById(R.id.ratingStar);
IntrstLvl = Integer.toString(rBar.getRating());
https://developer.android.com/reference/android/widget/RatingBar.html
You are calling getNumStars() which according to the documentation "Returns the number of stars shown." which means the total number of stars a user can select. You should instead be checking getRating() which returns the number of stars currently selected.
https://developer.android.com/reference/android/widget/RatingBar.html#getRating()
I have a piece of code where a function opens a popup window to later return an integer based on what happened inside that window. But when I run it, it directly returns the integer without opening any popup window.
How do I tell that function to wait to return until a user has done a certain action?
Here's the code in case you need it:
public int initPopup(String monsterName, String monsterHP){
final int monsterHPInt = Integer.parseInt(monsterHP);
PopupWindow popup;
TextView popupText;
Button closePopupButton;
final SeekBar monsterHPChanger;
LinearLayout popupLayout;
popupText = new TextView(this);
popupText.setText(monsterName);
monsterHPChanger = new SeekBar(this);
monsterHPChanger.setMax(monsterHPInt);
/** Will only use if necessary
* monsterHPChanger.setProgress(monsterHPChanger.getMax());
*/
popupLayout = new LinearLayout(this);
popupLayout.setOrientation(LinearLayout.VERTICAL);
popupLayout.addView(popupText);
popupLayout.addView(monsterHPChanger);
//TODO: Create the layout of the popup and the popup itself
popup = new PopupWindow(popupLayout, LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
popup.setContentView(popupLayout);
//Creating encapsulation class to edit the monsterHP with the value of the SeekBar
final MonsterHP monsterHPObject = new MonsterHP(monsterHPInt, monsterHPChanger.getProgress());
closePopupButton = new Button(this);
closePopupButton.setId(R.id.closePopup);
closePopupButton.setText("Ok");
closePopupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
monsterHPObject.update(monsterHPChanger.getProgress());
}
});
Log.println(1, "Method", "Returns " + monsterHPObject.getHP());
// TODO: reactivate when debug is done return monsterHPObject.getHP();
//Returning 0 for debug reasons
return 0;
}
I'm looking your code and I dont see the call "popup.show()" anywhere. Also, if you want to wait some time to perform an operation you can use the following code.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// your operations (open popup?)
}
}, **your_delay_time**);
Hope it helps you!!
Use a callback interface that you pass to your method.
When the user performs the action, call the appropriate callback method.
i am developing/designing a quiz application in android, on the testActivity i have
a TextView which loads the questions and four answer(alternatives) buttons.
btnAnswer1, btnAnswer2, btnAnswer3, and btnAnswer4.
Problem:When i click on btnAnser1 as my answer, it should remain in selected state, however it should also be possible to unselect(normal state) it if i doubt the answer. and lastly if its selected, and i decide to go for btnAnswer2 whiles btnAnswer1 is selected, immediately i select btnAnswer2, btnAnswer1 should be unselected(normal) whiles btnAnswer2 is selected.
i hope my question is clear and it sounds quiet easy but am still new in android programming so will appreciate the help.
thanks.
optionone = (Button) findViewById(R.id.optionone);
optionone.setTag(1);
optionone.setId(i);
//optionone.setBackgroundColor(Color.parseColor("#F1F1F1"));
optionone.setBackgroundColor(Color.parseColor("#F1F1F1"));
optionone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setSelected(true);
checkAnswer();
final int change = (Integer) v.getTag();
if (change == 1) {
optionone.setBackgroundColor(Color.parseColor("#B2B2B2"));
back.setVisibility(View.VISIBLE);
next.setVisibility(View.VISIBLE);
v.setTag(0);
} else {
optionone.setBackgroundColor(Color.parseColor("#F1F1F1"));
back.setVisibility(View.GONE);
next.setVisibility(View.GONE);
v.setTag(1);
}
}
});
Try to use toggle buttons instead of buttons, or just change background color of buttons when they pressed, not state.