I'm creating a simple whack a mole game using buttons,so far I only managed to get the score of the game when the button is clicked into the count.How do I register a miss count when button is not pressed?
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b2 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
b1 = (Button)findViewById(R.id.button1);
b2 = (Button)findViewById(R.id.button2);
final Handler handler = new Handler();
Runnable runnable = new Runnable() { public void run() {
int x1= r1.nextInt(array.length);
int x2= r2.nextInt(array.length);
b1.setText(array[x1].toString());
b1.setText(array[x1].toString());
int rando = (int)((Math.random()) * 2000);
handler.postDelayed(this, rando); //for interval...
}
};
handler.postDelayed(runnable, 2000);
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(b1)){
//Toast.makeText(Random_textviewActivity.this, "Hello", Toast.LENGTH_SHORT).show();
count++;
score.setText(String.valueOf(count));
b1.setText("");
}
else if (v.equals(b2)) {
count++;
score.setText(String.valueOf(count));
b2.setText("");
}
Those are part of my codes,is there any way to register a count for button not being clicked?
UPDATE
Okay I've got a grasp of the whole idea now,but due to I'm still not very good with android programming yet,I've gotten a lot of error while trying to do what you thought me.Belows are part of the code I've gotten so far:
b1 = (whackamolebutton) findViewById(R.id.button1);
((whackamolebutton) b1).setmoleactive(this);
public class whackamolebutton extends Button{
public whackamolebutton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}//it insist I must cast a method here which I'm not sure why
//from this point onwards I got confused by the auto fix from eclipse.
public void setmoleactive(Random_textviewActivity random_textviewActivity){
if (boolean active){
count++
}
else{
misscount++
}
}
public int getScore(){
return count;
}
}
Any help with the code would be greatly appreciated.Thank you in advance.
I would prefer implementing a custom Button:
public class WhackAMoleButton extends Button {
public void setMoleActive(boolean active) {
...
}
public int getScore() {
...
}
}
The idea is to collect the total score/count from all visible "WhackAMoleButton"s and move the count logic into the WhackAMoleButton-Class. If the button changes from moleActive(true) to moleActive(false) and there was no click in the meantime, you could raise the "not being clicked"-count.
Related
I'm new in Android programming but i know Java.
My question is, how does a timer work in Android? I've read that is better to use a handler.
What I want to do is, you click a button and the timer starts. To the moment when the button is clicked all is clear for me but how to start the timer?
How does a timer work in Android?
You better read Timer documentation, CountDownTimer Documentation and Handler Documentation.
To the moment, when the button is clicked, all is cleared for me; but, how can I start the timer?
If I didn't misunderstand your question, when you say Timer, you refer to CounteDownTimer. So, you should have something like this:
(I've written a sample code. So, you should understand it first, and then, you should apply it to your code.)
Adding the Buttons
btn1 = (Button)findViewById(R.id.bt1);
btn2 = (Button)findViewById(R.id.bt2);
Adding the SetOnClickListener()
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
});
}
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
});
}
My btn1 starts the CountDownTimer, and the second one stops and clears it.
Now, I create an Inner Class with CountDownTimerTest name.
public class CountDownTimerTest extends CountDownTimer {
public CountDownTimerTest(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
text.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
}
Then on my btn1, I put this code (start the CountDownTimer):
countDownTimer.start();
And on my btn2, I put this code (stop/cancel the CountDownTimer):
countDownTimer.cancel();
Now, I hope that you can understand how CountDownTimer works, if your question isn't about CountDownTimer, let me know, and I'll update my answer as soon as possible with your wishes.
EDIT - Only with one Button
To do it with the same Button, you can do this:
Create a Boolean variable as:
Boolean ButtonClicked = false;
And then, modify the code as follows:
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!ButtonClicked)) {
ButtonClicked = true;
countDownTimer.start();
} else {
ButtonClicked = false;
countDownTimer.cancel();
}
});
}
EDIT 2 Get what button is clicked
You can create an int called NumberButtonClicked like this :
int NumberButtonClicked = 0;
Then on every Button you have you'll have to do this (Example) :
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
NumberButtonClicked = 1;
});
}
Then you know that if you have clicked btn1 your variable will be 1.
This is the first time I'm ever dabbling in Android development so please bear with me.
My requirement is this:
I have two buttons on screen, A and B. If the user presses both buttons (order doesn't matter), I need another page to be displayed. Pressing either A or B should do nothing.
Is this possible? If so, how would I achieve this?
Thank you.
This is possible if you take a flag. (boolean)
You should set a flag in your button listeners.
public class Mtest extends Activity {
Button b1;
Button b2;
boolean flag_1 = false;
boolean flag_2 = false;
public void onCreate(Bundle savedInstanceState) {
...
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(myhandler1);
b2.setOnClickListener(myhandler2);
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 1st button
flag_1 = true;
doSomething();
}
};
View.OnClickListener myhandler2 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 2nd button
flag_2 = true;
doSomething();
}
};
}
public void doSomething(){
if(flag_1 && flag_2)
{
//DO SOMETHING
}
}
}
Create two boolean's like button1isClickedand button2isClicked,then set an onClickListener for each Button. When the the Button is clicked set the value of these two boolean's to true, then simply create an if() statement that will chekc to see if both buttons have been clicked, like this:
if(button1isClicked == true && button2isClicked == true){
//display your new page
}
I did this code and want to make a traffic light on and off several times and then stop and choose one of the two lights at random, but the program does the operation, but does not show the changing lights as the operation does
private ImageView redLight;
private ImageView greenLight;
private Button Button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.traffic_lights);
redLight = (ImageView) findViewById(R.id.red_light);
greenLight = (ImageView) findViewById(R.id.green_light);
Button = (Button) findViewById(R.id.start_button);
// Assign click listeners to buttons
Button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v == Button) {
int flag = 0;
for (int i = 0; i <= 100; i++) {
if (flag == 0) {
turnOnRedLight();
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
Log.i("Traffic", "Red");
flag = 1;
} else {
turnOnGreenLight();
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
Log.i("Traffic", "Green");
flag = 0;
}
}
}
}
private void turnOnRedLight() {
redLight.setImageResource(R.drawable.red_on);
}
private void turnOnGreenLight() {
greenLight.setImageResource(R.drawable.green_on);
}
}
You are only sleeping for 100ms so you probably aren't seeing the lights change. Change that to something like 1000 or maybe even 500 and you will probably see the change
Thread.sleep(1000);
Also, a couple notes
Although with this code it may not be a problem, sleeping on the UI Thread usually isn't a good idea. Use a Thread and update UI with runOnUiThread(), use AsyncTask, or Handler.
Don't name your Button "Button". Name it something that isn't an Android keyword like button, btn, startButton, startBtn, or something similar.
When distinguishing between which Button was clicked use the Button id instead of the Object. So you would want to change it to
#Override
public void onClick(View v) {
if (v.getId() == (R.id.start_button)) {
you could also use a switch statement here but not important.
The purpose of my app is: User enters a number and clicks a button. The button uses the input to calculate the Fibonacci sequence with a timer - with each number in the sequence displaying each second to a textView. But when I try to run the timer I get the CalledFromWrongThreadException. I've posted my code below. As you can tell by my log statements I believe I know which line is causing the problem. I think it's because I'm calling a method which is outside my onclicklistener but when I move that other method around I just cause more problems.
I've read a couple other posts and I'm not really sure what the proper way is to print to a text area using my method. Does anyone know how I can make this work?
public class MainActivity extends Activity {
// primary widgets
private EditText editText;
private TextView textView;
private Button button1;
static int seconds = 0;
static Timer timer;
static ArrayList<Integer> fibList = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView) findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
final int delay = 1000;
final int period = 1000;
timer = new Timer();
//Attempt to clear TextView
textView.setText("");
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Clear Textview
String array = " ";
fibList.clear();
textView.setText(array);
//Log.i("ARRAY", "ATTEMPT to CLEAR"+fibList);
String input = editText.getText().toString();
int number = Integer.parseInt(input);
int tmp = 0;
// confirm input
if (number < 20) {
Toast.makeText(getApplicationContext(),
"You entered: " + number, Toast.LENGTH_LONG).show();
for (int i = 0; i <= number; i++) {
fibList.add(fib(i));
// sum even numbers
if (fib(i) % 2 == 0) {
tmp += fib(i);
}
}
} else {
Toast.makeText(getApplicationContext(),
"Number is too Large: " + number, Toast.LENGTH_LONG)
.show();
}
//I believe error occurs in this method
Log.i("TEST", "START TIMER");
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.i("TEST", "RUN TIMER");
int nextIndex = setInterval();
Log.i("TEST", "SET INTERVAL");
if (nextIndex < fibList.size()) {
Log.i("TEST", "TRY TO PRINT");
//It looks like error occurs here when I try to print to textView
textView.setText(fibList.get(nextIndex)+ " ");
Log.i("TEST", "NEXT INDEX"+fibList.get(nextIndex));
Log.i("TEST", "DID PRINT");
}
}
}, delay, period);
Log.i("TEST", "END TIMER");
}
});
}
// run fibonacci sequence
public static int fib(int n) {
if (n < 2) {
return n;
} else {
return fib(n - 1) + fib(n - 2);
}
}
//counts up for every element through the array
public static final int setInterval() {
if (seconds >= fibList.size())
timer.cancel();
return seconds++;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You can use
runOnUiThread(new Runnable(){
public void run(){
textView.setText("aaa");
}
});
Have your timer post a message to a Handler. The handler will, by default, run on the main thread. IT can then change the UI as needed, so just put the body of your timer into that handler.
I just had this problem and came on to StackOverflow to check out a solution. Didn't find anything proper but a little more experimenting with lot many Logs and debugging got me my solution.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText("Your String");
}
});
In my code, the problem was due to me accessing Two TextViews in seperate threads one after another using TextView.post(new Runnable...). I guess this was due to it not being able to access UI Thread (as it was busy with previous thread changes). Setting both TextViews together in UI Thread solved the problem. So posting here for anyone else who might be perplexed by similar problem. Hope it helps.
Hi I am popping up dialog to take comments from user. And returning a value according to that. That "rcomment" is a global variable. And it returns null. This is not working. What am I doing wrong ?
public String getDoNotBoardDialog(final int groupposition)
{
final Dialog dia = new Dialog(this);
dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
dia.setContentView(R.layout.donotboard);
final EditText donotedit = (EditText) dia.findViewById(R.id.donotboardcomment);
donotedit.setText("");
Button button1 = (Button) dia.findViewById(R.id.donotboardbutton);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
r = donotedit.getText().toString();
String boardingComment = getString(R.string.donotboard) + " " + r;
PostCommentForAC(groupposition, boardingComment);
Intent intent = new Intent(getBaseContext(), TestExList.class);
intent.putExtra("EmpID", empid);
startActivity(intent);
rcomment = "true";
dia.cancel();
}
});
Button button2 = (Button) dia.findViewById(R.id.boardbutton);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rcomment = "false";
dia.cancel();
}
});
dia.show();
return rcomment;
}
The getDoNotBoardDialog will initial return rcomment as null. rcomment will only be changed to "true" or "false" when the onClickListeners are fired. They are fired not when getDoNotBoardDialog is run, but after that, whenever the onClickListeners are fired.
Whatever you want to happen when rcomment is changed to "true" or "false" should be placed in the onClick methods. So if you want to check what rcomment is after a user clicks, do it there.
Edit: dont use below code. It will kill your app (ANR).
You would have to wait before you can return something. A quick (but really dirty) solution would be to add some wait/notify mechanism like so: (written blind so might contain some errors).
public String getDoNotBoardDialog(final int groupposition) {
// some Object to wait on
final Object waitOnMe = new Object();
final Dialog dia = new Dialog(this);
dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
dia.setContentView(R.layout.donotboard);
final EditText donotedit = (EditText) dia.findViewById(R.id.donotboardcomment);
donotedit.setText("");
Button button1 = (Button) dia.findViewById(R.id.donotboardbutton);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
r = donotedit.getText().toString();
String boardingComment = getString(R.string.donotboard) + " " + r;
PostCommentForAC(groupposition, boardingComment);
Intent intent = new Intent(getBaseContext(), TestExList.class);
intent.putExtra("EmpID", empid);
startActivity(intent);
rcomment = "true";
dia.cancel();
// stop waiting.
synchronized(waitOnMe) {
waitOnMe.notify();
}
}
});
Button button2 = (Button) dia.findViewById(R.id.boardbutton);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rcomment = "false";
dia.cancel();
// stop waiting.
synchronized(waitOnMe) {
waitOnMe.notify();
}
}
});
dia.show();
// this wait's until someone calls notify
synchronized (waitOnMe) {
try {
waitOnMe.wait();
} catch (InterruptedException e) {}
}
return rcomment;
}
It's problematic though. You could miss the notify() and thus never stop waiting (e.g. when you close the dialog via the "back" button). A much cleaner and safer solution would be to use some Callback mechanism (you call some method in your program from each onClick) to get a value from the dialog.
In you application
the program flows to
return rcomment;
directly after going to
dia.show();
Remember it does not wait for the button to be clicked before it goes to the return statement!!! It goes to return statement directly after the dialog is shown (before the button is clicked)
Try using this string.equals(data) it should find out if the string is the same. Since rcomment is a string. Also like Soham said it will not update only until it is clicked.
I suggest that in the future you should change to Boolean rcomment. Since it only looks like you are doing either true or false status.