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);
Related
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);
This class extends my main Activity.
public class Numbers extends MainActivity{
public ArrayList<ImageView> getNumbers () {
ArrayList<ImageView> numbers = new ArrayList<>();
ImageView one = (ImageView) findViewById(R.id.one);
numbers.add(one);
return numbers;
}
And I've done some digging but can figure out why my variable "one" is coming back null.
My MainActivity has a ContentView set.
This is the content of my onCreate in MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView start = (ImageView) findViewById(R.id.start);
sceneRoot = (ViewGroup) findViewById(R.id.scene_root);
questionView = findViewById(R.id.questionView);
startView = findViewById(R.id.startView);
gameOverView = findViewById(R.id.gameOver);
animSlide = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide);
animSlide.setAnimationListener(this);
animZoom = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_fade);
animZoom.setAnimationListener(this);
set.addTransition(new Fade())
.addTransition(new Slide(Gravity.RIGHT));
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getQuestion();
TransitionManager.beginDelayedTransition(sceneRoot, set);
startView.setVisibility(View.GONE);
questionView.setVisibility(View.VISIBLE);
}
});
}
public void getQuestion (){
time = (TextView) findViewById(R.id.timeBar);
time.startAnimation(animSlide);
}
I don't call getNumbers() until after start has been clicked and the animation has started.
public void onAnimationStart(Animation animation){
if(animation == animSlide) {
final Questions questions = new Questions();
Numbers n = new Numbers();
for (int i = 0; i < n.getNumbers().size(); i++) {
n.getNumbers().get(i).setVisibility(View.GONE);
n.getNumbersTen().get(i).setVisibility(View.GONE);
}
n.getNumbers().get(0).setVisibility(View.VISIBLE);
EDIT:
If anyone was wondering, I got it to work by extending the class as a Fragment instead of my MainActivity. Then I just used the fragment in my xml.
Because you extended an Activity class doesn't mean setContentView gets called for that class also. It will only do so if properly started and you call super.onCreate(bundle) from your own implementation of onCreate within Numbers
Basically, you should never new any Activity. It has no life-cycle, and therefore no content view, so findViewById just won't work.
Numbers n = new Numbers();
You could not extend anything and have a data-only class around your list of images.
public class Numbers {
private List<ImageView> numbers = new ArrayList<ImageView>();
public Numbers() {}
public void addNumber(ImageView v) { numbers.add(v); }
public List<ImageView> getNumbers() { return numbers; }
}
And from MainActivity you can find and add as you want.
Number n = new Numbers();
n.addNumber((ImageView) findViewById(R.id.one));
However, I don't know if that is useful, really...
Maybe a Fragment would serve a better purpose if you want a "sub-view" of your Activity, but it's hard to tell.
Hey everyone :) Ive been scratching my head on this one, and can't seem to find an appropriate answer that works even though I'm sure its a simple issue.
I have a program which generates a random letter text on a group of buttons when another button being pressed.
When I open the application it loads fine and the first time the button is pressed it generates correctly, but after that I can't seem to get it to regenerate random letters.
I can accomplish what I want by adding an Intent, and essentially "refreshing" (not sure of the wording) the main activity but I would like to add a counter for the button clicks, and it resets when the activity does.
{Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
overridePendingTransition(0, 0);
I just cant seem to wrap my mind around how to do it otherwise. It's seems like I need to rerun the java every time the button is clicked. Any suggestions?
Here is some code, I used buttons rather than textview because I a)wanted to set an easy background b)may make them clickable later. Thanks so much in advance!
public class MainActivity extends Activity
{
Button spin;
Button reel1,reel2,reel3,reel4;
private String rnd,rnd2,rnd3,rnd4;
int count1=50;
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();}
private static String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}
private static String rndm2[] = {"A","B","C","D"};
{rnd2 = rndm2[(int) (Math.random() * rndm2.length)];}
private static String rndm3[] = {"A","B","C","D"};
{rnd3 = rndm3[(int) (Math.random() * rndm3.length)];}
private static String rndm4[] = {"A","B","C","D"};
{rnd4 = rndm4[(int) (Math.random() * rndm4.length)];}
public void perform_action(View v){}
public void addListenerOnButton() {
spin = (Button) findViewById(R.id.spin);
spin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
{Toast.makeText(getApplicationContext(),"button pressed", Toast.LENGTH_SHORT).show();}
{Button tv = (Button) findViewById(R.id.reel1);
tv.setText(String.valueOf(rnd));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel2);
tv.setText(String.valueOf(rnd2));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel3);
tv.setText(String.valueOf(rnd3));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel4);
tv.setText(String.valueOf(rnd4));
tv.setTextColor(Color.parseColor("#000000"));
I figured it out!!! Whoot. But I can't upvote myself for a correct answer.
public class MainActivity extends Activity
{
Button spin;
Button reel1,reel2,reel3,reel4;
private String rnd,rnd2,rnd3,rnd4;
int count1=50;
#Override
protected void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();}
public void perform_action(View v){}
public void addListenerOnButton() {
spin = (Button) findViewById(R.id.spin);
spin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String rndm[] = {"A","B","C","D"};
{rnd = rndm[(int) (Math.random() * rndm.length)];}
String rndm2[] = {"A","B","C","D"};
{rnd2 = rndm2[(int) (Math.random() * rndm2.length)];}
String rndm3[] = {"A","B","C","D"};
{rnd3 = rndm3[(int) (Math.random() * rndm3.length)];}
String rndm4[] = {"A","B","C","D"};
{rnd4 = rndm4[(int) (Math.random() * rndm4.length)];}
{Toast.makeText(getApplicationContext(),"button pressed", Toast.LENGTH_SHORT).show();}
{Button tv = (Button) findViewById(R.id.reel1);
tv.setText(String.valueOf(rnd));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel2);
tv.setText(String.valueOf(rnd2));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel3);
tv.setText(String.valueOf(rnd3));
tv.setTextColor(Color.parseColor("#000000"));}
{Button tv = (Button) findViewById(R.id.reel4);
tv.setText(String.valueOf(rnd4));
tv.setTextColor(Color.parseColor("#000000"));
I moved my random Strings into my Onclick event and removed the private and static parts. Then whala! Things work like a charm!
I have just started Android Studio and am also a little new to java, so please excuse the inefficient code.
Anyway, when I click on the button on the main activity on my app to take the user to the activity that I want to display the images, my app stops working and it throws an OutOfMemoryError.
Here is MainActivty.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button presidentQuizButton = (Button) findViewById(R.id.presidentQuizButton);
Button reviewPresidentsButton = (Button) findViewById(R.id.reviewPresidentsButton);
presidentQuizButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
//when button is clicked, do something
}
});
reviewPresidentsButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
//when button is clicked, do something
startActivity(new Intent(MainActivity.this, presidentReviewActivity.class));
}
});
}
Here is presidentReviewActivity.java:
ImageView imageView;
public int presidentNumber = 0;
private Drawable drawable;
private Drawable [] drawables = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_president_review);
Button menuButton = (Button) findViewById(R.id.menuButton);
Button nextButton = (Button) findViewById(R.id.nextButton);
Button backButton = (Button) findViewById(R.id.backButton);
drawables = new Drawable[]{
getResources().getDrawable(R.drawable.president1),
getResources().getDrawable(R.drawable.president2),
getResources().getDrawable(R.drawable.president3),
getResources().getDrawable(R.drawable.president4),
getResources().getDrawable(R.drawable.president5),
getResources().getDrawable(R.drawable.president6),
getResources().getDrawable(R.drawable.president7),
getResources().getDrawable(R.drawable.president8),
getResources().getDrawable(R.drawable.president9),
getResources().getDrawable(R.drawable.president10),
getResources().getDrawable(R.drawable.president11),
getResources().getDrawable(R.drawable.president12),
getResources().getDrawable(R.drawable.president13),
getResources().getDrawable(R.drawable.president14),
getResources().getDrawable(R.drawable.president15),
getResources().getDrawable(R.drawable.president16),
getResources().getDrawable(R.drawable.president17),
getResources().getDrawable(R.drawable.president18),
getResources().getDrawable(R.drawable.president19),
getResources().getDrawable(R.drawable.president20),
getResources().getDrawable(R.drawable.president21),
getResources().getDrawable(R.drawable.president22),
getResources().getDrawable(R.drawable.president23),
getResources().getDrawable(R.drawable.president24),
getResources().getDrawable(R.drawable.president25),
getResources().getDrawable(R.drawable.president26),
getResources().getDrawable(R.drawable.president27),
getResources().getDrawable(R.drawable.president28),
getResources().getDrawable(R.drawable.president29),
getResources().getDrawable(R.drawable.president30),
getResources().getDrawable(R.drawable.president31),
getResources().getDrawable(R.drawable.president32),
getResources().getDrawable(R.drawable.president33),
getResources().getDrawable(R.drawable.president34),
getResources().getDrawable(R.drawable.president35),
getResources().getDrawable(R.drawable.president36),
getResources().getDrawable(R.drawable.president37),
getResources().getDrawable(R.drawable.president38),
getResources().getDrawable(R.drawable.president39),
getResources().getDrawable(R.drawable.president40),
getResources().getDrawable(R.drawable.president41),
getResources().getDrawable(R.drawable.president42),
getResources().getDrawable(R.drawable.president43),
getResources().getDrawable(R.drawable.president44),
};
menuButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
presidentNumber++;
drawable = drawables[presidentNumber];
imageView.setImageDrawable(drawable);
}
});
And here is most of the error log:
http://imgur.com/xzFfPrq
Instead of store all the drawable content in an array. You can actually just store the resource id in a array.
replace private Drawable [] drawables = null; with private int[] drawableids
replace drawables = new Drawable[]{...} to drawableids = new int[]{...}
replace
drawable = drawables[presidentNumber];
imageView.setImageDrawable(drawable);
to
drawable = getResource().getDrawable(drawableids[presidentNumber]);
imageView.setImageDrawable(drawable);
Try to change as above steps and try again.
The nullpointerexception may be caused by you did not init the drawableids array or you are still using the drawables array instead of drawableids.
you are trying to load large size images directly into memory which causes out of memory exceptions,this issue is discussed in details and a nice solution is given in developers site
How can i display list items on each button click. Lets say there are 4 names in the list. When I press next it displays the first name. Then when you press next it displays the second name and so on.
The only way I think is using the list.get() method. however I dont know how to use the method so that it knows how many values there are in the list and displaying then on each button hit. I think i need to use for method however I hadnt had any luck with it.
public class ZaidimasActivity extends ZaidejaiActivity {
public TextView mPlayer;
public TextView mKlausimas;
public Button mNext;
public Button mBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zaidimas);
/** //get the player list from ZaidejaiActivity
Bundle recdData = getIntent().getExtras();
String myVal = recdData.getString("playerList"); */
Intent zaidejuInfo = getIntent();
Bundle extrasBundle = zaidejuInfo.getExtras();
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
//show the first players name
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.setText(players.get(1));
}
});
mBack = (Button)findViewById(R.id.GryztiMeniuBtn);
mBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent gryztiMeniu = new Intent(ZaidimasActivity.this, ZaidejaiActivity.class);
startActivity(gryztiMeniu);
}
});
}
Here you go, maintain a variable for storing the global array index and increment it every time the button is clicked.
private int count = 0; // Global array index. Make it as class field
final ArrayList<String> players = extrasBundle.getStringArrayList("playerList");
mPlayer = (TextView)findViewById(R.id.ZaidejoVardas);
players.size();
mPlayer.setText(players.get(0));
mNext = (Button)findViewById(R.id.KitasBtn);
mNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
mPlayer.setText(players.get((count)%players.size())); //Incrementing global count and making sure it never exceeds the players list size
}
});