How to store users coins on firebase database and retrive them? - java

I am creating an app in which coins/points increases on watching reward video ads and those coins/points should be saved to firebase.
For example: every time on button click the coins value increases to 10 points. Now when I completely destroy the app and open it again, the points value should show the same, not zero
Here is my code till now without database implementation
private TextView mText;
private int coinCount;
mText = (TextView) findViewById(R.id.money);
coinCount = 0;
mText.setText(" " + coinCount);
Button button = (Button) findViewById(R.id.buynow);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (coinCount <= 29) {
//if(coinCount <30) {
new MaterialStyledDialog.Builder(MainActivity.this)
.setTitle("Not Enough Coins")
.setDescription("Watch the Ad To Get 10 coins")
.setIcon(R.drawable.ic_money)
.withIconAnimation(true)
.withDialogAnimation(true)
.withDarkerOverlay(true)
.setHeaderColor(R.color.color)
.setPositiveText("Get some coins")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
mRewardedVideoAd.show();
}
})
.show();
} else {
coinCount = coinCount - 30;
mText.setText(String.valueOf(coinCount));
}
}
});
My queston is how to Save The Coin value to DATABASE and retrieve it ?

Related

How can I transfer integer value from one activity to another?

i'm trying to compile 4 integers from 4 different activities. the first activity is one of the 4 integer. the second activity is where i compile them.. I don't know what's the best way to send a value from different activites. Most of the intent methods i saw uses startActivity but still won't work.
public class QuizSecond extends AppCompatActivity implements View.OnClickListener{
TextView totalQuestionsTextView2;
TextView questionTextView2;
Button ansA2, ansB2, ansC2, ansD2;
Button submitBtn2;
int score= 0;
int totalQuestion2 = QuestionAnswer2.question2.length;
int currentQuestionIndex2 = 0;
String selectedAnswer2 = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_second);
totalQuestionsTextView2 = findViewById(R.id.total_question2);
questionTextView2 = findViewById(R.id.question_preview);
ansA2 = findViewById(R.id.ans_A2);
ansB2 = findViewById(R.id.ans_B2);
ansC2 = findViewById(R.id.ans_C2);
ansD2 = findViewById(R.id.ans_D2);
submitBtn2 = findViewById(R.id.submit_btn2);
ansA2.setOnClickListener(this);
ansB2.setOnClickListener(this);
ansC2.setOnClickListener(this);
ansD2.setOnClickListener(this);
submitBtn2.setOnClickListener(this);
totalQuestionsTextView2.setText("Total questions : "+totalQuestion2);
loadNewQuestion();
}
#Override
public void onClick(View view) {
ansA2.setBackgroundColor(Color.WHITE);
ansB2.setBackgroundColor(Color.WHITE);
ansC2.setBackgroundColor(Color.WHITE);
ansD2.setBackgroundColor(Color.WHITE);
Button clickedButton = (Button) view;
if(clickedButton.getId()==R.id.submit_btn2){
if(selectedAnswer2.equals(QuestionAnswer2.correctAnswers2[currentQuestionIndex2])) {
score++;
}
currentQuestionIndex2++;
loadNewQuestion();
Intent quizIntent = new Intent(QuizSecond.this,ComputeActivity.class);
quizIntent.putExtra("EXTRA_NUMBER",score);
}
else{
//choices button clicked
selectedAnswer2 = clickedButton.getText().toString();
clickedButton.setBackgroundColor(Color.MAGENTA);
}
}
void loadNewQuestion(){
if(currentQuestionIndex2 == totalQuestion2 ){
startActivity(new Intent(QuizSecond.this, ComputeActivity.class));
return;
}
questionTextView2.setText(QuestionAnswer2.question2[currentQuestionIndex2]);
ansA2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][0]);
ansB2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][1]);
ansC2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][2]);
ansD2.setText(QuestionAnswer2.choices2[currentQuestionIndex2][3]);
}
}
second activity:
int number = getIntent().getIntExtra("EXTRA_NUMBER",0); if (number > 3){ Toast.makeText(ComputeActivity.this, "Your Message", Toast.LENGHT_LONG).show();}
Update this
Intent quizIntent = new Intent(QuizSecond.this, ComputeActivity.class);
quizIntent.putExtra("TRANSFER_NUMBER", score);
startActivity(quizIntent);

Plus/Minus button with a counter but counter does not work properly

I have 2 buttons and a TextView to update the counter based on how many times the plus or minus button was pressed.
But, the issue is that: (for example) When I press the "+" button to 4 and goes down to 3 after pressing "-" button. Then, when I try to press "+"(add) button again it jumps up to 5 instead of 4. (i.e. the counter continues adding 1 from when the last time "+" button was pressed.
This is the adapter class where the ImageButtons and TextView listeners are implemented
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
//inflate layout flavor_item.xml
View view = LayoutInflater.from(context).inflate(R.layout.flavor_item, container, false);
//initialize UID views from flavor_item.xml
ImageView imageIv = view.findViewById(R.id.imageIv);
TextView flavorTv = view.findViewById(R.id.flavorTv);
TextView quantityTv = view.findViewById(R.id.quantityTv);
ImageButton minusbutton = (ImageButton) view.findViewById(R.id.minusbutton);
ImageButton plusbutton = (ImageButton) view.findViewById(R.id.plusbutton);
//getting data
DashboardFlavorModel model = modelArrayList.get(position);
String title = model.getTitle();
int image = model.getImage();
String qty = model.getQuantity();
//setting data
imageIv.setImageResource(image);
flavorTv.setText(title);
quantityTv.setText(qty);
//plusbutton listener
plusbutton.setOnClickListener(new View.OnClickListener() {
int count = Integer.parseInt(model.getQuantity());
#Override
public void onClick(View view) {
count++;
model.setQuantity(""+count);
quantityTv.setText(""+count);
}
});
//listener
minusbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = Integer.parseInt(model.getQuantity());
if (i > 0) {
i--;
model.setQuantity(""+i);
quantityTv.setText(""+i);
} else{
Snackbar.make(view,"Cannot have < 0 QTY",Snackbar.LENGTH_SHORT).setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
model.setQuantity("0");
quantityTv.setText(model.getQuantity());
}[![enter image description here][1]][1]
}).show();
}
}
});
(Note***) I tried checking the counter using getter and setter to check whether it worked and it did so I have no idea why when pressing "+" after "-" it wouldn't just +1 from the value after "-" button.
try putting
int count = Integer.parseInt(model.getQuantity());
inside onClick for plusbutton onclicklistener

Takes multiples attempts to close dialog box

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.

how to trigger timer from other class and its TextView and implementation in another xml and class respectively?

I am working on android quiz and want timer on my each question-answer page. I have menu page in my quiz and play button to start game. And i want this timer is triggered when i click on play button. For this i have to create TextView in question XML that represent my menu page. And implementation in QuestionActivity class which represent my first question page. i am also posting WelcomeActivity class although its not play any role in this question.
Play Button Layout
<Button
android:text="Play"
android:id="#+id/playBtn"
android:layout_width="80dip"
android:layout_alignParentRight="true"
android:layout_height="wrap_content"
android:paddingTop="5dip"
android:paddingBottom="5dip"
android:textColor="#ffffff"
android:background="#drawable/start_button" />
Question XML representing TextView for Timer
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/question"
android:layout_centerHorizontal="true"
android:background="#drawable/timer_bttn"
android:onClick="onClick"/>
QuestionActivity where i implemented timer code
public class QuestionActivity extends Activity implements OnClickListener{
private Question currentQ;
private GamePlay currentGame;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
/**
* Configure current game and get question
*/
currentGame = ((CYKApplication)getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
Button nextBtn1 = (Button) findViewById(R.id.answer1);
nextBtn1.setOnClickListener(this);
Button nextBtn2 = (Button) findViewById(R.id.answer2);
nextBtn2.setOnClickListener(this);
Button nextBtn3 = (Button) findViewById(R.id.answer3);
nextBtn3.setOnClickListener(this);
Button nextBtn4 = (Button) findViewById(R.id.answer4);
nextBtn4.setOnClickListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current games
* current question
*/
private void setQuestions() {
//set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion());
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
//set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
int score = currentGame.getScore();
String scr = String.valueOf(score);
TextView score1=(TextView) findViewById(R.id.score);
score1.setText(scr);
}
#Override
public void onClick(View arg0) {
//Log.d("Questions", "Moving to next question");
if(!checkAnswer(arg0)) return;
/**
* check if end of game
*/
if (currentGame.isGameOver()) {
//Log.d("Questions", "End of game! lets add up the scores..");
//Log.d("Questions", "Questions Correct: " + currentGame.getRight());
//Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
}
else {
Intent i = new Intent(this, QuestionActivity.class);
startActivity(i);
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK :
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it
* has then check if its correct and update gamescore
*/
private boolean checkAnswer(View v) {
Button b=(Button) v;
String answer = b.getText().toString();
//Log.d("Questions", "Valid Checkbox selection made - check if correct");
if (currentQ.getAnswer().equalsIgnoreCase(answer))
{
//Log.d("Questions", "Correct Answer!");
currentGame.incrementScore();
}
else {
//Log.d("Questions", "Incorrect Answer!");
currentGame.decrementScore();
}
return true;
}
public void setTimer() {
long finishTime = 5;
CountDownTimer counterTimer = new CountDownTimer(finishTime * 1000, 1000) {
public void onFinish() {
//code to execute when time finished
}
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
txtTimer.setText("" + minutes + ":0" + seconds);
} else {
txtTimer.setText("" + minutes + ":" + seconds);
}
}
};
counterTimer.start();
}
}
WelcomeActivity
public class WelcomeActivity extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
//////////////////////////////////////////////////////////////////////
//////// GAME MENU /////////////////////////////////////////////////
Button playBtn = (Button) findViewById(R.id.playBtn);
playBtn.setOnClickListener(this);
Button settingsBtn = (Button) findViewById(R.id.settingsBtn);
settingsBtn.setOnClickListener(this);
Button rulesBtn = (Button) findViewById(R.id.rulesBtn);
rulesBtn.setOnClickListener(this);
Button exitBtn = (Button) findViewById(R.id.exitBtn);
exitBtn.setOnClickListener(this);
}
/**
* Listener for game menu
*/
#Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.playBtn :
//once logged in, load the main page
//Log.d("LOGIN", "User has started the game");
//Get Question set //
List<Question> questions = getQuestionSetFromDb();
//Initialise Game with retrieved question set ///
GamePlay c = new GamePlay();
c.setQuestions(questions);
c.setNumRounds(getNumQuestions());
((CYKApplication)getApplication()).setCurrentGame(c);
//Start Game Now.. //
i = new Intent(this, QuestionActivity.class);
startActivityForResult(i, Constants.PLAYBUTTON);
break;
case R.id.rulesBtn :
i = new Intent(this, RulesActivity.class);
startActivityForResult(i, Constants.RULESBUTTON);
break;
case R.id.settingsBtn :
i = new Intent(this, SettingsActivity.class);
startActivityForResult(i, Constants.SETTINGSBUTTON);
break;
case R.id.exitBtn :
finish();
break;
}
}
As mentioned by Piyush Gupta, you should call the setTimer() method from onResume in your QuestionActivity.
From the Android Developer Documentation:
(onResume is) called for your activity to start interacting with the user. This is a good place to begin animations, open exclusive-access devices (such as the camera), etc.
In your code you should also make the counterTimer you use in setTimer() a class member, not a local variable; if you don't it will go out of scope once the setTimer() call completes and your access to it will be lost.
So you will need to add the following to QuestionActivity:
public class QuestionActivity extends Activity implements OnClickListener{
// NEW: add counterTimer as a member
private CountDownTimer counterTimer;
// NEW: implement onResume
#Override
public void onResume() {
setTimer();
super.onResume();
}
// CHANGE: setTimer should be changed as follows
public void setTimer() {
long finishTime = 5;
// NOTE: use the member, instead of a local
counterTimer = new CountDownTimer(finishTime * 1000, 1000) {
public void onFinish() {
//code to execute when time finished
}
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
if (seconds < 10) {
txtTimer.setText("" + minutes + ":0" + seconds);
} else {
txtTimer.setText("" + minutes + ":" + seconds);
}
}
};
counterTimer.start();
}
}
This above example uses your code as it is now, but I would advise you to create the timer in onCreate using the class member to store it (ie. everything that is currently in setTimer(), except for the counterTimer.start(); call. Then just use counterTimer.start(); in onResume. And maybe add a counterTimer.cancel() call to onPause so that the timer ends when the activity loses focus.

Text view if statement not working

Can anyone help me work out where I'm going wrong here. On the button click the media player plays one of the mfiles at random and I'm trying to set a textview depending on which file was played. Currently the setText if statements only match the audio playing half the time. Really not sure where I'm going wrong here.
private final int SOUND_CLIPS = 3;
private int mfile[] = new int[SOUND_CLIPS];
private Random rnd = new Random();
MediaPlayer mpButtonOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mfile[0] = R.raw.one;
mfile[1] = R.raw.two;
mfile[2] = R.raw.three;
//Button setup
Button bOne = (Button) findViewById(R.id.button1);
bOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, mfile[rnd.nextInt(SOUND_CLIPS)]);
if (mpButtonOne==null){
//display a Toast message here
return;
}
mpButtonOne.start();
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[0]){
textOne.setText("one");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[1]){
textOne.setText("two");
}
if (mfile[rnd.nextInt(SOUND_CLIPS)] == mfile[2]){
textOne.setText("three");
}
mpButtonOne.setOnCompletionListener(new soundListener1());
{
}
So just to clarify the problem I am having is that the setText only matches the audio occasionally, not on every click. The rest of the time it displays the wrong text for the wrong audio.
You are choosing another random file
mfile[rnd.nextInt(SOUND_CLIPS)]
set that to a variable in onClick() then check against that variable in your if statement
public void onClick(View v) {
int song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);
if (song == mfile[0]){
textOne.setText("one");
}
Edit
To make it a member variable so you can use it anywhere in the class, just declare it outside of a method. Usually do this before onCreate() just so all member variables are in the same place and it makes your code more readable/manageable.
public class SomeClass extends Activity
{
int song;
public void onCreate()
{
// your code
}
then you can just initialize it in your onClick()
public void onClick(View v) {
song = mfile[rnd.nextInt(SOUND_CLIPS)];
final TextView textOne = (TextView)findViewById(R.id.textView1);
mpButtonOne = MediaPlayer.create(MainActivity.this, song);

Categories

Resources