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?
Related
I want a test for 3-4 years old childs. I want if they click different apple , true count must plus one. And if they click one of same aplles false count must plus one. And click any apple the question and apples are must change.
My friend helped me and we did much of them. On clicks question and answers changing. But when click any apple wrong count plus one no matter it's true or false answer.
Can u pls help me?
We think we only have problems on if commands. He tried on it so much but couldn't solve the problem.
class file:
package tr.com.blogspot.etkinlikhavuzu.benimilkogretmenim;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Random;
/**
* Created by erisk on 31.01.2017.
*/
public class AA extends Activity implements View.OnClickListener{
TextView soru,dogrusayi,yanlissayi;
ImageView secenek1,secenek2,secenek3;
ArrayList<Soru> sorular;
Random random;
int dogruSayisi,yanlisSayisi,sayac,dogruCevap;
#Override
protected 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.aa);
init();
sorulariYukle();
}
public void init(){
secenek1 = (ImageView) findViewById(R.id.secenek1);
secenek1.setOnClickListener(this);
secenek2 = (ImageView) findViewById(R.id.secenek2);
secenek2.setOnClickListener(this);
secenek3 = (ImageView) findViewById(R.id.secenek3);
secenek3.setOnClickListener(this);
soru = (TextView) findViewById(R.id.soru);
dogrusayi = (TextView) findViewById(R.id.dogrusayi);
yanlissayi = (TextView) findViewById(R.id.yanlissayi);
sorular = new ArrayList<Soru>();
random = new Random();
}
public void sorulariYukle(){
sorular.add(new Soru("Hangi Elma Yeşildir?",R.drawable.yesilelma,R.drawable.kirmizielma,R.drawable.kirmizielma,R.drawable.yesilelma));
sorular.add(new Soru("Hangi Elma Kırmızıdır?",R.drawable.kirmizielma,R.drawable.yesilelma,R.drawable.yesilelma,R.drawable.kirmizielma));
sorular.add(new Soru("Hangi Elma Yeşildir?",R.drawable.kirmizielma,R.drawable.yesilelma,R.drawable.kirmizielma,R.drawable.yesilelma));
sorular.add(new Soru("Hangi Elma Kırmızıdır?",R.drawable.yesilelma,R.drawable.yesilelma,R.drawable.kirmizielma,R.drawable.kirmizielma));
sorular.add(new Soru("Hangi Elma Yeşildir?",R.drawable.kirmizielma,R.drawable.kirmizielma,R.drawable.yesilelma,R.drawable.yesilelma));
sayac = random.nextInt(5);
soru.setText(sorular.get(sayac).getSoru());
secenek1.setImageResource(sorular.get(sayac).getSecenek1());
secenek2.setImageResource(sorular.get(sayac).getSecenek2());
secenek3.setImageResource(sorular.get(sayac).getSecenek3());
dogruCevap = sorular.get(sayac).getDogruCevap();
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.secenek1:
if(secenek1.getDrawable() == getResources().getDrawable(dogruCevap)){
dogruSayisi++;
dogrusayi.setText(String.valueOf(dogruSayisi));
}else{
yanlisSayisi++;
yanlissayi.setText(String.valueOf(yanlisSayisi));
}
sayac = random.nextInt(5);
soru.setText(sorular.get(sayac).getSoru());
secenek1.setImageResource(sorular.get(sayac).getSecenek1());
secenek2.setImageResource(sorular.get(sayac).getSecenek2());
secenek3.setImageResource(sorular.get(sayac).getSecenek3());
dogruCevap = sorular.get(sayac).getDogruCevap();
break;
case R.id.secenek2:
if(secenek2.getDrawable() == getResources().getDrawable(dogruCevap)){
dogruSayisi++;
dogrusayi.setText(String.valueOf(dogruSayisi));
}else{
yanlisSayisi++;
yanlissayi.setText(String.valueOf(yanlisSayisi));
}
sayac = random.nextInt(5);
soru.setText(sorular.get(sayac).getSoru());
secenek1.setImageResource(sorular.get(sayac).getSecenek1());
secenek2.setImageResource(sorular.get(sayac).getSecenek2());
secenek3.setImageResource(sorular.get(sayac).getSecenek3());
dogruCevap = sorular.get(sayac).getDogruCevap();
break;
case R.id.secenek3:
if(secenek3.getDrawable() == getResources().getDrawable(dogruCevap)){
dogruSayisi++;
dogrusayi.setText(String.valueOf(dogruSayisi));
}else{
yanlisSayisi++;
yanlissayi.setText(String.valueOf(yanlisSayisi));
}
sayac = random.nextInt(5);
soru.setText(sorular.get(sayac).getSoru());
secenek1.setImageResource(sorular.get(sayac).getSecenek1());
secenek2.setImageResource(sorular.get(sayac).getSecenek2());
secenek3.setImageResource(sorular.get(sayac).getSecenek3());
dogruCevap = sorular.get(sayac).getDogruCevap();
break;
}
}
}
xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="tr.com.blogspot.etkinlikhavuzu.benimilkogretmenim.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp">
<Button
android:id="#+id/dogru"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#drawable/dogru" />
<Button
android:id="#+id/yanlis"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/dogru"
android:layout_marginTop="10dp"
android:background="#drawable/yanlis" />
<TextView
android:id="#+id/dogrusayi"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_above="#+id/yanlis"
android:layout_toEndOf="#+id/dogru"
android:layout_toRightOf="#+id/dogru"
android:gravity="center"
android:text="#string/dogrusayi"
android:textColor="#006600"
android:textSize="30sp" />
<TextView
android:id="#+id/yanlissayi"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignBottom="#+id/yanlis"
android:layout_toEndOf="#+id/yanlis"
android:layout_toRightOf="#+id/yanlis"
android:gravity="center"
android:text="#string/yanlissayi"
android:textColor="#990000"
android:textSize="30sp" />
<ImageView
android:id="#+id/secenek1"
android:layout_width="170dp"
android:layout_height="170dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:id="#+id/secenek2"
android:layout_width="170dp"
android:layout_height="170dp"
android:layout_alignBottom="#+id/secenek1"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/secenek3"
android:layout_width="170dp"
android:layout_height="170dp"
android:layout_alignBottom="#+id/secenek2"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true" />
<TextView
android:id="#+id/soru"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/secenek2"
android:layout_marginBottom="18dp"
android:layout_toEndOf="#+id/dogrusayi"
android:layout_toRightOf="#+id/dogrusayi"
android:gravity="center"
android:text="Hangi Elma Yeşildir?"
android:textColor="#006600"
android:textSize="40sp"
android:textStyle="bold|italic" />
<TextView
android:id="#+id/siradaki"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:textColor="#000000" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="1" />
</RelativeLayout>
</RelativeLayout>
And Soru.class file
package tr.com.blogspot.etkinlikhavuzu.benimilkogretmenim;
/**
* Created by erisk on 31.01.2017.
*/
public class Soru {
String soru;
int secenek1,secenek2,secenek3,dogruCevap;
public Soru(String soru, int secenek1, int secenek2, int secenek3, int dogruCevap) {
this.soru = soru;
this.secenek1 = secenek1;
this.secenek2 = secenek2;
this.secenek3 = secenek3;
this.dogruCevap = dogruCevap;
}
public String getSoru() {
return soru;
}
public void setSoru(String soru) {
this.soru = soru;
}
public int getSecenek1() {
return secenek1;
}
public void setSecenek1(int secenek1) {
this.secenek1 = secenek1;
}
public int getSecenek2() {
return secenek2;
}
public void setSecenek2(int secenek2) {
this.secenek2 = secenek2;
}
public int getSecenek3() {
return secenek3;
}
public void setSecenek3(int secenek3) {
this.secenek3 = secenek3;
}
public int getDogruCevap() {
return dogruCevap;
}
public void setDogruCevap(int dogruCevap) {
this.dogruCevap = dogruCevap;
}
}
Thank you so much
You are comparing drawables. which never matches.
Change your if(CONDITION) to following:
if(secenek1.getDrawable().getConstantState().equals(getResources().getDrawable(dogruCevap).getConstantState())).
same way for other two cases.
I want to validate the mobile number user enters. I have two edit texts one for the code i.e. +91,0 etc and another for the phone number.
I have a question that how to stop entering the numbers in edit text if more than 10 numbers being entered by the user. Also it should get validated with code and the number.
I tried the validation with this code.
private boolean isValidMobile(String phone)
{
return android.util.Patterns.PHONE.matcher(phone).matches();
}
else if (!isValidMobile(code.getText().toString()+mobileNo.getText().toString()))
{
Toast.makeText(RegisterActivity.this,"Please enter correct Mobile No.",Toast.LENGTH_LONG).show();
}
But it dose not return true for the number. Always returns false i.e. please enter the correct number.
edit texts for number :
<EditText
android:layout_width="30dp"
android:layout_height="match_parent"
android:ems="10"
android:id="#+id/editText_code"
android:layout_marginLeft="20dp"
android:background="#android:color/transparent"
android:hint="+91"
android:textSize="14sp"
android:phoneNumber="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="MOBILE NO"
android:singleLine="false"
android:layout_below="#+id/linearLayoutFirstName"
android:layout_toRightOf="#+id/linearLayoutFirstName"
android:layout_toEndOf="#+id/linearLayoutFirstName"
android:background="#android:color/transparent"
android:layout_gravity="center"
android:textSize="12sp"
android:layout_marginLeft="05dp"
android:id="#+id/mobileNo"
android:phoneNumber="true" />
</LinearLayout>
How to do this? Thank you.
Try this Example...
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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">
<EditText
android:id="#+id/edtCountryCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:hint="country_code"/>
<EditText
android:id="#+id/edtPhoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/edtCountryCode"
android:inputType="phone"
android:hint="phone_no"/>
<TextView
android:id="#+id/tvIsValidPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edtPhoneNumber"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<Button
android:id="#+id/btnValidate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvIsValidPhone"
android:text="validate"/>
</RelativeLayout>
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
public class MainActivity extends AppCompatActivity {
TextView tvIsValidPhone;
EditText edtPhone;
EditText edtCountryCode;
Button btnValidate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvIsValidPhone = (TextView) findViewById(R.id.tvIsValidPhone);
edtCountryCode = (EditText) findViewById(R.id.edtCountryCode);
edtPhone = (EditText) findViewById(R.id.edtPhoneNumber);
btnValidate = (Button) findViewById(R.id.btnValidate);
btnValidate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String countryCode = edtCountryCode.getText().toString().trim();
String phoneNumber = edtPhone.getText().toString().trim();
if(countryCode.length() > 0 && phoneNumber.length() > 0){
if(isValidPhoneNumber(phoneNumber)){
boolean status = validateUsing_libphonenumber(countryCode, phoneNumber);
if(status){
tvIsValidPhone.setText("Valid Phone Number (libphonenumber)");
} else {
tvIsValidPhone.setText("Invalid Phone Number (libphonenumber)");
}
}
else {
tvIsValidPhone.setText("Invalid Phone Number (isValidPhoneNumber)");
}
} else {
Toast.makeText(getApplicationContext(), "Country Code and Phone Number is required", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean isValidPhoneNumber(CharSequence phoneNumber) {
if (!TextUtils.isEmpty(phoneNumber)) {
return Patterns.PHONE.matcher(phoneNumber).matches();
}
return false;
}
private boolean validateUsing_libphonenumber(String countryCode, String phNumber) {
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
String isoCode = phoneNumberUtil.getRegionCodeForCountryCode(Integer.parseInt(countryCode));
Phonenumber.PhoneNumber phoneNumber = null;
try {
//phoneNumber = phoneNumberUtil.parse(phNumber, "IN"); //if you want to pass region code
phoneNumber = phoneNumberUtil.parse(phNumber, isoCode);
} catch (NumberParseException e) {
System.err.println(e);
}
boolean isValid = phoneNumberUtil.isValidNumber(phoneNumber);
if (isValid) {
String internationalFormat = phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
Toast.makeText(this, "Phone Number is Valid " + internationalFormat, Toast.LENGTH_LONG).show();
return true;
} else {
Toast.makeText(this, "Phone Number is Invalid " + phoneNumber, Toast.LENGTH_LONG).show();
return false;
}
}}
Download jar file and add in libs folder from below link..
http://www.java2s.com/Code/Jar/l/Downloadlibphonenumber41jar.htm
Try to use isGlobalPhoneNumber() method of PhoneNumberUtils to detect whether a number is valid phone number or not.
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