I have been working on application that displays a problem and 4 possible answers. Answer correctly, and the next problem appears. A wrong answer or letting the timer run out results in a popup that tells the correct answer and that you just lost a "life". Everything works well except that when the popup appears, the countdown timer continues and generates another popup. I can't find a way to get the activity to wait for the button on the dialog to be pressed before continuing to the next problem. I have read many questions/answers here and combed through many pages on the android developers site. Any help with this problem would be greatly appreciated.
public class MainActivity extends Activity {
String problems[][] = {{},{"Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"},
{"Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"}};
String answers[][] = {{},{"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"},
{"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"}};
public int level;
private int lister[] = {1,1,2,3,4};
Random rand = new Random();
int holder, probcount = 0, score = 0, lives = 5;
String problem, answer1, answer2, answer3, answer4, corrAnswer, l1, l2, l3;
boolean correct = false, changeBG = false, timeup = false, nolives = false, inpopup = false;
MyCount counter;
View lv, lf1, lf2, lf3, lf4, lf5;
MediaPlayer soundright, soundwrong;
final Context context = this;
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);
lv = findViewById(R.id.quizshow);
lf1 = findViewById(R.id.Life1);
lf2 = findViewById(R.id.Life2);
lf3 = findViewById(R.id.Life3);
lf4 = findViewById(R.id.Life4);
lf5 = findViewById(R.id.Life5);
Log.v("Events","onCreate");
soundright = MediaPlayer.create(this, R.raw.correct1);
soundwrong = MediaPlayer.create(this, R.raw.correct2);
Button btnAnswer1 = (Button)findViewById(R.id.Answer1);
btnAnswer1.setOnClickListener(onAnswer1);
Button btnAnswer2 = (Button)findViewById(R.id.Answer2);
btnAnswer2.setOnClickListener(onAnswer2);
Button btnAnswer3 = (Button)findViewById(R.id.Answer3);
btnAnswer3.setOnClickListener(onAnswer3);
Button btnAnswer4 = (Button)findViewById(R.id.Answer4);
btnAnswer4.setOnClickListener(onAnswer4);
Button btnExit = (Button)findViewById(R.id.btnExit);
btnExit.setOnClickListener(onExit);
Log.v("Events","onCreate2");
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
level = 1;
doNext();
}
protected void onResume() {
Log.d("Events", "onResume");
super.onResume();
}
protected void onPause() {
Log.d("Events", "onPause");
super.onPause();
counter.cancel();
}
protected void onDestroy() {
Log.d("Events", "onDestroy");
super.onDestroy();
}
private View.OnClickListener onAnswer1=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer1");
if (lister[1] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer2=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer2");
if (lister[2] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer3=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer3");
if (lister[3] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onAnswer4=new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onAnswer4");
if (lister[4] == lister[0]) {
doRight();
}
else {
doWrong();
}
};
};
private View.OnClickListener onExit = new View.OnClickListener() {
public void onClick(View v) {
Log.v("Events", "onExit");
finish();
};
};
private void doNext() {
if (changeBG == true) {
l1 = getResources().getString(R.string.LevelDone1);
l2 = getResources().getString(R.string.LevelDone2)+" "+String.valueOf(level);
l3 = getResources().getString(R.string.LevelDone3);
doPopup();
changeBG = false;
level = level + 1;
score = 0;
probcount = 0;
}
Log.v("Events", "DoNext1");
probcount = probcount + 1;
lister[0] = rand.nextInt(9);
holder = rand.nextInt(3);
lister[holder+1] = lister[0];
This is where I have boring code that makes sure that the 4 answers are different.
problem = problems[level][lister[0]];
TextView pr = (TextView) findViewById(R.id.Problem);
pr.setText(problem);
answer1 = answers[level][lister[1]];
TextView a1 = (TextView) findViewById(R.id.Answer1);
a1.setText(answer1);
answer2 = answers[level][lister[2]];
TextView a2 = (TextView) findViewById(R.id.Answer2);
a2.setText(answer2);
answer3 = answers[level][lister[3]];
TextView a3 = (TextView) findViewById(R.id.Answer3);
a3.setText(answer3);
answer4 = answers[level][lister[4]];
TextView a4 = (TextView) findViewById(R.id.Answer4);
a4.setText(answer4);
corrAnswer = answers[level][lister[0]];
if (probcount < 6){
counter = new MyCount(4000, 1);
} else if (probcount < 11) {
counter = new MyCount(3000, 1);
} else if (probcount < 21) {
counter = new MyCount(2500, 1);
} else if (probcount < 31) {
counter = new MyCount(2000, 1);
} else if (probcount < 41) {
counter = new MyCount(1500, 1);
} else if (probcount < 51) {
counter = new MyCount(1000, 1);
} else {
counter = new MyCount(750, 1);
}
counter.start();
}
private void doRight() {
Log.v("Events", "DoRight");
counter.cancel();
soundright.start();
if (probcount < 6){
score = score +10;
} else if (probcount < 11) {
score = score + 20;
} else if (probcount < 21) {
score = score +30;
} else if (probcount < 31) {
score = score +40;
} else if (probcount < 41) {
score = score + 50;
} else if (probcount < 51) {
score = score + 100;
} else {
score = score + 200;
}
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
if (score > 590) {
changeBG = true;
}
doNext();
}
private void doWrong() {
Log.v("Events", "DoWrong");
counter.cancel();
soundwrong.start();
lives = lives - 1;
if (lives != 5) {
if (lives == 4) {
lf5.setVisibility(View.INVISIBLE);
} else if (lives == 3) {
lf4.setVisibility(View.INVISIBLE);
} else if (lives == 2) {
lf3.setVisibility(View.INVISIBLE);
} else if (lives == 1) {
lf2.setVisibility(View.INVISIBLE);
} else if (lives == 0) {
lf1.setVisibility(View.INVISIBLE);
nolives = true;
}
}
if (nolives) {
l1 = getResources().getString(R.string.LivesGone1);
l2 = getResources().getString(R.string.LivesGone2);
l3 = getResources().getString(R.string.LivesGone3);
} else {
if (timeup) {
l1 = getResources().getString(R.string.TimeExpired);
timeup = false;
} else {
l1 = getResources().getString(R.string.WrongChoice);
}
l2 = getResources().getString(R.string.LifeLost);
l3 = getResources().getString(R.string.CorrAnswer)+" "+corrAnswer;
}
doPopup();
if (nolives) {
score = 0;
probcount = 0;
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
lf1.setVisibility(View.VISIBLE);
lf2.setVisibility(View.VISIBLE);
lf3.setVisibility(View.VISIBLE);
lf4.setVisibility(View.VISIBLE);
lf5.setVisibility(View.VISIBLE);
nolives = false;
}
doNext();
}
private void doPopup() {
Log.v("Events", "DoPopup");
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup);
TextView ln1 = (TextView) dialog.findViewById(R.id.Line1);
TextView ln2 = (TextView) dialog.findViewById(R.id.Line2);
TextView ln3 = (TextView) dialog.findViewById(R.id.Line3);
ln1.setText(l1);
ln2.setText(l2);
ln3.setText(l3);
inpopup = true;
dialog.show();
Button dialogButton = (Button) dialog.findViewById(R.id.btnPopup);
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
inpopup = false;
dialog.dismiss();
}
});
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
timeup = true;
doWrong();
}
#Override
public void onTick(long millisUntilFinished) {
double TimeLeft = millisUntilFinished;
TextView timer1 = (TextView) findViewById(R.id.Timer);
timer1.setText(String.valueOf(TimeLeft/1000));
}
}
}
You have a repetitive loop insisde a timer...
Let say, when your timer is is finished, it will call onFinish() and you are calling doWrong() in onFinish(). and doWrong() is calling doPopUp() which will open a Dialog again.(repetitively). To avoid, maintain some flags(like boolean or int) and based on the value of the flag, you decide whether to show PopUp Dialog when timer is finished or cancel the Timer when you are dismissing Diaog...
private void doWrong() {
Log.v("Events", "DoWrong");
counter.cancel();
soundwrong.start();
lives = lives - 1;
if (lives != 5) {
if (lives == 4) {
lf5.setVisibility(View.INVISIBLE);
} else if (lives == 3) {
lf4.setVisibility(View.INVISIBLE);
} else if (lives == 2) {
lf3.setVisibility(View.INVISIBLE);
} else if (lives == 1) {
lf2.setVisibility(View.INVISIBLE);
} else if (lives == 0) {
lf1.setVisibility(View.INVISIBLE);
nolives = true;
}
}
if (nolives) {
l1 = getResources().getString(R.string.LivesGone1);
l2 = getResources().getString(R.string.LivesGone2);
l3 = getResources().getString(R.string.LivesGone3);
} else {
if (timeup) {
l1 = getResources().getString(R.string.TimeExpired);
timeup = false;
} else {
l1 = getResources().getString(R.string.WrongChoice);
}
l2 = getResources().getString(R.string.LifeLost);
l3 = getResources().getString(R.string.CorrAnswer)+" "+corrAnswer;
}
// change here
if(!timeup)
doPopup();
if (nolives) {
score = 0;
probcount = 0;
TextView sc = (TextView) findViewById(R.id.Score);
sc.setText(String.valueOf(score));
lf1.setVisibility(View.VISIBLE);
lf2.setVisibility(View.VISIBLE);
lf3.setVisibility(View.VISIBLE);
lf4.setVisibility(View.VISIBLE);
lf5.setVisibility(View.VISIBLE);
nolives = false;
}
doNext();
}
I'm adding this answer to be able to mark the question as answered. Please read the comment I left after the question.
Thanks to all that provide help on this site. I have gained much knowledge here.
Related
I have a Class FoodDialog that extends AlertDialog that I have customized to how I would like it to look.
I am now wanting to edit the positive/negative buttons using an AlertDialog.Builder, however, when I attempt to build an instance of FoodDialog using a builder, I am facing an 'Incompatible types' error where the builder is asking for AlertDialog instead I am providing it with an extension of AlertDialog - is there a way around this?
If not, is there a way I can edit the positive/negative buttons of my custom AlertDialog class FoodDialog?
Below is my FoodDialog class. The yes/no buttons I have there are ones I have created myself, but I would like the ones that are part of the AlertDialog.Builder to appear instead as these buttons get pushed out of sight when the soft keyboard appears:
public class FoodDialog extends AlertDialog implements OnClickListener {
private TextView foodNameTextView, foodDescTextView, foodPortionTextView, catTextView, qtyText, cal, fat, sFat, carb, sug, prot, salt, imageTxt,
measureText;
private EditText foodQty;
private ImageView foodImage;
private ImageButton yesBtn, noBtn;
private int foodID, totalCal;
private Bitmap image;
private String user, portionType, foodName, foodDesc, cat, totalCalString, totalFatString,
totalSFatString, totalCarbString, totalSugString, totalProtString, totalSaltString, portionBaseString;
private double totalFat, totalSFat, totalCarb, totalSug, totalProt, totalSalt, portionBase;
private Food food;
private Portion portion;
private Nutrients nutrients;
private PortionType pType;
private DBHandler db;
public FoodDialog(Context context){
super(context);
}
public FoodDialog(Context context, int foodID, String imgLocation, final String user) {
super(context, android.R.style.Theme_Holo_Light_Dialog);
this.setTitle("Confirm?");
setContentView(R.layout.dialog_layout);
this.foodID = foodID;
this.user = user;
db = new DBHandler(context);
food = db.getFoodByID(foodID, user);
portion = db.getPortionByFoodID(foodID);
nutrients = db.getNutrientsByFoodIDAndPortionType(foodID, portion.getPortionType());
pType = db.getPortionTypeByName(portion.getPortionType());
//getting object attributes
portionType = portion.getPortionType();
portionBase = portion.getPortionBase();
//food
foodName = food.getName();
foodDesc = food.getDesc();
cat = food.getCat();
//nutrients
totalCal = nutrients.getCal();
totalFat = nutrients.getFat();
totalSFat = nutrients.getSFat();
totalCarb = nutrients.getCarb();
totalSug = nutrients.getSug();
totalProt = nutrients.getProt();
totalSalt = nutrients.getSalt();
//converting to string
totalCalString = String.valueOf(totalCal);
if (totalFat % 1 == 0) {
totalFatString = String.format("%.0f", totalFat);
} else {
totalFatString = String.valueOf(totalFat);
}
if (totalSFat % 1 == 0) {
totalSFatString = String.format("%.0f", totalSFat);
} else {
totalSFatString = String.valueOf(totalSFat);
}
if (totalCarb % 1 == 0) {
totalCarbString = String.format("%.0f", totalCarb);
} else {
totalCarbString = String.valueOf(totalCarb);
}
if (totalSug % 1 == 0) {
totalSugString = String.format("%.0f", totalSug);
} else {
totalSugString = String.valueOf(totalSug);
}
if (totalProt % 1 == 0) {
totalProtString = String.format("%.0f", totalProt);
} else {
totalProtString = String.valueOf(totalProt);
}
if (totalSalt % 1 == 0) {
totalSaltString = String.format("%.0f", totalSalt);
} else {
totalSaltString = String.valueOf(totalSalt);
}
if (portionBase % 1 == 0) {
portionBaseString = String.format("%.0f", portionBase);
} else {
portionBaseString = String.valueOf(portionBase);
}
//textviews
foodNameTextView = (TextView) findViewById(R.id.dialogName);
foodNameTextView.setText(foodName);
foodDescTextView = (TextView) findViewById(R.id.dialogDesc);
foodDescTextView.setText(foodDesc);
foodPortionTextView = (TextView) findViewById(R.id.dialogPortion);
foodPortionTextView.setText("Values based per " + portionBase + " " + portionType);
catTextView = (TextView) findViewById(R.id.dialogCat);
catTextView.setText(cat);
measureText = (TextView) findViewById(R.id.dialogMeasure);
measureText.setText(portionType);
qtyText = (TextView) findViewById(R.id.dialogQtyText);
imageTxt = (TextView) findViewById(R.id.dialogImageText);
cal = (TextView) findViewById(R.id.dialogCal);
cal.setText(totalCalString);
fat = (TextView) findViewById(R.id.dialogFat);
fat.setText(totalFatString + "g");
sFat = (TextView) findViewById(R.id.dialogSFat);
sFat.setText(totalSFatString + "g");
carb = (TextView) findViewById(R.id.dialogCarb);
carb.setText(totalCarbString + "g");
sug = (TextView) findViewById(R.id.dialogSug);
sug.setText(totalSugString + "g");
prot = (TextView) findViewById(R.id.dialogProt);
prot.setText(totalProtString + "g");
salt = (TextView) findViewById(R.id.dialogSalt);
salt.setText(totalSaltString + "g");
//img
foodImage = (ImageView) findViewById(R.id.dialogImage);
imgLocation = food.getImgURL();
image = BitmapFactory.decodeFile(imgLocation);
foodImage.setImageBitmap(image);
if (imgLocation.equals("nourl")) {
imageTxt.setText("No Image");
}
//edit tex
foodQty = (EditText) findViewById(R.id.dialogQty);
//adjusting edittext
foodQty.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
foodQty.setFilters(new InputFilter[]{
new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {
int beforeDecimal = 4, afterDecimal = 3;
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
String temp = foodQty.getText() + source.toString();
if (temp.equals(".")) {
return "0.";
} else if (temp.toString().indexOf(".") == -1) {
// no decimal point placed yet
if (temp.length() > beforeDecimal) {
return "";
}
} else {
temp = temp.substring(temp.indexOf(".") + 1);
if (temp.length() > afterDecimal) {
return "";
}
}
return super.filter(source, start, end, dest, dstart, dend);
}
}
});
foodQty.setText(portionBaseString);
//btns
yesBtn = (ImageButton) findViewById(R.id.yesBtn);
noBtn = (ImageButton) findViewById(R.id.noBtn);
Bitmap tick = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_tick);
Bitmap cross = BitmapFactory.decodeResource(context.getResources(),
R.drawable.png_cross);
yesBtn.setImageBitmap(tick);
noBtn.setImageBitmap(cross);
yesBtn.setOnClickListener(this);
noBtn.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
#Override
public void onClick(View v) {
if (v == yesBtn) {
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
String date = currentDate.format(new Date());
String time = currentTime.format(new Date());
double qty = 0;
//get quantity amount
// if (portionMeasure.equals("singles")) {
//qty = foodQty.getValue();
// } else {
if (foodQty.getText().length() != 0) {
qty = Double.valueOf(foodQty.getText().toString());
} else {
qty = 0;
}
// }
if (qty == 0 || String.valueOf(qty) == "") {
Toast.makeText(getContext(), "Please enter an amount", Toast.LENGTH_SHORT).show();
} else {
//create new intake
Intake intake = new Intake(0, foodID, portionType, qty, date, time);
//record it and increment food used value
db.recordIntake(intake, user);
db.incrementUsedCount(intake.getFoodID(), 1);
db.close();
cancel();
Toast.makeText(getContext(), foodName + " recorded", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("What next?");
builder.setItems(new CharSequence[]
{"Record another food intake..", "Main Menu..", "View Stats.."},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
cancel();
break;
case 1:
Intent main = new Intent(getContext(), ProfileActivity.class);
getContext().startActivity(main);
break;
case 2:
Intent stats = new Intent(getContext(), StatsActivity.class);
getContext().startActivity(stats);
break;
}
}
});
AlertDialog choose = builder.create();
choose.show();
}
} else if (v == noBtn) {
cancel();
}
}
}
You can catch your buttons click listener as follows:
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//yes button click code here
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//no button click code here
}
});
You can use the logcat to see if your listener are being fired.
I am developing a game program where I want to store images in the buttons. I want to randomize the images shown in the buttons when the users play the game again, but I don't know how to randomize the images.
public class MainActivity extends Activity {
public static final String COME_FROM = "come_from";
private int[] id_mc = new int[16];
private Integer[][] img_mc = new Integer [16][2];
private Button[] myMcs = new Button[16];
private int mc_counter = 0;
private int firstid = 0;
private int secondid = 0;
private Boolean mc_isfirst = false;
private int correctcounter = 0;
private TextView tFeedback;
private MediaPlayer mp;
private Boolean b_snd_inc, b_snd_cor;
Random r = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
initGame();
}
private void initGame() {
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
mc_counter = 0;
firstid = 0;
secondid = 0;
mc_isfirst = false;
correctcounter = 0;
tFeedback = (TextView) findViewById(R.id.mc_feedback);
// setup button listeners
Button startButton = (Button) findViewById(R.id.game_menu);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startMenu();
}
});
Button settingsButton = (Button) findViewById(R.id.game_settings);
settingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startPrefs();
}
});
// fill arrays with resources
id_mc[0] = R.id.mc0;
id_mc[1] = R.id.mc1;
id_mc[2] = R.id.mc2;
id_mc[3] = R.id.mc3;
id_mc[4] = R.id.mc4;
id_mc[5] = R.id.mc5;
id_mc[6] = R.id.mc6;
id_mc[7] = R.id.mc7;
id_mc[8] = R.id.mc8;
id_mc[9] = R.id.mc9;
id_mc[10] = R.id.mc10;
id_mc[11] = R.id.mc11;
id_mc[12] = R.id.mc12;
id_mc[13] = R.id.mc13;
id_mc[14] = R.id.mc14;
id_mc[15] = R.id.mc15;
img_mc[0][0] = R.drawable.back1;
img_mc[0][1] = R.drawable.ic_img1;
img_mc[1][0] = R.drawable.back2;
img_mc[1][1] = R.drawable.ic_img2;
img_mc[2][0] = R.drawable.back3;
img_mc[2][1] = R.drawable.ic_img3;
img_mc[3][0] = R.drawable.back4;
img_mc[3][1] = R.drawable.ic_img4;
img_mc[4][0] = R.drawable.back5;
img_mc[4][1] = R.drawable.ic_img5;
img_mc[5][0] = R.drawable.back6;
img_mc[5][1] = R.drawable.ic_img6;
img_mc[6][0] = R.drawable.back7;
img_mc[6][1] = R.drawable.ic_img7;
img_mc[7][0] = R.drawable.back8;
img_mc[7][1] = R.drawable.ic_img8;
img_mc[8][0] = R.drawable.back1;
img_mc[8][1] = R.drawable.ic_img1;
img_mc[9][0] = R.drawable.back2;
img_mc[9][1] = R.drawable.ic_img2;
img_mc[10][0] = R.drawable.back3;
img_mc[10][1] = R.drawable.ic_img3;
img_mc[11][0] = R.drawable.back4;
img_mc[11][1] = R.drawable.ic_img4;
img_mc[12][0] = R.drawable.back5;
img_mc[12][1] = R.drawable.ic_img5;
img_mc[13][0] = R.drawable.back6;
img_mc[13][1] = R.drawable.ic_img6;
img_mc[14][0] = R.drawable.back7;
img_mc[14][1] = R.drawable.ic_img7;
img_mc[15][0] = R.drawable.back8;
img_mc[15][1] = R.drawable.ic_img8;
//Collections.shuffle(Arrays.asList(img_mc));
for (int i = 0; i < 16; i++) {
try{
myMcs[i] = (Button) findViewById(id_mc[i]);
myMcs[i].setBackgroundResource(img_mc[i][0]);
myMcs[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int i = 0;
for (int n = 0; n < 16; n++) {
if (id_mc[n] == view.getId())
i = n;
}
doClickAction(view, i);
}
});
}catch(Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}}
}
private void doClickAction(View v, int i)
{
v.setBackgroundResource(img_mc[i][1]);
mc_isfirst = !mc_isfirst;
// disable all buttons
for (Button b : myMcs) {
b.setEnabled(false);
}
if (mc_isfirst) {
// turning the first card
firstid = i;
// re enable all except this one
for (Button b : myMcs) {
if (b.getId() != firstid) {
b.setEnabled(true);
}
}
} else {
// turning the second card
secondid = i;
doPlayMove();
}
}
private void doPlayMove() {
mc_counter++;
if (img_mc[firstid][1] - img_mc[secondid][1] == 0) {
//correct
if (b_snd_cor) playSound(R.raw.correct);
waiting(200);
myMcs[firstid].setVisibility(View.INVISIBLE);
myMcs[secondid].setVisibility(View.INVISIBLE);
correctcounter++;
} else {
//incorrect
if (b_snd_inc) playSound(R.raw.incorrect);
waiting(400);
}
// reenable and turn cards back
for (Button b : myMcs) {
if (b.getVisibility() != View.INVISIBLE) {
b.setEnabled(true);
b.setBackgroundResource(R.drawable.memory_back);
for (int i = 0; i < 16; i++) {
myMcs[i].setBackgroundResource(img_mc[i][0]);
}
}
}
tFeedback.setText("" + correctcounter + " / " + mc_counter);
if (correctcounter > 7) {
Intent iSc = new Intent(getApplicationContext(), Scoreboard.class);
iSc.putExtra("com.gertrietveld.memorygame.SCORE", mc_counter);
startActivity(iSc);
finish();
}
}
public void playSound(int sound) {
mp = MediaPlayer.create(this, sound);
mp.setVolume((float).5,(float).5);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
public static void waiting(int n) {
long t0, t1;
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ((t1 - t0) < (n));
}
private void startMenu() {
Intent launchMenu = new Intent(this, MenuScreen.class);
launchMenu.putExtra(COME_FROM,"PlayGame");
startActivity(launchMenu);
}
private void startPrefs() {
Intent launchPrefs = new Intent(this, Setting.class);
startActivity(launchPrefs);
}
////////////////////////////////
#Override
protected void onRestart() {
super.onRestart();
//String sender = getIntent().getExtras().getString("SENDER");
//initGame();
Toast.makeText(this, "onRestart-sender is " , Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
}
////////////////////////////////
}
You had the Collections.shuffle() part right, you just need to get the randomized list back into your array:
private Integer[][] img_mc = new Integer [16][2];
...
List<Integer[]> img_mc_list = new ArrayList<Integer[]>();
for (Integer[] img : img_mc) {
img_mc_list.add(img);
}
Collections.shuffle(img_mc_list);
img_mc_list.toArray(img_mc);
Or use this:
private void randomize(Integer[][] array) {
int index;
Integer[] temp;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
I'm streaming a video in my app, and it works fine.
The problem is that when I try to make it full screen (in a new activity or otherwise), the screen is blank.
I have tried doing it without starting a new activity, as suggested here:
In my main activity:
butFullScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(isFS)
setContentView(R.layout.activity_full_screen_video);
else
setContentView(R.layout.activity_starting_point);
}
});
I've also tried opening it in a new activity (which I prefer):
butFullScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start fs intent
Intent myIntent = new Intent(StartingPoint.this, FullScreenVideo.class);
StartingPoint.this.startActivity(myIntent);
}
});
Where FullScreenVideo:
public class FullScreenVideo extends StartingPoint{
//private VideoView vv;
public FullScreenVideo(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen_video);
vv.start();
}
}
And activity_full_screen_video:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:background="#ff000000">
<VideoView
android:id="#+id/vv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And in my manifest:
<activity
android:name=".FullScreenVideo"
android:label="#string/app_name"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize" />
It doesn't show any error or crash, just a blank screen. Also, I'm not using the media controller, so answers without that would be appreciated :)
Edit::
StartingPoint:
public class PlayVid extends ActionBarActivity {
int play = -1;
int k;
int m = 0;
int where;
int pausePressed = 0;
int displaySub = 0;
String curSub = " ";
ArrayList<Stime> timeArray = new ArrayList<Stime>();
Button but;
Button butStop;
Button butSub;
Button butFS;
TextView subs, log;
VideoView vv;
ProgressBar pBar;
int isFS, space;
String srt = "00:00:01,478 --> 00:00:04,020\n" +
"VimeoSrtPlayer Example\n" +
"\n" +
"00:00:05,045 --> 00:00:09,545\n" +
"Support for <i>italic</i> font\n" +
"\n" +
"00:00:09,378 --> 00:00:13,745\n" +
"Support for <b>bold</b> font\n" +
"\n" +
"00:00:14,812 --> 00:00:16,144\n" +
"Multi\n" +
"Line\n" +
"Support ;)\n" +
"\n" +
"00:00:18,211 --> 00:00:21,211\n" +
"Fonts: DejaVu\n" +
"http://dejavu-fonts.org\n" +
"\n" +
"00:00:22,278 --> 00:00:25,678 \n" +
"END OF EXAMPLE FILE";
subParse sp = new subParse(this, srt);
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setProgressBarIndeterminateVisibility(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point);
pBar = (ProgressBar) findViewById(R.id.progressBar);
subs = (TextView) findViewById(R.id.subtitleBox);
log = (TextView) findViewById(R.id.logBox);
but = (Button) findViewById(R.id.but);
butStop = (Button) findViewById(R.id.butStop);
butSub = (Button) findViewById(R.id.butSub);
butFS = (Button) findViewById(R.id.butFS);
vv = (VideoView) findViewById(R.id.vv);
vv.setVideoPath("#string/video_link");
String[] lines = {" \n", " \n"};
sp.parseSub(srt);
subs.setText("--Click Play to start--\n--Click on SUB to view subtitles--");
final String[] sub2 = log.getText().toString().split(System.getProperty("line.separator"));
final subHelper sob = new subHelper(this, sub2);
final onPauseHelper oph = new onPauseHelper();
final fsHelper fsh = new fsHelper(this);
final playHelper ph = new playHelper();
timeArray.add(new Stime(vv.getDuration(), 0));
but.setOnClickListener(new View.OnClickListener() {
long startTime = 0, trop = 0;
int space = 0;
public void onClick(View v) {
subs.setText(curSub);
fsh.space = space;
if (fsh.isFS == 1) {
//Chill
} else if (play == 0 || play == -1) {
vv.start();
pBar.setVisibility(View.VISIBLE);
if (vv.isPlaying()) {
startTime = Calendar.getInstance().getTimeInMillis();
pBar.setVisibility(View.INVISIBLE);
//Play
if (play == -1) {
sob.setDefaults();
}
oph.putAttr(3, startTime);
but.setText("||");
but.setTextColor(Color.parseColor("#ffaaaaaa"));
if (k < m) {
play = 1;
final Handler handler = new Handler();
final Runnable run = new Runnable() {
#Override
public void run() {
if (k < m && play == 1 && fsh.isFS == 0) {
if (pausePressed == 0) {
oph.putAttr(0, Calendar.getInstance().getTimeInMillis());
} else {
oph.putAttr(0, startTime);
where--;
}
//oph.nextPressed=Calendar.getInstance().getTimeInMillis();
if (space == 0) {
space = 1;
fsh.space = space;
play = sob.subPlay(startTime, 0);
fsh.play = play;
trop = (timeArray.get(k).getTime(1) - timeArray.get(k).getTime(0));
handler.postDelayed(this, Math.abs(trop > 0 ? (trop - oph.done) : 0));
} else if (space == 1) {
space = 0;
fsh.space = space;
play = sob.subPlay(startTime, 1);
fsh.play = play;
trop = timeArray.get(k + 1).getTime(0) - timeArray.get(k).getTime(1);
handler.postDelayed(this, Math.abs(trop > 0 ? (trop - oph.done) : 0));
k++;
}
oph.putAttr(1, Calendar.getInstance().getTimeInMillis());
pausePressed = 0;
sob.pp = 0;
oph.reset();
oph.done = 0;
} else if (k >= m && fsh.isFS == 0) {
final Runnable run = new Runnable() {
#Override
public void run() {
but.setText("↻");
but.setTextColor(Color.parseColor("#ffcdcdcd"));
subs.setText("Play Again?");
handler.removeCallbacks(this);
play = -1;
fsh.play = play;
//ph.saveState(play,0,k,0,curSub,displaySub);
curSub = " ";
}
};
while (vv.isPlaying()) {
}
handler.postDelayed(run, 0);
}
}
};
if (k == 0)
handler.postDelayed(run, (timeArray.get(0).getTime(0)));
else if (k < m) handler.postDelayed(run, 0);
}
}
} else if (play == 1) {
//Pause
vv.pause();
oph.reset();
oph.putAttr(2, Calendar.getInstance().getTimeInMillis());
subs.setText(curSub);
pausePressed = 1;
oph.done = +oph.getProg();
sob.pp++;
but.setText("▶");
but.setTextColor(Color.parseColor("#ffcdcdcd"));
if (k < m) {
if (space == 0) {
space = 1;
fsh.space = space;
} else if (space == 1) {
space = 0;
fsh.space = space;
}
play = sob.subPause(oph.getAttr(2));
fsh.play = play;
}
}
}
});
butStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vv.stopPlayback();
sob.setDefaults();
play = 0;
fsh.play = play;
but.setText("▶");
subs.setText("--Click Play to start--");
curSub = " ";
}
});
butSub.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (displaySub == 0) {
displaySub = 1;
subs.setText(curSub);
butSub.setTextColor(Color.parseColor("#ffaaaaaa"));
} else if (displaySub == 1) {
displaySub = 0;
subs.setText(" ");
butSub.setTextColor(Color.parseColor("#ffcdcdcd"));
}
}
});
butFS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Start fs intent
Intent myIntent = new Intent(PlayVid.this, TwoFullScreenVideo.class);
PlayVid.this.startActivity(myIntent);
}
});
}
}
FullScreenVideo:
public class FullScreenVideo extends StartingPoint {
fsHelper fsh;
onPauseHelper oph;
subHelper sob;
playHelper ph;
protected PlayVid context;
TextView subs;
Button but, butStop, butSub, butFS;
public FullScreenVideo(){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_full_screen_video);
subs = (TextView) findViewById(R.id.subtitleBox);
but = (Button) findViewById(R.id.but);
butStop = (Button) findViewById(R.id.butStop);
butSub = (Button) findViewById(R.id.butSub);
butFS = (Button) findViewById(R.id.butFS);
vv = (VideoView) findViewById(R.id.vv);
butFS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FullScreenVideo.this.finish();
}
});
}
}
I have my List-view Item: Easy Medium Hard.
How am I going to Disable Medium and Hard? . and how to Enable it after
reaching certain score on "Easy" quiz . Please Help me guys. :(
This is my code.
String classes[] = {"Easy", "Medium", "Hard" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String easy = classes[position];
try{
Class openClass = Class.forName("first.project." + easy);
Intent openIntent = new Intent(this , openClass);
startActivity(openIntent);
}
catch (ClassNotFoundException e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
This is the code on my QuestionActivity
public class QuestionActivity extends Activity {
// Called when the activity is first created.
EditText question = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioButton answer4 = null;
RadioGroup answers = null;
Button finish = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review =false;
Button prev, next = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
TableLayout quizLayout = (TableLayout) findViewById(R.id.quizLayout);
quizLayout.setVisibility(android.view.View.INVISIBLE);
try {
question = (EditText) findViewById(R.id.question);
answer1 = (RadioButton) findViewById(R.id.a0);
answer2 = (RadioButton) findViewById(R.id.a1);
answer3 = (RadioButton) findViewById(R.id.a2);
answer4 = (RadioButton) findViewById(R.id.a3);
answers = (RadioGroup) findViewById(R.id.answers);
RadioGroup questionLayout = (RadioGroup)findViewById(R.id.answers);
Button finish = (Button)findViewById(R.id.finish);
finish.setOnClickListener(finishListener);
prev = (Button)findViewById(R.id.Prev);
prev.setOnClickListener(prevListener);
next = (Button)findViewById(R.id.Next);
next.setOnClickListener(nextListener);
selected = new int[Easy.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[Easy.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0,review);
quizLayout.setVisibility(android.view.View.VISIBLE);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex,boolean review) {
try {
JSONObject aQues = Easy.getQuesList().getJSONObject(qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.WHITE);
answer2.setTextColor(Color.WHITE);
answer3.setTextColor(Color.WHITE);
answer4.setTextColor(Color.WHITE);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(3).getString("Answer");
answer4.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("",selected[qIndex]+"");
if (selected[qIndex] == 0)
answers.check(R.id.a0);
if (selected[qIndex] == 1)
answers.check(R.id.a1);
if (selected[qIndex] == 2)
answers.check(R.id.a2);
if (selected[qIndex] == 3)
answers.check(R.id.a3);
setScoreTitle();
if (quesIndex == (Easy.getQuesList().length()-1))
next.setEnabled(false);
if (quesIndex == 0)
prev.setEnabled(false);
if (quesIndex > 0)
prev.setEnabled(true);
if (quesIndex < (Easy.getQuesList().length()-1))
next.setEnabled(true);
if (review) {
Log.d("review",selected[qIndex]+""+correctAns[qIndex]);;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
if (selected[qIndex] == 3)
answer4.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 3)
answer4.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private OnClickListener finishListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
//Calculate Score
int score = 0;
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) && (correctAns[i] == selected[i]))
score++;
}
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(QuestionActivity.this).create();
alertDialog.setTitle("Score");
alertDialog.setMessage((score) +" out of " + (Easy.getQuesList().length()));
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Retake", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
quesIndex=0;
QuestionActivity.this.showQuestion(0, review);
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Review", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = true;
quesIndex=0;
QuestionActivity.this.showQuestion(0, review);
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,"Quit", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
finish();
}
});
alertDialog.show();
}
};
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
if (answer4.isChecked())
selected[quesIndex] = 3;
Log.d("",Arrays.toString(selected));
Log.d("",Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex++;
if (quesIndex >= Easy.getQuesList().length())
quesIndex = Easy.getQuesList().length() - 1;
showQuestion(quesIndex,review);
}
};
private OnClickListener prevListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex--;
if (quesIndex < 0)
quesIndex = 0;
showQuestion(quesIndex,review);
}
};
private void setScoreTitle() {
this.setTitle("Question # " + (quesIndex+1)+ "/" + Easy.getQuesList().length());
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Warning!!")
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
Use a loop like so:
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
adapter.remove(adapter.getItem(i));
}
I think that should work
XcutionX
this what i understood, what you are going to do is:
First of all the 'easy' button will be enabled and the rest of two will be disabled (I guess).
buttonEasy.setEnabled(true);
buttonMediun.setEnabled(false);
buttonHard.setEnabled(false);
then after the quiz with 'easy' level is finished, check the score if it has reached a certain value. If yes, then you will enable the 'Medium' button with the code:
buttonMedium.setEnabled(true);
i am a beginner in android. i am trying to make a calculator with just one input edit text.
when i click + button it doesn't give a sum output. to get a correct ans i have to click the +button after both the entries. like to get a sum i will do it as 1"+" 1"+""=. then it would give 2. here's my code,someoneplease help me.
public void onClick(View v){
double sum=0;
switch(v.getId()){
case R.id.buttonplus:
sum += Double.parseDouble(String.valueOf(textView.getText()));
numberDisplayed.delete(0,numberDisplayed.length());
break;
case R.id.buttonequal:
resultView.setText(String.valueOf(sum));
sum=0;
}
If I understand you correctly, you want the sum to show after you press the "equals" button. If so, then you need to have
sum += Double.parseDouble(String.valueOf(textView.getText()));
in this line also
case R.id.buttonequal:
sum += Double.parseDouble(String.valueOf(textView.getText()));
resultView.setText(String.valueOf(sum));
sum=0;
The second number isn't entered yet when you press the "plus" button so the sum is only the first number. Then you have to press it again to add to sum
So in if equals btn pressed, something like
if (lastOp.equals("sub")
{
sum -= Double.parseDouble(String.valueOf(textView.getText()));
...
}
Example
public class SimpleCalculatorActivity extends Activity
{
//variables needing class scope
double answer = 0, number1, number2;
int operator = 0, number;
boolean hasChanged = false, flag = false;
String display = null;
String display2 = null;
String curDisplay = null;
String calcString = "";
String inputLabel;
String inputString = null;
String inputString2 = null;
String inputString3 = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("Super Duper Calculator");
initButtons();
}
//when button is pressed, send num to calc function
button1.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button1.getText().toString();
displayCalc(inputString);
}
}
);
button2.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
inputString = button2.getText().toString();
displayCalc(inputString);
}
}
);
...
//send operator to calc function
addButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(1);
}
}
);
subButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(2);
}
}
);
calcButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(5);
}
}
);
clearButton.setOnClickListener
(new Button.OnClickListener()
{
public void onClick(View v)
{
calculation(6);
}
}
);
}
//function to calculate
public void calculation(int input)
{
number = input;
//see which operator was clicked
switch (number)
{
case 1:
operator = 1;
hasChanged = true;
display = "";
showDisplay("+");
break;
case 2:
operator = 2;
hasChanged = true;
display = "";
showDisplay("-");
break;
case 3:
operator = 3;
hasChanged = true;
display = "";
showDisplay("*");
break;
case 4:
operator = 4;
hasChanged = true;
display = "";
showDisplay("/");
break;
case 5:
number2 = Double.parseDouble(display2);
if(number2 == 0)
{
custErrMsg();
}
else
{
operator();
displayAnswer(answer);
hasChanged = true;
}
break;
case 6:
clear();
break;
default:
clear();
break;
}
}
private void operator()
{
if (operator != 0)
{
if (operator == 1)
{
answer = number1 + number2;
}
else if (operator == 2)
{
answer = number1 - number2;
}
else if (operator == 3)
{
answer = number1 * number2;
}
else if (operator == 4)
{
answer = number1 / (number2);
}
}
}
private void displayCalc(String curValue)
{
String curNum = curValue;
if (!hasChanged)
{
if (display == null)
{
//display number if reset
inputString2 = curNum;
display = inputString2;
showDisplay(display);
}
else
{
//display previous input + new input
inputString2 = inputString2 + curNum;
display = display + curNum;
showDisplay(display);
}
}
else
{
displayNum2(curNum);
}
}
private void displayNum2 (String curValue2)
{
String curNum2;
curNum2 = curValue2;
if (!flag)
{
//display number if reset
inputString3 = curNum2;
display2 = inputString3;
number1 = Double.parseDouble(inputString2);
flag = true;
}
else
{
//display previous input + new input
inputString3 = curNum2;
display2 = display2 + curNum2;
}
showDisplay(inputString3);
}
private void displayAnswer(double curAnswer)
{
String finAnswer = String.valueOf(curAnswer);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
textView1.setText(finAnswer);
}
private void showDisplay(String output)
{
inputLabel = output;
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setBackgroundColor(0xffffffff);
if (operator != 0)
{
curDisplay = textView1.getText().toString();
textView1.setText(curDisplay + inputLabel);
}
else
{
textView1.setText(inputLabel);
}
}