I am new to Java and I am developing a Number Guessing Game. When I click the random button , I get a random number that's okay but When I try this second time, second and first random numbers are the same.
How can I solve it? Here is my code:
int KullaniciTahmini;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView Sayi = (TextView) findViewById(R.id.Sayi);
Button Tamam = (Button) findViewById(R.id.Tamam);
final Button Rastgele = (Button) findViewById(R.id.Rastgele);
final EditText Tahmin = (EditText) findViewById(R.id.Tahmin);
final int gizliSayi = 0 + (int)(Math.random() * 100);
Rastgele.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int random = (int)(Math.random() * 100);
Sayi.setText("Lutfen 0 ile 100 arasinda bir deger giriniz!");
}
});
Tamam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int KullaniciTahmini = Integer.parseInt(Tahmin.getText().toString());
if (KullaniciTahmini < gizliSayi) {
Sayi.setText("Degeri Buyult");
}
if (KullaniciTahmini > gizliSayi) {
Sayi.setText("Degeri Kucult");
}
if (KullaniciTahmini == gizliSayi) {
Sayi.setText("Dogru Cevap!");
}
}
});
}
You only assign to gizliSayi once, in onCreate:
final int gizliSayi = 0 + (int)(Math.random() * 100);
I think you want to remove the final there and then update that value in Rastgele.setOnClickListener by changing this line:
int random = (int)(Math.random() * 100);
to this:
gizliSayi = (int)(Math.random() * 100);
Related
I am facing difficulties in showing data in textView after going to the next page
I am storing the return value in EMI variable but I am not able to print that value in the next page textview.
public class EmiCalculator extends AppCompatActivity {
public static double emical(double p,double r, double t)
{
double emi;
r = r / (12 * 100); // one month interest
t = t * 12; // one month period
emi = (p * r * (double)Math.pow(1 + r, t)) / (double)(Math.pow(1 + r, t) - 1);
return (emi);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emi_calculator);
EditText getText_1, getText_2, getText_3;
getText_1 = (EditText) findViewById(R.id.emi_editText_1);
getText_2 = (EditText) findViewById(R.id.emi_editText_2);
getText_3 = (EditText) findViewById(R.id.emi_editText_3);
Button calculateButton = (Button) findViewById(R.id.emi_calculate);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double emi_edit_Text_01 = Double.parseDouble(getText_1.getText().toString());
double emi_edit_Text_02 = Double.parseDouble(getText_2.getText().toString());
double emi_edit_Text_03 = Double.parseDouble(getText_3.getText().toString());
double emi = emical(emi_edit_Text_01, emi_edit_Text_02, emi_edit_Text_03);
String str = String.valueOf(emi);
TextView result = (TextView) findViewById(R.id.result_textView_3);
result.setText(""+emi);
Intent nextPage = new Intent(EmiCalculator.this,Result.class);
startActivity(nextPage);
}
});
}
}
you must use
Intent.putExtra
for send data to another activity.
in first activity:
Intent nextPage = new Intent(EmiCalculator.this,Result.class);
nextPage.putExtra("result",""+emi);
startActivity(nextPage);
in second activity:
Intent intentResult=this.getIntent;
if(intentResult.hasExtra("result")){
textview.setText(intent.getStringExtra("result"));
}
I am practising on a simple Android Game where a round button is randomly placed on the screen when the user taps on it..
it works fine but i want to speedify the process of placing the button so that the game gets harder for user...
here is the Code I'm using -
public class GameWindow extends Activity implements View.OnClickListener {
static int score;
private Timer t;
private int TimeCounter = 29;
private boolean canMove = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
////Remove title screen for activty.
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_game_window);
moveButton();
endonTimeOver();
}
public void endonTimeOver(){
////Activity timer for 60 seconds.
final TextView timer = (TextView) findViewById(R.id.seconds);
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
////Set string to timer.
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
timer.setText(String.valueOf(TimeCounter)); // you can set it to a textView to show it to the user to see the time passing while he is writing.
TimeCounter = TimeCounter - 1;
}
});
}
}, 1000, 1000); // 1000 means start from 1 sec, and the second 1000 is do the loop each 1 sec.
new Timer().schedule(new TimerTask(){
public void run() {
GameWindow.this.runOnUiThread(new Runnable() {
public void run() {
startActivity(new Intent(GameWindow.this, Finished.class));
}
});
}
}, 30000);
}
////Move button.
private void moveButton()
{
if(!canMove){ return; }
runOnUiThread(
new Runnable()
{
#Override
public void run()
{
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Button button = (Button)findViewById(R.id.button);
Random r = new Random();
int startX = width/2;
int startY = height/2;
if(score==0){
button.setX(startX);
button.setY(startY);
}
else {
int x = r.nextInt(width - 210);
int y = r.nextInt(height - 200);
button.setX(x);
button.setY(y);
}
}
}
);
}
////Display score
public void displayScore(int score) {
TextView scoreView = (TextView) findViewById(R.id.score);
scoreView.setText(String.valueOf(score));
}
#Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.buttonsound);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
score = score + 1;
displayScore(score);
switch (v.getId()) {
case (R.id.button): {
moveButton();
}
}
}
public static int getScore(){
return score;
}}
Use global variables for values that don't change:
findViewById is slow
Creating new Random every time is not necessary
getting the window parameter every time is not necessary either
You seem to be starting a new thread and telling it to runonui , this might be slowing you down , try this :
private void moveButton()
{
if(!canMove){ return; }
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Button button = (Button)findViewById(R.id.button);
Random r = new Random();
int startX = width/2;
int startY = height/2;
if(score==0){
button.setX(startX);
button.setY(startY);
}
else {
int x = r.nextInt(width - 210);
int y = r.nextInt(height - 200);
button.setX(x);
button.setY(y);
}
}
the computation itself doesn't seem to heavy so no need for another thread , you can do it on the main thread , if you're calling from oncreate that means you're already on main thread , this might give you the answer if i understood the question , try it
I am new to Android Studio. I have gone through the official developer.android.com training and I decided to create a new and simple app called Grocery+ in which user will enter the price and quantity of particular item and app will display total sum.
I have done all UI based work then today I switched to programming. I am an experienced programmer of Java. I have also done all the work in it but:
1- my app crashes when I try to enter the first .
Then I have to enter any other value first then first value.
2- even after above hack my app doesn't display anything on 'grand total
Plese help :(((
package com.amostrone.akash.grocery;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
static int Quantity[] = new int[4];
static float Price[] = new float[4];
public static double total=0;
static TextView txtValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtValue = (TextView) findViewById(R.id.txtExample);
}
/////////// QUANTITY
public void input_Quantity(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity);
calc();
}
public void input_Quantity2(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity2);
Quantity[1] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity3(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity3);
Quantity[2] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity4(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity4);
Quantity[3] = Integer.parseInt(x.toString());
calc();
}
public void input_Quantity5(View view) {
EditText x = (EditText) findViewById(R.id.editQuantity5);
Quantity[4] = Integer.parseInt(x.toString());
calc();
}
/////////////// Quantity
////////////// Price
public void input_Price(View view) {
EditText x = (EditText) findViewById(R.id.editPrice);
Price[0] = Float.parseFloat(x.toString());
calc();
}
public void input_Price2(View view) {
EditText x = (EditText) findViewById(R.id.editPrice2);
Price[1] = Float.parseFloat(x.toString());
calc();
}
public void input_Price3(View view) {
EditText x = (EditText) findViewById(R.id.editPrice3);
Price[2] = Float.parseFloat(x.toString());
calc();
}
public void input_Price4(View view) {
EditText x = (EditText) findViewById(R.id.editPrice4);
Price[3] = Float.parseFloat(x.toString());
calc();
}
public void input_Price5(View view) {
EditText x = (EditText) findViewById(R.id.editPrice5);
calc();
}
///////////// Price
/////////////// Calculate
public static void calc()
{
for(int i=0;i<=4;i++)
total += (Quantity[i] * Price[i]);
String str = Double.toString(total);
txtValue.setText(str);
}
////////////// Calculate }
Looking at your code it appears your are triggering EditText value get and calculation on click event (via xml). This does not work this way as they are triggered immediately. One of the approaches to solve this problem is to go the TextWatcher route. Check the below code built around that, I also refactored it a bit (should be lesser prone to memory leaks now):
public double mTotal;
private TextView mTextView;
private EditText[] mQuantityEditTexts = new EditText[5];
private EditText[] mPriceEditTexts = new EditText[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.txtExample);
mQuantityEditTexts[0] = (EditText) findViewById(R.id.editQuantity);
mQuantityEditTexts[1] = (EditText) findViewById(R.id.editQuantity2);
mQuantityEditTexts[2] = (EditText) findViewById(R.id.editQuantity3);
mQuantityEditTexts[3] = (EditText) findViewById(R.id.editQuantity4);
mQuantityEditTexts[4] = (EditText) findViewById(R.id.editQuantity5);
mPriceEditTexts[0] = (EditText) findViewById(R.id.editPrice);
mPriceEditTexts[1] = (EditText) findViewById(R.id.editPrice2);
mPriceEditTexts[2] = (EditText) findViewById(R.id.editPrice3);
mPriceEditTexts[3] = (EditText) findViewById(R.id.editPrice4);
mPriceEditTexts[4] = (EditText) findViewById(R.id.editPrice5);
for (int i = 0; i < 5; i++) {
mQuantityEditTexts[i].addTextChangedListener(mTextWatcher);
mPriceEditTexts[i].addTextChangedListener(mTextWatcher);
}
}
private TextWatcher mTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
calc();
}
#Override
public void afterTextChanged(Editable s) {
}
};
public void calc()
{
try {
for (int i = 0; i <= 4; i++)
mTotal += Integer.parseInt(mQuantityEditTexts[i].getText().toString()) *
Double.parseDouble(mPriceEditTexts[i].getText().toString());
String str = Double.toString(mTotal);
mTextView.setText(str);
} catch (NumberFormatException e) {
Toast.makeText(this, "WTF! Enter valid numbers!", Toast.LENGTH_SHORT).show();
}
}
I have created custom edittext which does not hangs.
SearchTimerEditText
I have 2 textviews, 1 editbox and 1 button in my xml.
In my code, this line is not working:
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
But next line (else statement) is working and In both cases (if & else statement) it shows else function toast ("Wrong").
Here is my code:
public class GameActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
Random r = new Random();
int i = r.nextInt(10 - 2) + 2;
tv.setText(i +"");
Random r1 = new Random();
int j = r1.nextInt((9 - 2) + 1) + 2;
tv2.setText(j +"");
int a = Integer.parseInt(tv.getText().toString());
int b = Integer.parseInt(tv2.getText().toString());
int result = a*b;
String str = String.valueOf(result);
EditText txt4 = (EditText) findViewById(R.id.editText1);
String c = txt4.getText().toString();
if(TextUtils.isEmpty(txt4.getText().toString())) {
txt4.setError("Please enter your answer");
return;
}
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(GameActivity.this, "wrong",Toast.LENGTH_LONG).show();
}
txt4.setText("");
}
});
}
Try this,
I got result
public class Test extends AppCompatActivity {
Button b1;
TextView t1,t2;
EditText e1;
int a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
b1 = (Button) findViewById(R.id.button2);
t1=(TextView) findViewById(R.id.textView4);
t2=(TextView) findViewById(R.id.textView5);
e1=(EditText) findViewById(R.id.editText);
Random r = new Random();
int i = r.nextInt(10 - 2) + 2;
t1.setText(i +"");
Random r1 = new Random();
int j = r1.nextInt((9 - 2) + 1) + 2;
t2.setText(j +"");
a = Integer.parseInt(t1.getText().toString());
b = Integer.parseInt(t2.getText().toString());
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int result = a*b;
String str = String.valueOf(result);
String c = e1.getText().toString();
if(TextUtils.isEmpty(c)) {
e1.setError("Please enter your answer");
return;
}
if(c.equals(str)){
Toast.makeText(Test.this, "Alright",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Test.this, "wrong",Toast.LENGTH_LONG).show();
}
e1.setText("");
}
});
}}
Instead of
String str = String.valueOf(result);
you should use
String str = Integer.toString(result);
I have 2 EditText fields set up for numeric inputs, a button to start a calculation on the 2 inputs when pressed, and a TextView to display the result of the calculation. For repeated calculations I want to clear the TextView result as soon as either EditText is changed.
Following the reply to "A better way to OnClick for EditText fields" given by 'avalancha', my program clears the result when the first EditText field is changed, but retains the previous answer if only the second EditText field is changed. Yet I have used the same source code for both fields.
Can someone explain why, and how to cure this? my code is appended:
public class DoublesActivity extends ActionBarActivity {
private EditText textBox1, textBox2;
private Button calcButton;
private Context context;
#Override
protected void onCreate(Bundle outState) {
super.onCreate(outState);
setContentView(R.layout.activity_doubles); // Sets the layout .xml file
context = this.getApplicationContext();
textBox1 = (EditText) findViewById(R.id.editText1); //textBox1 holds a reference to the editText1 object in the xml layout
textBox2 = (EditText) findViewById(R.id.editText2);
textBox1.setText("");
textBox2.setText("");
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
textBox2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v2, boolean hasFocus2) {
if (hasFocus2) {
textBox3.setText("");
}
}
});
textBox1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v1, boolean hasFocus1) {
if (hasFocus1) {
textBox3.setText("");
}
}
});
calcButton = (Button) findViewById(R.id.button1);
calcButton.setBackgroundColor(Color.CYAN);
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CharSequence userNumber1 = textBox1.getText(); //userNumber1 is a CharSequence holding the text in textBox1
CharSequence userNumber2 = textBox2.getText();
Float handicap1 = Float.parseFloat(userNumber1.toString()); //convert to integer
Float handicap2 = Float.parseFloat(userNumber2.toString()); //convert to integer
Float handicapT = calculate(handicap1, handicap2);
CharSequence userNumber = String.valueOf(handicapT);
if (handicapT > 98.5) {
userNumber = "Non-valid h'cap 1!";
}
if (handicapT < -98.5) {
userNumber = "Non-valid h'cap 2!";
}
textBox3.setText(userNumber); // put result in the TextView
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userNumber = textBox3.getText();
outState.putCharSequence("savedText", userNumber);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userText = savedInstanceState.getCharSequence("savedText");
textBox3.setText(userText);
}
Float calculate(Float h1, Float h2) {
float[] handicapArray;
handicapArray = new float[29];
handicapArray[0] = 28;
handicapArray[1] = 26;
handicapArray[2] = 24;
handicapArray[3] = 22;
handicapArray[4] = 20;
handicapArray[5] = 18;
handicapArray[6] = 16;
handicapArray[7] = 14;
handicapArray[8] = 12;
handicapArray[9] = 11;
handicapArray[10] = 10;
handicapArray[11] = 9;
handicapArray[12] = 8;
handicapArray[13] = 7;
handicapArray[14] = 6;
handicapArray[15] = 5;
handicapArray[16] = 4.5F;
handicapArray[17] = 4;
handicapArray[18] = 3.5F;
handicapArray[19] = 3;
handicapArray[20] = 2.5F;
handicapArray[21] = 2;
handicapArray[22] = 1.5F;
handicapArray[23] = 1;
handicapArray[24] = 0.5F;
handicapArray[25] = 0;
handicapArray[26] = -0.5F;
handicapArray[27] = -1;
handicapArray[28] = -1.5F;
int index1 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h1 - handicapArray[i]) < 0.001) {
index1 = i;
break;
}
}
if (index1 == -1) {
EditText textBox1 = (EditText) findViewById(R.id.editText1);
textBox1.setText("");
}
int index2 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h2 - handicapArray[i]) < 0.001) {
index2 = i;
break;
}
}
if (index2 == -1) {
EditText textBox2 = (EditText) findViewById(R.id.editText2);
textBox2.setText("");
}
int indexT = (index1 + index2) / 2; // Correctly rounds indexT halves down.
Float result = handicapArray[indexT];
if (index1 == -1) {
result = 99F;
}
;
if (index2 == -1) {
result = -99F;
}
;
return result;
}
Use addTextChangedListener to clear textview.
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
resultTextView.setText("");
}
});
For example please use below link
android on Text Change Listener