Hi can anyone help me on my small project please, I have been following this Tutorial and I got to the part where I insert 1 Minute into the EditText the Progress Bar works fine 1 Progress per sec but when I put in more than 1 Minute into the EditText the Progress Bar does not work. It does not goes down please help?
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#086A87">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:padding="10dp" >
<EditText
android:id="#+id/edtTimerValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="minutes"
android:inputType="phone" />
<Button
android:id="#+id/btnStartTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Start Timer"
android:background="#drawable/custombuttongreen"
android:textColor="#fff"/>
<Button
android:id="#+id/btnStopTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="2"
android:gravity="center"
android:text="Stop Timer"
android:visibility="gone"
android:background="#drawable/custombuttongreen"
android:textColor="#fff"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical" >
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="350dip"
android:layout_height="350dip"
android:indeterminate="false"
android:progressDrawable="#drawable/circle"
android:background="#drawable/circle_shape"
style="?android:attr/progressBarStyleHorizontal"
android:max="60"
android:progress="0" />
<TextView
android:id="#+id/tvTimeCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="00:00"
android:textColor="#fff"
android:textSize="60dip"/>
</RelativeLayout>
MainActivity.java
package com.tag.countdowntimer;
import com.tag.countdowntimer.R.drawable;
import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
int i=-1;
ProgressBar mProgressBar;
private Button buttonStartTime, buttonStopTime;
private EditText edtTimerValue;
private TextView textViewShowTime; // will show the time
private CountDownTimer countDownTimer; // built in android class
// CountDownTimer
private long totalTimeCountInMilliseconds; // total count down time in
// milliseconds
private long timeBlinkInMilliseconds; // start time of start blinking
private boolean blink; // controls the blinking .. on and off
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonStartTime = (Button) findViewById(R.id.btnStartTime);
buttonStopTime = (Button) findViewById(R.id.btnStopTime);
textViewShowTime = (TextView) findViewById(R.id.tvTimeCount);
edtTimerValue = (EditText) findViewById(R.id.edtTimerValue);
buttonStartTime.setOnClickListener(this);
buttonStopTime.setOnClickListener(this);
mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btnStartTime) {
textViewShowTime.setTextAppearance(getApplicationContext(),
R.style.normalText);
setTimer();
//Hides the Keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edtTimerValue.getWindowToken(), 0);
buttonStopTime.setVisibility(View.VISIBLE);
buttonStartTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.GONE);
edtTimerValue.setText("");
//textViewShowTime.setTextColor(color.white);
//textViewShowTime.getContext();
startTimer();
} else if (v.getId() == R.id.btnStopTime) {
countDownTimer.cancel();
buttonStartTime.setVisibility(View.VISIBLE);
buttonStopTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.VISIBLE);
}
}
private void setTimer() {
int time = 0;
if (!edtTimerValue.getText().toString().equals("")) {
time = Integer.parseInt(edtTimerValue.getText().toString());
} else
Toast.makeText(MainActivity.this, "Please Enter Minutes...",
Toast.LENGTH_LONG).show();
totalTimeCountInMilliseconds = 60 * time * 1000;
timeBlinkInMilliseconds = 30 * 1000;
}
private void startTimer() {
countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
// 500 means, onTick function will be called at every 500
// milliseconds
#Override
public void onTick(long leftTimeInMilliseconds) {
long seconds = leftTimeInMilliseconds / 1000;
//i++;
//Setting the Progress Bar to decrease wih the timer
mProgressBar.setProgress((int) (leftTimeInMilliseconds / 1000));
textViewShowTime.setTextAppearance(getApplicationContext(),
R.style.normalColor);
if (leftTimeInMilliseconds < timeBlinkInMilliseconds) {
textViewShowTime.setTextAppearance(getApplicationContext(),
R.style.blinkText);
// change the style of the textview .. giving a red
// alert style
if (blink) {
textViewShowTime.setVisibility(View.VISIBLE);
// if blink is true, textview will be visible
} else {
textViewShowTime.setVisibility(View.INVISIBLE);
}
blink = !blink; // toggle the value of blink
}
textViewShowTime.setText(String.format("%02d", seconds / 60)
+ ":" + String.format("%02d", seconds % 60));
// format the textview to show the easily readable format
}
#Override
public void onFinish() {
// this function will be called when the timecount is finished
textViewShowTime.setText("Time up!");
textViewShowTime.setVisibility(View.VISIBLE);
buttonStartTime.setVisibility(View.VISIBLE);
buttonStopTime.setVisibility(View.GONE);
edtTimerValue.setVisibility(View.VISIBLE);
}
}.start();
}
}
Normal State of Timer
When I enter 1 Minute
When I Entered 3 Minutes
Progress Bar is not Counting Down
In your main.xml, for ProgressBar you mentioned max value as 60. So the progress bar takes it max value as 60 and your progress bar starts decreasing from 60 seconds onwards.
Instead of that to work your Progress bar properly all times, in your "setTimer()" method write the below line.
mProgressBar.setMax(60*time);
Related
I have 4 different buttons. I want to change the background of the buttons at a fixed time (say 1 sec i.e. one button changes its color for one sec then retains its previous color and then other button does the same and so on) in certain random pattern, and then the user will repeat this pattern. However I am unable to change the background of the buttons randomly. I know that a timer or handler will b used but I have no idea ho to use it. Can anyone post a example program that shows how to change the background of buttons randomly?
here is my xml file:
`
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<TextView
android:id="#+id/levelText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="50dp"
android:textColor="#FFFFFF"
android:text = "" />
<TextView
android:id="#+id/countDnText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textSize="100dp"
android:textStyle="bold"
android:textColor="#FFFFFF"
android:text=""
/>
<Button
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button5"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="79dp" />
<Button
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button6"
android:layout_alignTop="#+id/button5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button7"
android:layout_below="#+id/button5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<Button
android:layout_width="160dp"
android:layout_height="200dp"
android:background="#000000"
android:id="#+id/button8"
android:layout_alignTop="#+id/button7"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
`
here is my Activity:`
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class EasyGameActivity extends AppCompatActivity
{
private int counter;
private TextView text;
private boolean flag = false;
private Button button = null;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy_game);
startGame();
}
public void startGame()
{
counter = 3;
int temp;
final Random rand = new Random();
Handler handler = new Handler();
while(true)
{
BinaryTree binaryTree = new BinaryTree(counter);
for(int i = 0; i<counter; ++i)
{
temp = rand.nextInt(3);
// yellow color button...
if(temp == 0)
{
button = (Button) findViewById(R.id.button5);
button.setBackgroundColor(Color.YELLOW);
}
else if(temp == 1)
{
button = (Button) findViewById(R.id.button6);
button.setBackgroundColor(Color.BLUE);
}
else if(temp == 2)
{
button = (Button) findViewById(R.id.button7);
button.setBackgroundColor(Color.RED);
}
else if(temp == 3)
{
button = (Button) findViewById(R.id.button8);
button.setBackgroundColor(Color.GREEN);
}
//button.setBackgroundColor(Color.BLACK);
}
break;
}
}
}`
You could try something like this:
Button[] changingButtons = new Button[4];
changingButtons[0] = (Button)findViewById(R.id.button1_id);
changingButtons[1] = (Button)findViewById(R.id.button2_id);
changingButtons[2] = (Button)findViewById(R.id.button3_id);
changingButtons[3] = (Button)findViewById(R.id.button4_id);
You can then access the corresponding button in the array and change the background colour using changingButtons[<desired index>].setBackgroundResource(<color resource>)
To retain the previous color, you can use ColorDrawable previousBackground = (ColorDrawable)changingButtons[<desired index>].getBackground();
Then, for the "set time" part, use a timer, and do the colour switching in the TimerTask.
If you wish to use a TimerTask would look something like this inside the method calling it:
timer = new Timer();
timer.schedule(new MyTask(buttonNumber), numMilliseconds);
And then MyTask would be an extension class of TimeTask
class MyTask extends TimerTask
{
private int buttonId;
public MyTask(int buttonId)
{
super();
this.buttonId = buttonId;
}
public void run()
{
//Do your button alterations here
}
}
Here's a sample I made using the above code on Ideone
Hopefully this points you in the right direction!
For more information, check out these: Changing the background color programmatically, Getting the background color, Java Timer documentation
You can use Collections.shuffle(colorList);
List<String> colorList=new ArrayList<>();
colorList.add("#108E44");
colorList.add("#000000ff");
colorList.add("#108E44");
for() {
giveMeButtons(i).setBackgorundColor(Color.parseColor(colorList.get(i)));
}
And you must make other method. It will return random View button.
Posting this on behalf of a friend, I don't have the android SDK to test this so apologies if it's super obvious:
Trying to update a TextView with a timestamp on a new line:
viewText = viewText + "\n"+ String.format("%d:%02d:%02d", minutes, seconds,millis);
But no matter what seems to always end up on the same line.
Code below:
package com.example.polyrhythm;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView showResults, countDown;
long start, stop;
String sResults = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bStart = (Button) findViewById(R.id.startButton);
Button bStop = (Button) findViewById(R.id.rhythmOne);
showResults = (TextView) findViewById(R.id.resultTextView);
// countDown = (TextView) findViewById(R.id.countDownTextView);
showResults.setSingleLine(false);
bStart.setOnClickListener(this);
bStop.setOnClickListener(this);
start = 0;
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.startButton:
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
// countDown.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
// countDown.setVisibility(View.GONE);
start = System.currentTimeMillis();
}
}.start();
break;
case R.id.rhythmOne:
stop = System.currentTimeMillis();
if (start != 0) {
String viewText = "";
long result = stop - start;
int millis = (int) result;
int seconds = (int) result / 1000;
int minutes = seconds / 60;
millis = millis % 100;
seconds = seconds % 60;
viewText = viewText
+ "\n"
+ String.format("%d:%02d:%02d", minutes, seconds,
millis);
showResults.setText(viewText);
}
break;
}
}
}
The layout file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/rhythmOne"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="----------------" />
<Button
android:id="#+id/startButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/rhythmOne"
android:layout_centerHorizontal="true"
android:text="Start" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/startButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result\n"
android:lines="2" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
It can be:
That you only allow one line on the textview.
android:lines="2"
Try leaving a space between \n and the texts.
viewText = viewText + " \n"+ String.format("%d:%02d:%02d", minutes, seconds, millis);
By default a TextView should already have multiple lines.
So I assume that the problem is in your layout file (which you haven't posted).
Try hard-coding the text in XML temporarily and see if the problem occurs there.
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="firstline\nsecondline"
android:textAppearance="?android:attr/textAppearanceMedium" />
IMPLEMENTATION 1 ISSUE
Doubt 1: I tried timer using progress bar. Its like say 5 seconds per question. However, the progress bar does display countdown values. My issue is after time gets over(value reaches 0 ) , I do not go to next question by default ..
IMPLEMENTATION 2 ISSUE
Doubt 2: Also ,how can I set a countdown timer using progress bar which starts at first question and is decreasing values continuously till specified limit.Like say I want all 20 questions in my quiz to be answered in 120 mins.
So progress bar should be 120,119 ....1 .And after reaching 0,I should be automatically redirected to results page.
QuestionActivity.java
package works.really.good;
import java.sql.Date;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import works.really.good.quiz.GamePlay;
import works.really.good.quiz.Question;
import works.really.good.util.Utility;
public class QuestionActivity extends Activity implements OnClickListener{
private Question currentQ;
private GamePlay currentGame;
ProgressBar mProgressBar;
CountDownTimer mCountDownTimer;
TextView tv;
int i=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
currentGame = ((MyApplication)getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
Button nextBtn = (Button) findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(this);
setQuestions();
tv = (TextView) findViewById(R.id.tv_counter);
mProgressBar=(ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setProgress(i);
mCountDownTimer=new CountDownTimer(5000,1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress"+ i+ millisUntilFinished);
i++;
String time = (String) DateFormat.format("ss", new Date(millisUntilFinished));
tv.setText(time);
mProgressBar.setProgress(i);
}
#Override
public void onFinish() {
//Do what you want
i++;
mProgressBar.setProgress(i);
}
};
mCountDownTimer.start();
}
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)));
}
#Override
public void onClick(View arg0) {
/**
* validate a checkbox has been selected
*/
if (!checkAnswer()) return;
/**
* check if end of game
*/
if (currentGame.isGameOver()){
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);
}
private boolean checkAnswer() {
String answer = getSelectedAnswer();
if (answer==null){
return false;
}
else {
if (currentQ.getAnswer().equalsIgnoreCase(answer))
{
currentGame.incrementRightAnswers();
}
else{
currentGame.incrementWrongAnswers();
}
return true;
}
}
private String getSelectedAnswer() {
RadioButton c1 = (RadioButton)findViewById(R.id.answer1);
RadioButton c2 = (RadioButton)findViewById(R.id.answer2);
RadioButton c3 = (RadioButton)findViewById(R.id.answer3);
RadioButton c4 = (RadioButton)findViewById(R.id.answer4);
if (c1.isChecked())
{
if (currentQ.getAnswer().equalsIgnoreCase(c1.getText().toString()))
{
c1.setTextColor(Color.GREEN);
}
else
{
c1.setTextColor(Color.RED);
if (currentQ.getAnswer().equalsIgnoreCase(c2.getText().toString()))
{
c2.setTextColor(Color.GREEN);
}
else if (currentQ.getAnswer().equalsIgnoreCase(c3.getText().toString()))
{
c3.setTextColor(Color.GREEN);
}
else if (currentQ.getAnswer().equalsIgnoreCase(c4.getText().toString()))
{
c4.setTextColor(Color.GREEN);
}
}
return c1.getText().toString();
}
if (c2.isChecked())
{
if(currentQ.getAnswer().equalsIgnoreCase(c2.getText().toString()))
{
c2.setTextColor(Color.GREEN);
}
else
{
c2.setTextColor(Color.RED);
if (currentQ.getAnswer().equalsIgnoreCase(c1.getText().toString()))
{
c1.setTextColor(Color.GREEN);
}
else if (currentQ.getAnswer().equalsIgnoreCase(c3.getText().toString()))
{
c3.setTextColor(Color.GREEN);
}
else if (currentQ.getAnswer().equalsIgnoreCase(c4.getText().toString()))
{
c4.setTextColor(Color.GREEN);
}
}
return c2.getText().toString();
}
if (c3.isChecked())
{
if(currentQ.getAnswer().equalsIgnoreCase(c3.getText().toString()))
{
c3.setTextColor(Color.GREEN);
}
else
{
c3.setTextColor(Color.RED);
if (currentQ.getAnswer().equalsIgnoreCase(c1.getText().toString()))
{
c1.setTextColor(Color.GREEN);
}
else if (currentQ.getAnswer().equalsIgnoreCase(c2.getText().toString()))
{
c2.setTextColor(Color.GREEN);
}
else if (currentQ.getAnswer().equalsIgnoreCase(c4.getText().toString()))
{
c4.setTextColor(Color.GREEN);
}
}
return c3.getText().toString();
}
if (c4.isChecked())
{
if(currentQ.getAnswer().equalsIgnoreCase(c4.getText().toString()))
{
c4.setTextColor(Color.GREEN);
}
else
{
c4.setTextColor(Color.RED);
if (currentQ.getAnswer().equalsIgnoreCase(c1.getText().toString()))
{
c1.setTextColor(Color.GREEN);
}
else if (currentQ.getAnswer().equalsIgnoreCase(c2.getText().toString()))
{
c2.setTextColor(Color.GREEN);
}
else if (currentQ.getAnswer().equalsIgnoreCase(c3.getText().toString()))
{
c3.setTextColor(Color.GREEN);
}
}
return c4.getText().toString();
}
return null;
}
}
Question.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:gravity="center_horizontal"
android:background="#drawable/background">
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:paddingTop="15dip" android:paddingBottom="15dip"
android:gravity="center_horizontal">
<ImageView android:id="#+id/logo" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:src="#drawable/logo2"
android:contentDescription="Quiz_Logo" />
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:paddingTop="5dip" android:paddingBottom="5dip"
android:gravity="center_horizontal" >
<RadioGroup android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="vertical"
android:id="#+id/group1">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textColor="#ffffff"
android:textStyle="bold" android:id="#+id/question"/>
<RadioButton android:checked="false" android:id="#+id/answer1" />
<RadioButton android:checked="false" android:id="#+id/answer2" />
<RadioButton android:checked="false" android:id="#+id/answer3" />
<RadioButton android:checked="false" android:id="#+id/answer4" />
</RadioGroup>
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:paddingTop="5dip" android:paddingBottom="5dip"
android:gravity="center_horizontal">
<Button android:text="Next" android:id="#+id/nextBtn"
android:layout_width="80dip"
android:layout_height="wrap_content" android:background="#drawable/button_selector"
android:paddingTop="5dip" android:paddingBottom="5dip"
android:textColor="#ffffff" />
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="290.0dip" android:layout_height="wrap_content"
android:paddingTop="5dip" android:paddingBottom="5dip" android:layout_marginTop="50dp"
android:gravity="center_horizontal" >
<ProgressBar
android:id="#+id/progressbar"
android:max="5"
android:progress="0"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1.0"
style="#android:style/Widget.ProgressBar.Horizontal"
/>
<TextView
android:id="#+id/tv_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5"/>
</LinearLayout>
</LinearLayout>
In picture above is my question activity wherein I want to display and start
countdown progress timer.In all there are 20 questions in quiz.
I want to start timer as soon as question activity is started , time
interval to be 2 mins(120 sec) and want it to reduce value by 1
sec continuously till it
reaches 0.
Also I want progress bar to decrease by 1 percent with every second
elapsed and value(text) displayed alongside progress bar also should
decrease too simultaneously.
Like for 120 sec,progress bar is 100% . It should be 99% for 119 sec
and so on.
After reaching 0 , user should be redirected to results
page(EndgameActivity.java).
I am willing to mail my code to anybody willing to help me in case of any doubts in my code.
When your countdown stops you will need to call your set question function and start timer again. There will be onFinish() function for countdowntimer. You need to call your next question function.
2 ISSUE. Same with final countdown timer. You need to intent to the result page as soon as countdown finish
I want to create a clock showing the hour and Minute of the current time like this 02:15 PM. What i want is now to keep the minutes part updating obviously after every 60 seconds as it is changed in our systems. So i want to know what is the best way to keep the time updating
thanks
.xml file's code,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/txtTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
</RelativeLayout>
Activity file's code,
package com.example.demoproject;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.text.format.Time;
import android.widget.TextView;
public class MainActivity extends Activity
{
private static TextView textview;
private Timer timer;
private Time today;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView ) findViewById( R.id.txtTime );
today = new Time(Time.getCurrentTimezone());
timer = new Timer();
timer.schedule(new RemindTask(), 1000, 1000 );
}
private class RemindTask extends TimerTask
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
today.setToNow();
textview.setText(today.format("%k:%M:%S")); // Current time
}
});
}
}
}
I am developing a code breaking game i.e. Bulls and Cows in android. The problem is that in my main class I have applied a logic to check the numbers. This logic falls under a loop but when i run the application it freezes after entering into the loop. I'm tired of searching the answer on internet. I would be grateful to you people here if you could help out in some way. I regret if my code look lame to you as I'm a beginner in android programming.
The following is the code of my main class. :-
package com.bullsncows.bnc;
import java.util.Random;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Startingpoint extends Activity {
EditText etn1, etn2, etn3, etn4;
Button bsub;
TextView errormsg,res;
Random r = new Random();
int num = 0;
boolean guessed = false;
int count =0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
initializevar();
// making the computer select a random four digit number
while(hasDupes(num= (r.nextInt(9000) + 1000)));
// on clicking the submit button
bsub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String n1 = etn1.getText().toString();
String n2 = etn2.getText().toString();
String n3 = etn3.getText().toString();
String n4 = etn4.getText().toString();
String cnum = num+"";
if (n1.length()==0||n2.length()==0||n3.length()==0||n4.length()==0) {
errormsg.setText("Fields cannot be left blank");
errormsg.setTextColor(Color.RED);
errormsg.setGravity(Gravity.CENTER);
} else if (n1.equals(n2) || n1.equals(n3) || n1.equals(n4)
|| n2.equals(n3) || n2.equals(n4) || n3.equals(n4)) {
errormsg.setText("Please enter distinct number");
errormsg.setTextColor(Color.RED);
errormsg.setGravity(Gravity.CENTER);
}else{
String guess = n1+n2+n3+n4;
errormsg.setText("Correct "+ cnum + " "+ guess);
errormsg.setTextColor(Color.GREEN);
errormsg.setGravity(Gravity.CENTER);
do{
int bulls = 0;
int cows = 0;
count++;
for(int i= 0;i < 4;i++){
if(guess.charAt(i) == cnum.charAt(i)){
bulls++;
}else if(cnum.contains(guess.charAt(i)+"")){
cows++;
}
else if(bulls == 4){
guessed = true;
break;
}else{
res.setText(cows+" Cows and "+bulls+" Bulls.");
res.setTextColor(Color.BLUE);
res.setGravity(Gravity.CENTER);
}
}
}while(!guessed);
errormsg.setText("You won after "+count+" guesses!");
errormsg.setTextColor(Color.MAGENTA);
errormsg.setGravity(Gravity.CENTER);
}
}
});
}
private void initializevar() {
// TODO Auto-generated method stub
etn1 = (EditText) findViewById(R.id.etnum1);
etn2 = (EditText) findViewById(R.id.etnum2);
etn3 = (EditText) findViewById(R.id.etnum3);
etn4 = (EditText) findViewById(R.id.etnum4);
bsub = (Button) findViewById(R.id.bsubmit);
errormsg = (TextView) findViewById(R.id.tverror);
res = (TextView) findViewById(R.id.tvres);
}
public static boolean hasDupes(int n){
boolean[] digs = new boolean[10];
while(n > 0){
if(digs[n%10]) return true;
digs[n%10] = true;
n/= 10;
}
return false;
}
}
The following is the XML coding for the same page :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Please select the numbers below" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<EditText
android:id="#+id/etnum1"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
<EditText
android:id="#+id/etnum2"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
<EditText
android:id="#+id/etnum3"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
<EditText
android:id="#+id/etnum4"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:inputType="number"
android:maxLength="1" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:id="#+id/tverror"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
<TextView android:id="#+id/tvres"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/bsubmit"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_gravity="fill_vertical"
android:text="Submit" />
</LinearLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</TableLayout>
</LinearLayout>
without reading all of your code, i seems very unlikely
else if(bulls == 4)
will ever evalute to true, since you reset bulls each iteration
int bulls = 0;
and you only have four tries:
for(int i= 0;i < 4;i++)
Since
else if(bulls == 4){
guessed = true;
break;
is your only termination condition, you loop forever.
If you could narrow down your code to just the area that is causing problems that will help. But I might guess that the loop that has an error is
while(n > 0){
n/= 10;
}
n might never get to 0. Can you step through your code and work out exactly which part is failing?