How to use accelerometer to press a button in android? - java

I am trying to use accelerometer to press a button in android studio for my dice app. Does anyone know how to hook it up to a button, so that when I shake my phone the dice will roll? I've tried to use SensorEventListener but couldn't get it to work. Thanks for any feedback/suggestion.
PS. I'm a noob.
Here is my java code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button rollButton;
rollButton = findViewById(R.id.rollButton);
final ImageView leftDice = findViewById(R.id.diceLeft);
final ImageView rightDice = findViewById(R.id.diceRight);
final ImageView topDice = findViewById(R.id.diceTop);
final int [] diceArray = {
R.drawable.perspective_dice_one,
R.drawable.perspective_dice_two,
R.drawable.perspective_dice_three,
R.drawable.perspective_dice_four,
R.drawable.perspective_dice_five,
R.drawable.perspective_dice_six,
};
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Dice", "You pressed the button!");
Random randomNumberGenerator = new Random();
int number = randomNumberGenerator.nextInt(6);
Log.d("Dice", "The random number is: " + number);
leftDice.setImageResource(diceArray[number]);
number = randomNumberGenerator.nextInt(6);
rightDice.setImageResource(diceArray[number]);
number = randomNumberGenerator.nextInt(6);
topDice.setImageResource(diceArray[number]);
}
});
}
}

Related

I made an app in which if you click a button an audio will play and if you click twice it will stop but the stop function is working only once

Hi I am new to coding and I am making an app in which if you click a button an audio will play and if you double click the button the audio will stop. But the stop function is only working once. How can I solve it. Here's the Code.
public class MainActivity extends
AppCompatActivity {
private Button rrjk_btn,
gdsph_btn, aspamm, stop_btn;
int counter = 0;
#Override
protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mediaPlayer1 = MediaPlayer.create(this, R.raw.radhasoami_rakshak_jeev_ke);
rrjk_btn = findViewById(R.id.rrjk_btn);
rrjk_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter == 2)
{
mediaPlayer1.pause();
}
mediaPlayer1.start();
counter++;
}
});
//
MediaPlayer mediaPlayer2 = MediaPlayer.create(MainActivity.this, R.raw.guru_dhara_sheesh_par_haath);
gdsph_btn = findViewById(R.id.gdsph_btn);
gdsph_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer2.start();
}
});
//
aspamm = findViewById(R.id.gdsph_btn);
MediaPlayer mediaPlayer3 = MediaPlayer.create(MainActivity.this, R.raw.ae_satguru_pita_aur_malik_mere);
aspamm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer3.start();
}
});
}
}
Your counter int is always increasing so it will be equal to 2 once.
Check this code:
if (counter == 2){
mediaPlayer1.pause();
counter = 0;
}
mediaPlayer1.start();
counter++;
Anyway, this code doesn't make any sense if you want to know if the user is double clicking the button. Check this:
Implement double click for button in Android

Multiple random number results

Currently working in Android Studio and running into a little trouble. Trying to get my rollScore button to roll over and over. At this point it "rolls" once and stops. I've tried a for loop and while loop and unable to get it to allow multiple "rolls".
public class GameScreen extends AppCompatActivity {
private Button rollButton; // Roll button being declared as a variable
private TextView rollScore; // Text view being declared as a variable
private TextView totalSCore; //
private int mCounter = 0;
private int totalRuns = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Random randomGenerator = new Random();
final int randomInt = randomGenerator.nextInt(7) + 1;
rollButton = (Button) findViewById(R.id.rollButton);
rollScore = (TextView) findViewById(R.id.rollScore);
totalSCore = (TextView) findViewById(R.id.totalScore);
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollScore.setText(Integer.toString(randomInt));
mCounter++;
}
});
}
}
You have to generate a new random number on each click on your button.
Like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_screen);
Random randomGenerator = new Random();
int randomInt;
rollButton = (Button) findViewById(R.id.rollButton);
rollScore = (TextView) findViewById(R.id.rollScore);
totalSCore = (TextView) findViewById(R.id.totalScore);
rollButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
randomInt = randomGenerator.nextInt(7) + 1;
rollScore.setText(Integer.toString(randomInt));
mCounter++;
}
});
}
You need to generate a new random number after every roll e.g.
rollScore.setText(Integer.toString(randomGenerator.nextInt(7) + 1));

Why the button added dynamically does not receive the input?

I was developing an application that It is a simple game of cards and I added a button, in a dynamic way at the view, which represents a card of the game, but this button doesn't receive any input when It is pressed.
The question is: Why the button does not receive any input?
I've already tried to use the Log to print the message but nothing is printed.
public class MainActivity extends AppCompatActivity {
private Banco banco;
private Giocatore giocatore1;
private Giocatore giocatore2;
private Giocatore giocatoreAttuale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
giocatore1 = new GiocatoreUmano();
giocatore2 = new GiocatoreUmano();
banco = new Banco(giocatore1,giocatore2);
giocatoreAttuale=giocatore1;
DaiCarteAiGiocatori();
DaiCarteAlPlayerOne();
}
private void DaiCarteAlPlayerOne(){
Button primaCarta = new Button(this); //BUTTON OF THE CARD
primaCarta.setText(giocatore1.getCartaByIndex(0).getSeme().toString()+":"+giocatore1.getCartaByIndex(0).getValore());
ConstraintLayout layout = findViewById(R.id.baseLayout);
layout.addView(primaCarta);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.move_cards); // THE ANIMATION
primaCarta.startAnimation(animation);
//when the button is pressed the log should print the message of the card
primaCarta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
banco.giocaCarte(giocatore1,giocatore1.getCartaByIndex(0));
Log.i("CARTA","Carta Premuta");
}
});
}
private void DaiCarteAiGiocatori(){
banco.pescaCarte();
}
}
Thanks for the help.
see my changes in three places commented by //!!!
public class MainActivity extends AppCompatActivity implements View.OnClickListener { //!!!
private Banco banco;
private Giocatore giocatore1;
private Giocatore giocatore2;
private Giocatore giocatoreAttuale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
giocatore1 = new GiocatoreUmano();
giocatore2 = new GiocatoreUmano();
banco = new Banco(giocatore1,giocatore2);
giocatoreAttuale=giocatore1;
DaiCarteAiGiocatori();
DaiCarteAlPlayerOne();
}
private void DaiCarteAlPlayerOne(){
Button primaCarta = new Button(this); //BUTTON OF THE CARD
primaCarta.setOnClickListener(MainActivity.this); //!!!
primaCarta.setText(giocatore1.getCartaByIndex(0).getSeme().toString()+":"+giocatore1.getCartaByIndex(0).getValore());
ConstraintLayout layout = findViewById(R.id.baseLayout);
layout.addView(primaCarta);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.move_cards); // THE ANIMATION
primaCarta.startAnimation(animation);
}
//!!!
#Override
public void onClick(View v) {
banco.giocaCarte(giocatore1,giocatore1.getCartaByIndex(0));
Log.i("CARTA","Carta Premuta");
}
private void DaiCarteAiGiocatori(){
banco.pescaCarte();
}

Coin flip app mistake in code (Java)

I have tried to make this app where the coin flips on the click of the button. Everything seems to be right but when I run it on my Android, It doesn't show the picture from Imageview and it crashes after a few button clicks.
Can someone see what is wrong in this code?
I have already checked are the images in right location, and their names.
public class MainActivity extends AppCompatActivity {
Button bt1;
ImageView nov;
int strana;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button) findViewById(R.id.bt1);
nov = (ImageView) findViewById(R.id.novcic);
r = new Random();
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
strana = r.nextInt(2);
if (strana == 0) {
nov.setImageResource(R.drawable.pismo);
Toast.makeText(MainActivity.this, "Pismo!", Toast.LENGTH_SHORT).show();
} else if (strana == 1) {
nov.setImageResource(R.drawable.glava);
Toast.makeText(MainActivity.this, "Glava!", Toast.LENGTH_SHORT).show();
}
}
});
}
}

Android:How to set listener on multiple image buttons?

First of all, I'm using Andorid and Java only for a week and I'm a total newbie.
I need to know which button user clicked and then compare it with good or bad answer.
Here is the code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
Integer[] flags = {
R.drawable.flag_albania,
R.drawable.flag_andorra,
R.drawable.flag_angola,
R.drawable.flag_avganistan,
};
String[] questions = {
"What is the flag of Albania",
"What is the flag of Andorra",
"What is the flag of Angola",
"What is the flag of Avganistan",
};
TextView tv = (TextView) findViewById(R.id.textView1);
int arraySize = flags.length;
Random rand = new Random();
ImageButton button1 = (ImageButton) findViewById(R.id.imageButton1);
int index = rand.nextInt(arraySize);
int questionIndex1 = index;
button1.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button2 = (ImageButton) findViewById(R.id.imageButton2);
index = rand.nextInt(arraySize);
int questionIndex2 = index;
button2.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button3 = (ImageButton) findViewById(R.id.imageButton3);
index = rand.nextInt(arraySize);
int questionIndex3 = index;
button3.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button4 = (ImageButton) findViewById(R.id.imageButton4);
index = rand.nextInt(arraySize);
int questionIndex4 = index;
button4.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
Integer[] question = {
questionIndex1,
questionIndex2,
questionIndex3,
questionIndex4
};
int questionArraySize = question.length;
int questionArray = rand.nextInt(questionArraySize);
tv.setText(questions[question[questionArray]]);
My idea is to compare questionIndex that is randomly selected to a button id but I really don't know how to implement it. Every help is appreciated.
Use this reduced code
ImageButton button1,button2,button3,button4;
ImageButton imagebuttons[]={ button1,button2,button3,button4};
int ids[]={R.id.imageButton1,R.id.imageButton2,R.id.imageButton3,R.id.imageButton4};
for(final int i=0;i<imagebuttons.length;i++)
{
imagebuttons[i]=(ImageButton) findViewById(ids[i]);
int index=rand.nextInt(arraySize);
imagebuttons[i].setImageResource(flags[index]);
flags[index] = flags[--arraySize];
indexes.put(i,index);
imagebuttons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( questionArray==indexes.get(i))
{
}
}
});
I hope this will help you
Try out this way:
button1.setOnClickListener(onClickListener);
button2.setOnClickListener(onClickListener);
/**
* Common click listener
*/
OnClickListener onClickListener = new OnClickListener()
{
#Override
public void onClick(View p_v)
{
switch (p_v.getId())
{
case R.id.imageButton1:
//Your logic here.
break;
case R.id.imageButton2:
//Your logic here.
break;
}
}
}
Write below code
public class MainActivity extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
/// Your Above Code ///
tv.setText(questions[question[questionArray]]);
Imagebutton1.setOnClickListener(this);
Imagebutton2.setOnClickListener(this);
Imagebutton3.setOnClickListener(this);
Imagebutton4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == Imagebutton1){
// Write Your Code Here
} else if(v == Imagebutton2){
// Write Your Code Here
} else if(v == Imagebutton3){
// Write Your Code Here
} else if(v == Imagebutton4){
// Write Your Code Here
}
}
}
You can do it this way:
First, make your activity implements onClick Listener:
public class MyActivity extends Activity implements View.OnClickListener{
Then set the action listeners to your buttons:
button1.setOnClickListener(this);
button2.setOnClickListener(this);
.....
then in the listener, check the id:
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
break;
case R.id.imageButton2:
break;
....
}
}
You can do the it this way also. You have to use some int variables to keep the tag value of the button. And also you have to create a onClickListner for the button actions. Coding is as follow
public class MyActivity extends Activity{
//Define the Tag values for image buttons.
private static final int TAG_IMAGE_BTN_1 = 0;
private static final int TAG_IMAGE_BTN_2 = 1;
private static final int TAG_IMAGE_BTN_3 = 2;
private static final int TAG_IMAGE_BTN_4 = 3;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initActivity();
}
private void initActivity(){
//Initialize the image buttons via xml or from the code itself.
//Add the onClickListner_BTN_CLICK and the corresponding tag to the image button
imageBtn1.setTag(TAG_IMAGE_BTN_1);
imageBtn1.setOnClickListener(onClickListner_BTN_CLICK);
imageBtn2.setTag(TAG_IMAGE_BTN_2);
imageBtn2.setOnClickListener(onClickListner_BTN_CLICK);
.......................................................
.......................................................
}
OnClickListener onClickListner_BTN_CLICK = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int iTag = (Integer)v.getTag();
switch (iTag) {
case TAG_IMAGE_BTN_1:
break;
case TAG_IMAGE_BTN_2:
break;
case TAG_IMAGE_BTN_3:
break;
case TAG_IMAGE_BTN_4:
break;
}
}
};
}
The advantages of using the tag values for capture the action,
1)If we use R.id....... then we have to change the value in switch case if we change it in the xml file
2)We can use only one onClickListner for every action in an activity.

Categories