Is my code using multithreading in Android? - java

I am trying to create a new thread for my app which will—of course—do all the necessary background work when I call it to prevent the UI thread from crashing. I cannot get it to work and am a little confused as to what I should do next. Here is my code:
package com.alarm.mobilegame;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class startGames extends MainActivity {
int a = (int)Math.ceil(Math.random()*100);
int b = (int)Math.ceil(Math.random()*100);
int c = (int)Math.ceil(Math.random()*100);
int d = (int)Math.ceil(Math.random()*100);
int e = (int)Math.ceil(Math.random()*10);
int f = (int)Math.ceil(Math.random()*10);
boolean A;
boolean B;
boolean C;
public void additionCalc() {
TextView addquestion;
TextView addquestion2;
addquestion = (TextView) findViewById(R.id.textView1);
addquestion2 = (TextView) findViewById(R.id.textView5);
addquestion.setText("" + a + "+");
addquestion2.setText("" + b);
}
public void substitutionCalc() {
if (d > c)
{
while(d > c)
d = (int)Math.ceil(Math.random()*100);
}
TextView subquestion;
TextView subquestion2;
subquestion = (TextView) findViewById(R.id.textView2);
subquestion2 = (TextView) findViewById(R.id.textView6);
subquestion.setText("" + c + "-");
subquestion2.setText("" + d);
}
public void multiplicationCalc() {
if (e * f < 1)
{
while(e * f < 1)
f = (int)Math.ceil(Math.random()*10);
}
TextView mulquestion;
TextView mulquestion2;
mulquestion = (TextView) findViewById(R.id.textView3);
mulquestion2 = (TextView) findViewById(R.id.textView7);
mulquestion.setText("" + e + "x");
mulquestion2.setText("" + f);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_game1);
final Button buttonMathStart = (Button) findViewById(R.id.button1);
buttonMathStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
additionCalc();
substitutionCalc();
multiplicationCalc();
}});
}
void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
checkResultsA();
checkResultsB();
checkResultsC();
}
public void checkResultsA() {
EditText aText;
aText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(aText.toString());
int d = a + b;
if (d != c) {
A = false;
}else{
A = true;
}
}
public void checkResultsB() {
EditText sText;
sText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(sText.toString());
int z = c - d;
if (d != c) {
B = false;
}
else{
B = true;
}
}
public void checkResultsC() {
EditText mText;
mText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(mText.toString());
int d = a * b;
if (d != c) {
C = false;
}
else {
C = true;
}
//runInBackground();
}
});
Button continueGame = (Button) findViewById(R.id.button2);
continueGame.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
runInBackground();
if (A || B || C == false)
{
//
}
else
{
Intent myIntent = new Intent(startGames.this, secondGame.class);
startGames.this.startActivity(myIntent);
}
}});
}
}

Your runInBackground() creates a Thread but does not start() it. The code is never run.
The thread code seems to be accessing UI elements. Generally you shouldn't touch the UI in a background thread.
Where you invoke runInBackground() in onClick() you seem to assume the thread result is already available on the next code line. It isn't.
I suggest you have a look at the AsyncTask to make background thread operations easier. It also has convenience helpers for working with the UI thread.
Also, based on the question comments it seems that you don't need a background thread in the first place. The root problem is the crash which you avoid by not running your code. To get help with the crash, have a look at exception stacktrace in logcat.

You have written the thread but seems you forgot to add code for starting the thread.
Change your runInBackground method to
void runInBackground() {
new Thread(new Runnable() {
#Override
public void run() {
checkResultsA();
checkResultsB();
checkResultsC();
}
public void checkResultsA() {
EditText aText;
aText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(aText.toString());
int d = a + b;
if (d != c) {
A = false;
}else{
A = true;
}
}
public void checkResultsB() {
EditText sText;
sText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(sText.toString());
int z = c - d;
if (d != c) {
B = false;
}
else{
B = true;
}
}
public void checkResultsC() {
EditText mText;
mText = (EditText) findViewById(R.id.editText1);
int c = Integer.parseInt(mText.toString());
int d = a * b;
if (d != c) {
C = false;
}
else {
C = true;
}
//runInBackground();
}
}).start();

Related

How to transfer and save numbers

This code right here is a random math questionnaire and I want to know how to be able to transfer the amount of questions answered right and wrong to a separate stats page after each time they answer a question. I want the stats page to save the numbers so that if the user exits the program and then goes back on later they can still look at their total right answered questions and wrong answered questions. Ive been looking all over the internet and cant find a good way to learn this. If anyone has some advice I would really appreciate it. btw this is pretty much all the code in the main page; I didn't add the stats page code (because it has pretty much nothing.)
Pushme1-4 are the buttons and the AdditionEasyRight and AdditionEasyWrong are the number counts that are displayed on the main page.
public class AdditionEasy extends AppCompatActivity {
int countCNumAddE = 0;
int countWNumAddE = 0;
boolean hasAnswered;
public static final String MY_PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addition);
final TextView count = (TextView) findViewById(R.id.Count);
final TextView count2 = (TextView) findViewById(R.id.Count2);
Button homeButton = (Button) findViewById(R.id.homeButton);
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final TextView textOne = (TextView) findViewById(R.id.textView);
final TextView textTwo = (TextView) findViewById(R.id.textView2);
final Button pushMe1 = (Button) findViewById(R.id.button1);
final Button pushMe2 = (Button) findViewById(R.id.button2);
final Button pushMe3 = (Button) findViewById(R.id.button3);
final Button pushMe4 = (Button) findViewById(R.id.button4);
final Button begin = (Button) findViewById(R.id.begin);
begin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hasAnswered = false;
pushMe1.setEnabled(true);
pushMe2.setEnabled(true);
pushMe3.setEnabled(true);
pushMe4.setEnabled(true);
begin.setVisibility(View.INVISIBLE);
pushMe1.setVisibility(View.VISIBLE);
pushMe2.setVisibility(View.VISIBLE);
pushMe3.setVisibility(View.VISIBLE);
pushMe4.setVisibility(View.VISIBLE);
pushMe1.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.BLACK);
pushMe1.setTextSize(20);
pushMe2.setTextSize(20);
pushMe3.setTextSize(20);
pushMe4.setTextSize(20);
textTwo.setText("");
String randGenChoice1 = "";
String randGenChoice2 = "";
String randGenChoice3 = "";
String randGenChoice4 = "";
String randText2 = "";
String randText3 = "";
Random RandomNum = new Random();
int randChoice1 = RandomNum.nextInt(40) + 1;
int randChoice2 = RandomNum.nextInt(40) + 1;
int randChoice3 = RandomNum.nextInt(40) + 1;
int randChoice4 = RandomNum.nextInt(40) + 1;
int rando2 = RandomNum.nextInt(20) + 1;
int rando3 = RandomNum.nextInt(20) + 1;
int pick = RandomNum.nextInt(4);
randGenChoice1 = Integer.toString(randChoice1);
randGenChoice2 = Integer.toString(randChoice2);
randGenChoice3 = Integer.toString(randChoice3);
randGenChoice4 = Integer.toString(randChoice4);
randText2 = Integer.toString(rando2);
randText3 = Integer.toString(rando3);
int value1;
int value2;
value1 = Integer.parseInt(randText2);
value2 = Integer.parseInt(randText3);
final int value = value1 + value2;
String line = randText2 + " + " + randText3;
textOne.setText(line);
final String answer;
answer = Integer.toString(value);
pushMe1.setText(randGenChoice1);
pushMe2.setText(randGenChoice2);
pushMe3.setText(randGenChoice3);
pushMe4.setText(randGenChoice4);
Button[] choice = {pushMe1, pushMe2, pushMe3, pushMe4};
Button display = choice[pick];
display.setText(answer);
pushMe1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe1.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.GREEN);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.RED);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe1.setEnabled(false);
}
}
});
pushMe2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe2.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.GREEN);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.RED);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe2.setEnabled(false);
}
}
});
pushMe3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe3.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.GREEN);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.RED);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe3.setEnabled(false);
}
}
});
pushMe4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe4.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.GREEN);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.RED);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe4.setEnabled(false);
}
}
});
}
});
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent homepage = new Intent(AdditionEasy.this , Menu.class);
startActivity(homepage);
}
});
}
}

Android Studio - Need help looping code every second

I need a system that will execute this code every second. I've been looking for a while and still can't find any ways that work. I'm quite new to Java programming and programming for android so any help will be greatly appreciated.
Values n = new Values();
double num = n.getNum();
double adder = n.getAdder();
if(adder>=1) {
num += (adder * 0.1);
}
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(num + "");
n.setNum(num);
Also, I'm importing values from a Values class that looks like this,
package com.example.durtle02.durtle02;
public class Values {
double num;
double cost = 30;
double adder;
public double getNum() {
return num;
}
public void setNum(double num) {
this.num = num;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public double getAdder() {
return adder;
}
public void setAdder(double adder) {
this.adder = adder;
}
}
EDIT
MainActivity.java
package com.example.durtle02.durtle02;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.Time;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//making game values accessible
final Values n = new Values();
//Loading The button for adding
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double num = n.getNum();
num++;
TextView tt = (TextView) findViewById(R.id.textView1);
n.setNum(num);
tt.setText(n.getNum() + "");
}
});
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double num = n.getNum();
double cost = n.getCost();
double adder = n.getAdder();
if (num >= cost) {
num -= cost;
cost = cost * 1.35;
adder++;
cost = Math.round(cost);
n.setNum(num);
n.setCost(cost);
n.setAdder(adder);
TextView tl = (TextView) findViewById(R.id.textView3);
tl.setText(n.getCost() + "");
TextView tk = (TextView) findViewById(R.id.textView4);
tk.setText(n.getAdder() + " Adders");
TextView tt = (TextView) findViewById(R.id.textView1);
tt.setText(n.getNum() + "");
TextView tp = (TextView) findViewById(R.id.textView2);
tp.setText((n.getAdder() * 0.1) + "/s");
}
}
});
countDownTimer.start();
}
// Do something each second in a time frame of 60 seconds.
CountDownTimer countDownTimer = new CountDownTimer(60000, 100) {
public void onTick(long millisUntilFinished) {
Values n = new Values();
double num = n.getNum();
double adder = n.getAdder();
if(adder>=1) {
num += (adder * 0.1);
}
num++;
n.setNum(num);
}
public void onFinish() {
countDownTimer.start(); // restart again.
}
};
/*
//---------------------------------------------------------------
Values n = new Values();
double num = n.getNum();
double adder = n.getAdder();
if(adder>=1) {
num += (adder * 0.1);
}
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(num + "");
n.setNum(num);
//--------------------------------------------------------------
*/
}
I think you can use CountDownTimer, something like this:
// Do something each second in a time frame of 60 seconds.
CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
// For every second, do something.
doSomething();
}
public void onFinish() {
countDownTimer.start(); // restart again.
}
}.start();
If your activity is in the foreground, the following code will do.
Handler mHandler= new Handler()
final Runnable runnable = new Runnable() {
#Override
public void run() {
// do your stuff here, called every second
mHandler.postDelayed(this, 1000);
}
};
// start it with:
mHandler.post(runnable);

Android Application Button onclicklistener

Hi there i've been constructing this code for a week but i still cant get it to work. It has no errors but when i run it on the AVD it terminates suddenly.
package com.tryout.sample;
import java.util.Random;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity implements View.OnClickListener{
Random number = new Random();
int Low = 1;
int High = 13;
int RandomNumber = number.nextInt(High-Low) + Low;
int current = 0;
int points=0;
final Integer[] cardid = { R.drawable.card1,
R.drawable.card10,
R.drawable.card11,
R.drawable.card12,
R.drawable.card13,
R.drawable.card2,
R.drawable.card3,
R.drawable.card4,
R.drawable.card5,
R.drawable.card6,
R.drawable.card7,
R.drawable.card8,
R.drawable.card9,
};
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView score = (TextView) findViewById(R.id.textView2);
Button high = (Button) findViewById(R.id.button1);
Button low = (Button) findViewById(R.id.button2);
final ImageView pic = (ImageView) findViewById(R.id.imageView1);
low.setOnClickListener(new view.OnClickListener() {
public void onClick(View v) {
int resource = cardid[RandomNumber];
if(current < RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
high.setOnClickListener(new View.OnClickListener() {
public void higher(View v) {
int resource = cardid[RandomNumber];
if(current > RandomNumber){
points = points + 1;
score.setText(points);
pic.setImageResource(resource);
}else{
score.setText("Game Over");
}
}
});
int resource = cardid[RandomNumber];
pic.setImageResource(resource);
current = RandomNumber;
}
}
I cant figure out where my problem is, kindly check out my code. THanks for any help
put this:
ImageView pic2 = (ImageView) findViewById(R.id.imageView1);
final TextView score = (TextView) findViewById(R.id.textView2);
in you onCreate method after the call setContentView(R.layout.activity_main);.
How should R.id.imageView1 assigned if the content is not specified like in your case?
ImageView pic2;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pic2 = (ImageView) findViewById(R.id.imageView1);
score = (TextView) findViewById(R.id.textView2);
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class minigame_cardpairing extends Activity implements View.OnClickListener {
private static final int TOTAL_CARD_NUM = 16;
private int[] cardId = {R.id.card01, R.id.card02, R.id.card03, R.id.card04, R.id.card05, R.id.card06, R.id.card07, R.id.card08,
R.id.card09, R.id.card10, R.id.card11, R.id.card12, R.id.card13, R.id.card14, R.id.card15, R.id.card16};
private Card[] cardArray = new Card[TOTAL_CARD_NUM];
private int CLICK_CNT = 0;
private Card first, second;
private int SUCCESS_CNT = 0;
private boolean INPLAY = false;
//----------- Activity widget -----------//
private Button start;
//-----------------------------------//
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.minigame_cardpairing);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
for(int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i] = new Card(i/2);
findViewById(cardId[i]).setOnClickListener(this);
cardArray[i].card = (ImageButton) findViewById(cardId[i]); // Card assignment
cardArray[i].onBack();
}
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startGame();
//start.setBackgroundDrawable(background);
}
});
findViewById(R.id.exit).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
} // end of onCreate
protected void startDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("The match-card game. Please remember to flip the cards two by two card hand is a pair Hit. Hit all pairs are completed.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Game Description");
alt2.show();
}
protected void clearDialog() {
AlertDialog.Builder alt1 = new AlertDialog.Builder(this);
alt1.setMessage("It fits all the cards in pairs. Congratulations.")
.setCancelable(false)
.setPositiveButton("close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alt2 = alt1.create();
alt2.setTitle("Match-complete");
alt2.show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
startDialog();
}
public void onClick(View v) {
if (INPLAY) {
switch (CLICK_CNT) {
case 0:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
first = cardArray[i];
break;
}
}
if (first.isBack) {
first.onFront();
CLICK_CNT = 1;
}
break;
case 1:
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (cardArray[i].card == (ImageButton) v) {
second = cardArray[i];
break;
}
}
if (second.isBack) {
second.onFront();
if (first.value == second.value) {
SUCCESS_CNT++;
Log.v("SUCCESS_CNT", "" + SUCCESS_CNT);
if (SUCCESS_CNT == TOTAL_CARD_NUM/2) {
clearDialog();
}
}
else {
Timer t = new Timer(0);
t.start();
}
CLICK_CNT = 0;
}
break;
}
}
}
void startGame() {
int[] random = new int[TOTAL_CARD_NUM];
int x;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
if (!cardArray[i].isBack)
cardArray[i].onBack();
}
boolean dup;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
while(true) {
dup = false;
x = (int) (Math.random() * TOTAL_CARD_NUM);
for (int j=0; j<i; j++) {
if (random[j] == x) {
dup = true;
break;
}
}
if (!dup) break;
}
random[i] = x;
}
start.setClickable(false);
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].card = (ImageButton) findViewById(cardId[random[i]]);
cardArray[i].onFront();
}
Log.v("timer", "start");
Timer t = new Timer(1);
//flag = false;
t.start();
/*
while(true) {
if (flag) break;
//Log.v("flag", "" + flag);
}
Log.v("timer", "end");
*/
SUCCESS_CNT = 0;
CLICK_CNT = 0;
INPLAY = true;
}
class Timer extends Thread {
int kind;
Timer (int kind) {
super();
this.kind = kind;
}
#Override
public void run() {
INPLAY = false;
// TODO Auto-generated method stub
try {
if (kind == 0) {
Thread.sleep(1000);
mHandler.sendEmptyMessage(0);
}
else if (kind == 1) {
Thread.sleep(3000);
mHandler.sendEmptyMessage(1);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
INPLAY = true;
}
}
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0) {
first.onBack();
second.onBack();
first.isBack = true;
second.isBack = true;
}
else if (msg.what == 1) {
//flag = true;
for (int i=0; i<TOTAL_CARD_NUM; i++) {
cardArray[i].onBack();
}
start.setClickable(true);
}
}
};
}
class Card { // start of Card class
private final static int backImageID = R.drawable.cardback;
private final static int[] frontImageID = {R.drawable.card1, R.drawable.card2,
R.drawable.card3, R.drawable.card4,
R.drawable.card5, R.drawable.card6,
R.drawable.card7, R.drawable.card8};
int value;
boolean isBack;
ImageButton card;
Card(int value) {
this.value = value;
}
public void onBack() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
}
public void flip() {
if (!isBack) {
card.setBackgroundResource(backImageID);
isBack = true;
}
else {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
public void onFront() {
if (isBack) {
card.setBackgroundResource(frontImageID[value]);
isBack = false;
}
}
} // end of Card class

how to add Double and Char arrays with each other in my scientific calculator program

i have two arrays.
double number[] = new double[5];
char oper[] = new char[4];
in my program when user press any operator sign like +,-,*,/ the number array is taking user input for example if he is entering 345 it is taking and saving it in number[0] and [0] become [1] and also save the current operation input from user and save it in oper[0] and so on.
but i dont know how can i get the result using both arrays.
i am pasting whole code here.
package com.example.calculatortesting;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements OnClickListener {
TextView textdisplay;
EditText currentcalc;
EditText et1;
double number[] = new double[5]; //for saving numbers in array
char oper[] = new char[4]; //for saving operation in array
int numposition = 0; //for position of number array
int operposition = 0; //for position of operation array
double currentnum; //saving current number before operation
int last_button = 0; //checking last button pressed
char operator; //saving pressed operation value
String newnum = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
et1 = (EditText) findViewById(R.id.editText1);
textdisplay = (TextView) findViewById(R.id.editText1);
currentcalc = (EditText) findViewById(R.id.textView1);
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);
Button b3 = (Button) findViewById(R.id.b3);
Button b4 = (Button) findViewById(R.id.b4);
Button b5 = (Button) findViewById(R.id.b5);
Button b6 = (Button) findViewById(R.id.b6);
Button b7 = (Button) findViewById(R.id.b7);
Button b8 = (Button) findViewById(R.id.b8);
Button b9 = (Button) findViewById(R.id.b9);
Button b0 = (Button) findViewById(R.id.b0);
Button multiply1 = (Button) findViewById(R.id.multiply);
Button divide1 = (Button) findViewById(R.id.divide);
Button plus1 = (Button) findViewById(R.id.plus);
Button minus1 = (Button) findViewById(R.id.minus);
Button equal1 = (Button) findViewById(R.id.equal);
Button clear1 = (Button) findViewById(R.id.clear);
Button back1 = (Button) findViewById(R.id.backspace);
Button dot1 = (Button) findViewById(R.id.decimal);
Button plusminus1 = (Button) findViewById(R.id.plusminus);
Button percent = (Button) findViewById(R.id.percent);
Button shift = (Button) findViewById(R.id.shift);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
b7.setOnClickListener(this);
b8.setOnClickListener(this);
b9.setOnClickListener(this);
b0.setOnClickListener(this);
multiply1.setOnClickListener(this);
divide1.setOnClickListener(this);
plus1.setOnClickListener(this);
minus1.setOnClickListener(this);
equal1.setOnClickListener(this);
clear1.setOnClickListener(this);
back1.setOnClickListener(this);
dot1.setOnClickListener(this);
plusminus1.setOnClickListener(this);
percent.setOnClickListener(this);
shift.setOnClickListener(this);
}
public void currentcalcmethod(String currentcalcoper) {
currentcalc.setText(currentcalc.getText() + currentcalcoper);
currentcalc.setSelection(currentcalc.getText().length());
}
void number() {
}
void oper() {
number[numposition] = currentnum;
oper[operposition] = operator;
numposition ++;
operposition++;
currentnum= 0;
}
void result (){
double total;
StringBuilder builder = new StringBuilder();
for (double num : number) {
for (char op : oper){
builder.append(num + op);
total = num+op;
et1.setText(Double.toString(total));
}}
}
public void shownum(String number) {
newnum = newnum + number ;
currentnum = Double.parseDouble(newnum);
et1.setText(Double.toString(currentnum));
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.b0) {
currentcalcmethod("0");
shownum("0");
} else if (v.getId() == R.id.b1) {
currentcalcmethod("1");
shownum("1");
} else if (v.getId() == R.id.b2) {
currentcalcmethod("2");
shownum("2");
} else if (v.getId() == R.id.b3) {
currentcalcmethod("3");
shownum("3");
} else if (v.getId() == R.id.b4) {
currentcalcmethod("4");
shownum("4");
} else if (v.getId() == R.id.b5) {
currentcalcmethod("5");
shownum("5");
} else if (v.getId() == R.id.b6) {
currentcalcmethod("6");
shownum("6");
} else if (v.getId() == R.id.b7) {
currentcalcmethod("7");
shownum("7");
} else if (v.getId() == R.id.b8) {
currentcalcmethod("8");
shownum("8");
} else if (v.getId() == R.id.b9) {
currentcalcmethod("9");
shownum("9");
} else if (v.getId() == R.id.plus) {
currentcalcmethod("+");
operator = '+';
oper();
} else if (v.getId() == R.id.minus) {
currentcalcmethod("-");
operator = '-';
oper();
} else if (v.getId() == R.id.percent) {
currentcalcmethod("%");
operator = '%';
oper();
} else if (v.getId() == R.id.divide) {
currentcalcmethod("/");
operator = '/';
oper();
} else if (v.getId() == R.id.multiply) {
currentcalcmethod("*");
operator = '*';
oper();
} else if (v.getId() == R.id.decimal) {
currentcalcmethod(".");
} else if (v.getId() == R.id.equal) {
result ();
currentcalcmethod("=");
} else if (v.getId() == R.id.backspace) {
if (currentcalc.getText().toString().length() > 0) {
int start =0;
int end2 = currentcalc.getText().toString().length() - 1;
String newText2 = currentcalc.getText().toString()
.substring(start, end2);
currentcalc.setText(newText2);
}
} else if (v.getId() == R.id.clear) {
textdisplay.setText("");
currentcalc.setText("");
number = null;
oper = null;
numposition = 0;
operposition = 0;
} else if (v.getId() == R.id.plusminus) {
}
last_button = v.getId();
}
}
Take the user input as a String and parse it. Something like:
String userInput = "3+5";
List<Character> numbers = new ArrayList<>();
List<Character> operators = new ArrayList<>();
for (char c : userInput.toCharArray()) {
if(Character.isDigit(c)){
numbers.add(c);
}
else{
operators.add(c);
}
}
// Now loop through lists and perform the desired arthimetic operation based on operator
You could put all of the inputs into a String and convert the string to a double to get an actual equation.
String ans = Double.toString(number[0]) +
Char.toString(oper[0]) + Double.toString(number[1]); //could use a loop to enter all values != null
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript"); // build-in javascript engine allows for string equations.
try {
System.out.println(engine.eval(ans));
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Something like that.

How to set default value to 0 in edittext when nothing is inputted?

I have an app here which adds the number. I have 4 edittexts here. What I want to happen is that when i entered none in one of the edittexts, it will assume that I entered 0. How can it be done? Here is my code:
public class Order extends Activity {
Button GoBackHome;
private Button button1;
private EditText txtbox1,txtbox2,txtbox3,txtbox4;
private TextView tv;
Button PayNow;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
GoBackHome = (Button) findViewById(R.id.gohomebutton);
PayNow = (Button) findViewById(R.id.button2);
txtbox1= (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.editText5);
txtbox2= (EditText) findViewById(R.id.editText2);
txtbox3= (EditText) findViewById(R.id.editText3);
txtbox4= (EditText) findViewById(R.id.editText4);
button1.setOnClickListener(new clicker());
GoBackHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, MainActivity.class);
startActivity(i);
}
});
PayNow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, Payment.class);
startActivity(i);
}
});
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
}
}
}
You can do as Tushar said or you can initialize the value in the XML. Something like
<EditText
android:name="#+id/editText1"
android:text="0"/>
FYI you might also find it cleaner to handle your button clicks on xml like:
<Button
android:name="#+id/btn1"
android:onClick="handleClicks"/>
and then in java you'd have a public void method:
public void handleClicks(View clickedView){
if(clickedView.getId() == btn1.getId(){
...
} else if (...){}
}
initialize as :
txtbox1.setText("0");
Check the EditText length when you get it
String value = null;
if(ed.getText().length()){
value = textBox.getText().toString();
} else
value = 0+"";
You can set android:hint="0" in your XML file, then, in your code, you can check if it's empty (maybe using TextUtils.isEmpty()) and setting some variable to 0.
android:hint="0" will make a "0" appear in your EditTexts, but the "0" will disappear when anything is inputted.
Then you can change the onClick() to this:
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
try {
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
} catch (NumberFormatException e) {
vis = "0";
}
// Do something with "vis"
}
}
Or you can create a method to check a value, try to parse to an int or return a default value.
public int getInt(String edtValue, int defaultValue) {
int value = defaultValue;
if (edtValue != null) {
try {
value = Integer.parseInt(edtValue);
} catch (NumberFormatException e) {
value = defaultValue;
}
}
return value;
}
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;

Categories