Android Java Dice roll app not changing dinamycaly - java

This is my MainActivity. I want when I hit "roll" button dices to "roll" - change until my cycle finish and I want to see that change. But when I run the code and hit the button I see only the end result. Tried increasing the delay of "TimeUnit", but it only slows down my app, I don't see dices "rolling". Where am I wrong and is my code in the wright direction, or am I missing something important? I am still learning Android coding :)
package com.example.rado.diceroller;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButtonListenerMethod();
}
public void myButtonListenerMethod() {
Button button = (Button) findViewById(R.id.rollButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < 3; i++) {
try {
Random rand = new Random();
int rollResult = rand.nextInt(6) + 1;
TextView diceResult = (TextView) findViewById(R.id.rollResult);
diceResult.setText(Integer.toString(rollResult));
ImageView img = (ImageView) findViewById(R.id.diceImage);
TimeUnit.MILLISECONDS.sleep(10);
switch (rollResult) {
case 1:
img.setImageResource(R.drawable.dice1);
break;
case 2:
img.setImageResource(R.drawable.dice2);
break;
case 3:
img.setImageResource(R.drawable.dice3);
break;
case 4:
img.setImageResource(R.drawable.dice4);
break;
case 5:
img.setImageResource(R.drawable.dice5);
break;
case 6:
img.setImageResource(R.drawable.dice6);
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}

Your problem is that Android renders view changes after execution finish. So you can wait as many time as you want with TimeUnit.MILLISECONDS.sleep, the only result you will get will be that Android freezes himself for a bit, then restart the for loop. But he starts to render only when the execution is finished and he can say that he isn't wasting time and cpu to render something that the user will never see.
So you can't accomplish your goal in this way. You could try something like this:
package com.firegloves.test;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private int rolledTimes = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButtonListenerMethod();
}
public void myButtonListenerMethod() {
Button button = (Button) findViewById(R.id.rollButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setTimeout();
}
});
}
private void setTimeout() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (rolledTimes < 6) {
// roll your dice
rollDice();
// set timeout again
setTimeout();
} else {
rolledTimes = 0;
}
}
}, 100);
}
private void rollDice() {
rolledTimes++;
Random rand = new Random();
int rollResult = rand.nextInt(6) + 1;
TextView diceResult = (TextView) findViewById(R.id.rollResult);
diceResult.setText(Integer.toString(rollResult));
ImageView img = (ImageView) findViewById(R.id.diceImage);
switch (rollResult) {
case 1:
img.setImageResource(R.drawable.dice1);
break;
case 2:
img.setImageResource(R.drawable.dice2);
break;
case 3:
img.setImageResource(R.drawable.dice3);
break;
case 4:
img.setImageResource(R.drawable.dice4);
break;
case 5:
img.setImageResource(R.drawable.dice5);
break;
case 6:
img.setImageResource(R.drawable.dice6);
break;
}
}
}

Related

Playing random sound when ImageButton is clicked on Android

I'm new in android and I'm trying to play random sound when ImageButton is clicked.
I'm still getting the same audio when I press the button. It should play different sounds every time the button is pressed. Also I would like to add a stop button later.
Here is my code:
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import java.util.Random;
public
class MainActivity extends AppCompatActivity {
MediaPlayer mp;
ImageButton soundbutton;
int[] sounds = {R.raw.audi, R.raw.berlin, R.raw.bratanki, R.raw.budzik, R.raw.cztery, R.raw.drzyz, R.raw.dziewczyny, R.raw.emeryt, R.raw.enter, R.raw.faza};
Random r = new Random();
int rndm = r.nextInt();
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
//media player
soundbutton = (ImageButton)this.findViewById(R.id.playButton);
mp = MediaPlayer.create(getApplicationContext(), sounds[rndm]);
soundbutton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
rndm = r.nextInt();
mp = MediaPlayer.create(getApplicationContext(), sounds[rndm]);
}
mp.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Thank you for your help.
You need to give a maximum to your Random. You have 10 sounds so you want a number between 0-9.
rndm = r.nextInt(10);
This will give you a number between 0-9.

implements View.OnClickListener on MainActivity doesn't work

Still in my learning phase and either I misunderstand the implements keyword. Am at the chapter where the app's MainActivity is supposed to handle all click related functions.
I don't know if it's the book missing something, or I misread something in the book. But when I debug the app I never get the OnClick call. Otherwise the app runs with no errors.
While I already know how to assign a new button listener am stuck on this chapter and would love to be able to move on.
Here's the entire code, it's very short.
Would appreciate knowing what I am missing here.
Thank you
package ted.com.eventhandling;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class MainActivity2 extends AppCompatActivity
implements View.OnClickListener
{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onClick(View view)
{
switch(view.getId())
{
case R.id.button1:
show("Button One");
break;
case R.id.button2:
show("Button Two");
break;
case R.id.button3:
show("Button Three");
break;
default:
show("Oh shit");
break;
}
}
void show(String message)
{
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
Log.i(getClass().getName(), message);
}
}
Use the below code,
package ted.com.eventhandling;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class MainActivity2 extends AppCompatActivity
implements View.OnClickListener
{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
}
#Override
public void onClick(View view)
{
switch(view.getId())
{
case R.id.button1:
show("Button One");
break;
case R.id.button2:
show("Button Two");
break;
case R.id.button3:
show("Button Three");
break;
default:
show("Oh shit");
break;
}
}
void show(String message)
{
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
Log.i(getClass().getName(), message);
}
}
You implemented the onClick but forgot to give clickListeners for your buttons, so none of buttons were not linked.

Error: This class should provide a default constructor

I tried to generate a signatured APK but then this error appears:
Error:Error: This class should provide a default constructor (a public
constructor with no arguments)
(com.penta.games.mrpolitik.SpendenDialog) [Instantiatable]
This is my Dialog file
package com.penta.games.mrpolitik;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
public class SpendenDialog extends Dialog implements
android.view.View.OnClickListener {
private Activity c;
private Button yes, no;
public SpendenDialog(Activity a) {
super(a);
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.spenden_dialog);
yes = (Button) findViewById(R.id.btn_yes);
no = (Button) findViewById(R.id.btn_no);
yes.setOnClickListener(this);
no.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
Uri uri = Uri.parse("https://patreon.com/user?u=5716519&utm_medium=social&utm_source=twitter&utm_campaign=creatorshare2");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
c.startActivity(intent);
break;
}
switch (v.getId()) {
case R.id.btn_no:
break;
}
dismiss();
}
}
How can I solve this error?
How can I solve this error?
Step #1: Delete your constructor
Step #2: Delete your c field
Step #3: Replace all former references to c with getContext()

How to set image resource in Android?

I am writing code for a poker game on eclipse and I am stuck on how to make the card clicked in the cardHand area show up in the playedCards area and have it removed from the deck I am drawing it from. Here's the code:
package com.viktorengineering.poker254;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import java.util.Random;
public class Poker extends Activity {
private ImageView mViewDeck;
private ImageView mViewHand;
private ImageView mViewPlayedCards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getWindow().setBackgroundDrawableResource(R.drawable.green_back);
mViewDeck = (ImageView) findViewById(R.id.deckImage);
mViewDeck.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
int[] imagesArray = {R.drawable.clubs_ace, R.drawable.hearts_seven, R.drawable.diamonds_five,
R.drawable.clubs_three, R.drawable.hearts_eight, R.drawable.spades_six};
Random random = new Random();
mViewHand.setImageResource(imagesArray[new Random().nextInt(6)]);
}
});
mViewHand = (ImageView) findViewById(R.id.cardHand);
mViewHand.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mViewPlayedCards.setImageResource(0);
mViewHand.setImageResource(0);
}
});
mViewPlayedCards = (ImageView) findViewById(R.id.playedCards);
}
}
Your Image in Drawable Folder means use bellow code
mViewPlayedCards.setImageResource(R.drawable.icon);
mViewHand.setImageResource(R.drawable.icon_home);

why does my code crash

So I am running a tutorial app, and it all works except when I try to run the bellow class, however I don't get errors in the code so I was wondering if anyone could help if there is maybe something wrong with the code.
Also on a side not when programming for example you type say: android: in the xml or something. in java how come I don't get the drop down menu with all the options of what can go after?
code:
package com.example.learn.tam;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;
public class textplay extends Activity implements View.OnClickListener{
Button chkCommand;
ToggleButton passToggle;
EditText input;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
holder();
passToggle.setOnClickListener(this);
chkCommand.setOnClickListener(this);
}
private void holder() {
Button chkCommand = (Button) findViewById(R.id.bResults);
passToggle = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.bResults:
String check = input.getText().toString();
display.setText(check);
if(check.contentEquals("left")){
display.setGravity(Gravity.LEFT);
}
else if(check.contentEquals("center")) {
display.setGravity(Gravity.CENTER);
}
else if(check.contentEquals("right")){
display.setGravity(Gravity.RIGHT);
}
else if(check.contentEquals("blue")){
display.setTextColor(Color.BLUE);
}
else if(check.contentEquals("WTF")){
Random crazy = new Random();
display.setText("WTF!!!!");
display.setTextSize(crazy.nextInt(75));
display.setTextColor(Color.rgb(crazy.nextInt(265),crazy.nextInt(265),crazy.nextInt(265)));
switch(crazy.nextInt(3)){
case 0:
display.setGravity(Gravity.LEFT);
break;
case 1:
display.setGravity(Gravity.CENTER);
break;
case 2:
display.setGravity(Gravity.RIGHT);
break;
}
}
else{
display.setText("Invalid");
display.setGravity(Gravity.CENTER);
display.setTextColor(Color.WHITE);
}
break;
case R.id.tbPassword:
if (passToggle.isChecked() == true){
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}else{
input.setInputType(InputType.TYPE_CLASS_TEXT);
}
break;
}
}
}
Change:
private void holder() {
Button chkCommand = (Button) findViewById(R.id.bResults);
passToggle = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
To
private void holder() {
chkCommand = (Button) findViewById(R.id.bResults);
passToggle = (ToggleButton) findViewById(R.id.tbPassword);
input = (EditText) findViewById(R.id.etCommands);
display = (TextView) findViewById(R.id.tvResults);
}
By declaring a new variable with the same name, you were hiding the class field. Due to this, the class level chkCommand remained null, and gave you an exception when you tried to use chkCommand.setOnClickListener(this);.

Categories