package com.example.my.galgu;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
long first=1, second=1, answer;
boolean a=false ,s=false ,m=false ,d=false;
int i=0;
String wholesome, goti;
Button ba, bs, bm, bd, be;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
ba = (Button) findViewById(R.id.ba);
bs = (Button) findViewById(R.id.bs);
bm = (Button) findViewById(R.id.bm);
bd = (Button) findViewById(R.id.bd);
be = (Button) findViewById(R.id.be);
be.setEnabled(false);
}
public void disable(){
ba.setEnabled(false);
bs.setEnabled(false);
bm.setEnabled(false);
bd.setEnabled(false);
}
A method for each of the buttons from one to zero.
The problem lies somewhere in the below method where the first and second
are stored. The method first checks if any of the +,-,*,/ buttons are
pressed and then stores the value in either the first or second variable.
The last digit for the first variable is omitted. And I can't say why.
public void onone(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 1;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("1");
else{
textView.setText(wholesome + "1");
}
}
public void ontwo(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 2;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("2");
else{
textView.setText(wholesome + "2");
}
}
public void onthree(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 3;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("3");
else{
textView.setText(wholesome + "3");
}
}
public void onfour(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 4;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("4");
else{
textView.setText(wholesome + "4");
}
}
public void onfive(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 5;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("5");
else{
textView.setText(wholesome + "5");
}
}
public void onsix(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 6;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("6");
else{
textView.setText(wholesome + "6");
}
}
public void onseven(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 7;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("7");
else{
textView.setText(wholesome + "7");
}
}
public void oneight(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 8;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("8");
else{
textView.setText(wholesome + "8");
}
}
public void onnine(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 9;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("9");
else{
textView.setText(wholesome + "9");
}
}
public void onzero(View view){
if(a||s||m||d){
second *= i;
i = i * 10;
second += 1;
}else{
first = Integer.parseInt(textView.getText().toString());
}
wholesome = textView.getText().toString();
if(wholesome.equals("0"))
textView.setText("0");
else{
textView.setText(wholesome + "0");
}
}
public void ona(View view){
a = true;
wholesome = textView.getText().toString();
textView.setText(wholesome + "+");
disable();
be.setEnabled(true);
}
public void ons(View view){
s = true;
wholesome = textView.getText().toString();
textView.setText(wholesome + "-");
disable();
be.setEnabled(true);
}
public void onm(View view){
m = true;
wholesome = textView.getText().toString();
textView.setText(wholesome + "*");
disable();
be.setEnabled(true);
}
public void ond(View view){
d = true;
wholesome = textView.getText().toString();
textView.setText(wholesome + "/");
disable();
be.setEnabled(true);
}
public void one(View view){
if(a){
answer = first + second;
}
else if (s){
answer = first - second;
}
else if (m){
answer = first * second;
}
else if (d){
answer = first / second;
}
goti = String.valueOf(answer);
textView.setText(goti);
second = 1;
i = 0;
a = false;
s = false;
m = false;
d = false;
ba.setEnabled(true);
bs.setEnabled(true);
bm.setEnabled(true);
bd.setEnabled(true);
}
public void once(View view){
textView.setText("0");
second = 1;
i = 0;
ba.setEnabled(true);
bs.setEnabled(true);
bm.setEnabled(true);
bd.setEnabled(true);
be.setEnabled(false);
a = false;
s = false;
m = false;
d = false;
}
}
Related
I'm almost new to android and trying to write a calculator code.
It's almost done but I want to try some other options for that
when I repeat clicking on equal button,I want to repeat last calculation entered.for example 3+5=8 then if I click on exe button again it would be 13(3+5+5)
and so on(18,23,...)
Also I have problem with entering more than two numbers.for example when I enter (4+5+6)and then click equal the answer will appear 11 and just calculates last two numbers entered.I want it to show the result of first two numbers then get other numbers.example:for(2+3*4-5/)->the output will be equal to (5->20->15)
Here is my code;If any one can help,I will be grateful! :) thanks
package com.example.sony.calculator;
public class MainActivity extends AppCompatActivity {
Float firstNumber,secondNumber,result;
Float thirdNumber;
TextView display;
Button one,two,three,four,five,six,seven,eight,nine,zero,exe,clear,multiply,divide,sum,minus;
boolean isSum,isMinus,isMultiply,isDivide,isEqual;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (TextView) findViewById(R.id.khali);
one = (Button) findViewById(R.id.adade1);
two = (Button) findViewById(R.id.adade2);
three = (Button) findViewById(R.id.adade3);
four = (Button) findViewById(R.id.adade4);
five = (Button) findViewById(R.id.adade5);
six = (Button) findViewById(R.id.adade6);
seven = (Button) findViewById(R.id.adade7);
eight = (Button) findViewById(R.id.adade8);
nine = (Button) findViewById(R.id.adade9);
zero = (Button) findViewById(R.id.adade0);
multiply = (Button) findViewById(R.id.zarb);
divide = (Button) findViewById(R.id.taghsim);
sum = (Button) findViewById(R.id.jam);
minus = (Button) findViewById(R.id.menha);
exe = (Button) findViewById(R.id.mosavi);
clear = (Button) findViewById(R.id.pak);
final Button[] operators = new Button[5];
operators[0] = multiply;
operators[1] = divide;
operators[2] = sum;
operators[3] = minus;
operators[4] = exe;
final Button[] numbers = new Button[10];
numbers[0] = zero;
numbers[1] = one;
numbers[2] = two;
numbers[3] = three;
numbers[4] = four;
numbers[5] = five;
numbers[6] = six;
numbers[7] = seven;
numbers[8] = eight;
numbers[9] = nine;
for (int a = 0; a < 10; a++) {
final int finalA = a;
numbers[a].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display.setText(display.getText().toString() + String.valueOf(finalA));
}
});
}
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display.setText("");
}
});
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText() == "") {
display.setText("");
return;
}
else{
firstNumber = parseFloat(display.getText().toString());
isSum=true;
display.setText("");
return;
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText()==""){
display.setText("");
}else {
firstNumber = parseFloat(display.getText().toString());
isMinus = true;
display.setText("");
}
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText()==""){
Toast Error1=Toast.makeText(MainActivity.this,"Error;Please enter right format",Toast.LENGTH_SHORT);
Error1.show();
}else {
firstNumber = parseFloat(display.getText().toString());
isMultiply = true;
display.setText("");
}
}
});
divide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText() == "") {
Toast Error1 = Toast.makeText(MainActivity.this, "Error;Please enter right format", Toast.LENGTH_SHORT);
Error1.show();
} else {
firstNumber = parseFloat(display.getText().toString());
isDivide = true;
display.setText("");
}
}
});
exe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isEqual=true;
if (display.getText() == "") {
display.setText("");
}
else {
secondNumber = parseFloat(display.getText().toString());
if (isSum == true) {
result = firstNumber + secondNumber ;
display.setText(String.valueOf(result));
isSum=false;
return;
}
if (isMinus == true) {
result = firstNumber - secondNumber;
display.setText(String.valueOf(result));
isMinus = false;
return;
}
if (isDivide == true) {
result = firstNumber / secondNumber;
display.setText(String.valueOf(result));
isDivide = false;
return;
}
if (isMultiply == true) {
result = firstNumber * secondNumber;
display.setText(String.valueOf(result));
isMultiply=false;
return;
}
}
}
});
}
}
I am building a little quiz app and let's say on Question 1, I select option B, then submit and the quiz gives me the next question. However for question 2 if I try to select B, the RadioButton quickly unchecks itself and it is completely uncheckable, until I select another radio button and then try B again. The pattern is, whatever option I selected in the previous question, is uncheckable in the next question unless I click on a different radiobutton and then try again. I'm attaching my code. Any help please?
public class MainActivity extends AppCompatActivity {
QuestionBank allQuestions = new QuestionBank();
String pickedAnswer = "", correctAnswer = "";
final int numberOfQuestions = allQuestions.list.size();
int questionNumber = 0;
boolean noSelection = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextQuestion();
}
private void nextQuestion() {
if (questionNumber <= numberOfQuestions - 1) {
TextView questionLabel = (TextView) findViewById(R.id.question_text_view);
String fullQuestion = allQuestions.list.get(questionNumber).questionSet.get("question").toString();
fullQuestion += "\n\na) " + allQuestions.list.get(questionNumber).questionSet.get("a");
fullQuestion += "\nb) " + allQuestions.list.get(questionNumber).questionSet.get("b");
fullQuestion += "\nc) " + allQuestions.list.get(questionNumber).questionSet.get("c");
fullQuestion += "\nd) " + allQuestions.list.get(questionNumber).questionSet.get("d");
correctAnswer = allQuestions.list.get(questionNumber).questionSet.get("answer").toString();
questionLabel.setText(fullQuestion);
questionNumber++;
} else {
restart();
}
}
public void getSelectedAnswer() {
RadioButton radio_1 = (RadioButton) findViewById(R.id.option1_button);
RadioButton radio_2 = (RadioButton) findViewById(R.id.option2_button);
RadioButton radio_3 = (RadioButton) findViewById(R.id.option3_button);
RadioButton radio_4 = (RadioButton) findViewById(R.id.option4_button);
if (radio_1.isChecked()) {
pickedAnswer = "a";
radio_1.setChecked(false);
} else if (radio_2.isChecked()) {
pickedAnswer = "b";
radio_2.setChecked(false);
} else if (radio_3.isChecked()) {
pickedAnswer = "c";
radio_3.setChecked(false);
} else if (radio_4.isChecked()) {
pickedAnswer = "d";
radio_4.setChecked(false);
} else {
noSelection = true;
}
}
public void submitAnswer(View view) {
getSelectedAnswer();
if (noSelection) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Please select an answer!");
a_builder.show();
noSelection = false;
} else {
checkAnswer();
nextQuestion();
}
}
public void checkAnswer() {
if (correctAnswer == pickedAnswer) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Right Answer!");
a_builder.show();
} else {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Wrong Answer!");
a_builder.show();
}
pickedAnswer = "";
correctAnswer = "";
}
public void restart() {
questionNumber = 0;
//Collections.shuffle(allQuestions.list);
nextQuestion();
}
}
call setChecked(false) on all the buttons after submitting or before showing next question
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);
}
});
}
}
After each trivia game is over, the Results page displays. After about 20 seconds, which is how long each question gives you during the game before your time runs out and it goes to the next question, the Results page reloads. Then when you go to the Highscores page, the score has been entered twice. So something is screwed up in my QuestionView class below but I cannot find the bug.
If any further information is needed let me know. Thank you in advanced!
Results.java
total_score = dh.calculateTotalScore(score, percentage);
if(dh.getLowest() == -1) {
dh.insert(score, percentage, total_score, category);
} else {
dh.delete(dh.getLowest());
dh.insert(score, percentage, total_score, category);
}
DatabaseHelper.java
public long insert(long score, int percentage, long total_score, String category) {
ContentValues values = new ContentValues();
values.put(SCORE, score);
values.put(PERCENTAGE, percentage);
values.put(TOTAL_SCORE, total_score);
values.put(CATEGORY, category);
return db.insert(TABLE, null, values);
}
public void delete(long lowScore) {
lowScore = getLowest();
db.delete(TABLE, TOTAL_SCORE + "=" + lowScore, null);
}
public long getLowest() {
Cursor c = db.rawQuery("SELECT * FROM " + TABLE + " ORDER BY " + TOTAL_SCORE, null);
long count = c.getCount();
long lowScore = -1;
if(count == 10) {
c.moveToLast();
lowScore = c.getInt(c.getColumnIndex(TOTAL_SCORE));
}
return lowScore;
}
public long calculateTotalScore(long score, int percentage) {
long i;
return i = (percentage * 1000) + score;
}
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter;
ArrayList<Question> queries;
Timer cdTimer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
pointCounter = (TextView)findViewById(R.id.timer);
questionNumber = (TextView)findViewById(R.id.timeElapsedView);
timeCounter = (TextView)findViewById(R.id.timeCounter);
cdTimer = new Timer(startTime, interval);
loadQuestion();
}
public void loadQuestion() {
if(i == 10) {
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(1);
if(answer == 1) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(2);
if(answer == 2) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(3);
if(answer == 3) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public void nextQuestion() {
score = score + points;
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
if(i >= 9) {
cdTimer.cancel();
endQuiz();
} else {
wrongAnswers++;
nextQuestion();
}
}
#Override
public void onTick(long millisUntilFinished) {
timeCounter.setText("Time remaining: " + (millisUntilFinished / 100));
points = (millisUntilFinished / 100) / 2;
pointCounter.setText("Points remaining: " + points);
if(i < 10) {
questionNumber.setText("Question " + (i + 1) + " of 10");
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
THE FIX:
Changed:
if(i == 10) {
endQuiz();
}
...to this:
if(i == 10) {
cdTimer.cancel();
endQuiz();
}**
Probably endQuiz gets called twice. And only when you answer the last question before the timer is up.
Because, I don't see you canceling the timer when you answer the last question. So, even though you answered already, the timer is still ticking, and when it is up, it will call endQuiz.
If you don't answer the last question and let the time run out, then the result will be inserted only once, because endQuiz will be called only once, from the timer.
I'm building an application that makes piechart from database according to precise date interval. Unfortunately the achartengine's repaint function is not working when I'm stepping with the buttons.
When the Activity starts everything is fine the chart is okay but when i'm using the buttons then nothing happens.
I hope somebody can help me.
here is the code:
private GraphicalView chartView;
...
tabHost.addTab(tabHost.newTabSpec("").setIndicator("Grafikon")
.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String arg0) {
final View view = LayoutInflater.from(SumMenuActivity.this).inflate(
R.layout.summenu_tab3, null);
periodSeekBar = (SeekBar) view.findViewById(R.id.summenutab3_periodslide);
final TextView periodName = (TextView) view
.findViewById(R.id.summenutab3_periodtw);
if (chartView == null) {
LinearLayout layout = (LinearLayout) view.findViewById(R.id.chart);
intValChanger(intVal, 0);
layout.addView(chartView);
} else {
chartView.repaint();
}
periodSeekBar
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (progress == 0) {
periodName.setText("Heti");
} else if (progress == 1) {
periodName.setText("Havi");
} else if (progress == 2) {
periodName.setText("Eves");
}
intVal = 0;
intValChanger(intVal, progress);
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
final View minusButton = view.findViewById(R.id.summenutab3_frombutton);
final View plusButton = view.findViewById(R.id.summenutab3_tobutton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intVal--;
intValChanger(intVal, periodSeekBar.getProgress());
if (chartView != null) {
chartView.refreshDrawableState();
chartView.repaint();
}
}
});
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intVal++;
intValChanger(intVal, periodSeekBar.getProgress());
if (chartView != null) {
chartView.refreshDrawableState();
chartView.repaint();
}
}
});
return view;
}
...
public void intValChanger(int intVal, int type) {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
if (type == 0) {
start.setFirstDayOfWeek(Calendar.MONDAY);
end.setFirstDayOfWeek(Calendar.MONDAY);
int currentStartOfWeek = (start.get(Calendar.DAY_OF_WEEK) + 7 - start
.getFirstDayOfWeek()) % 7;
int currentEndOfWeek = (end.get(Calendar.DAY_OF_WEEK) + 7 - end.getFirstDayOfWeek()) % 7;
start.add(Calendar.DAY_OF_YEAR, -currentStartOfWeek + intVal * 7);
end.add(Calendar.DAY_OF_YEAR, (-currentEndOfWeek + intVal * 7) + 6);
} else if (type == 1) {
start.set(Calendar.DATE, 1);
start.set(Calendar.MONTH, start.get(Calendar.MONTH) + 1 * intVal);
end.set(Calendar.DATE, start.getActualMaximum(Calendar.DATE));
end.set(Calendar.MONTH, end.get(Calendar.MONTH) + 1 * intVal);
} else if (type == 2) {
start.set(Calendar.YEAR, start.get(Calendar.YEAR) + 1 * intVal);
start.set(Calendar.MONTH, 0);
start.set(Calendar.DATE, 1);
end.set(Calendar.YEAR, end.get(Calendar.YEAR) + 1 * intVal);
end.set(Calendar.MONTH, 11);
end.set(Calendar.DATE, 31);
}
if (tabHost.getCurrentTab() == 0) {
populateTimeList(start.getTime(), end.getTime());
} else if (tabHost.getCurrentTab() == 1) {
populateSumArrayList(start.getTime(), end.getTime());
} else if (tabHost.getCurrentTab() == 2) {
populateChart(start.getTime(), end.getTime());
}
Toast.makeText(getApplicationContext(),
android.text.format.DateFormat.format("yyyy-MM-dd", start) +
"-tól " + android.text.format.DateFormat.format("yyyy-MM-dd", end)
+ "-ig", 3).show();
}
public GraphicalView executeChart(Context context, ArrayList<String> name,
ArrayList<Integer> value) {
ArrayList<Integer> colors = new ArrayList<Integer>();
CategorySeries categorySeries = new CategorySeries("Torta diagram");
for (int i = 0; i < name.size(); i++) {
Random r = new Random();
categorySeries.add(name.get(i), value.get(i));
colors.add(Color.rgb(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
}
DefaultRenderer renderer = buildCategoryRenderer(colors);
renderer.setLabelsTextSize(14);
GraphicalView gview = ChartFactory.getPieChartView(context,
categorySeries, renderer);
return gview;
}
protected DefaultRenderer buildCategoryRenderer(ArrayList<Integer> colors) {
DefaultRenderer renderer = new DefaultRenderer();
for (int color : colors) {
SimpleSeriesRenderer r = new SimpleSeriesRenderer();
r.setColor(color);
renderer.addSeriesRenderer(r);
}
return renderer;
}
public void populateChart(Date from, Date to) {
ArrayList<String> tmpName = new ArrayList<String>();
ArrayList<Integer> tmpValue = new ArrayList<Integer>();
ArrayList<Category> tmpCategory = getCategories();
ArrayList<Transaction> tmpTransaction = new ArrayList<Transaction>();
for (int i = 0; i < tmpCategory.size(); i++) {
tmpName.add(tmpCategory.get(i).getName());
tmpTransaction = (ArrayList<Transaction>) getTransactionsByTimeIntvalAndId(from, to,
tmpCategory.get(i).getId());
int ammount = 0;
for (int j = 0; j < tmpTransaction.size(); j++) {
ammount += tmpTransaction.get(j).getAmmount();
}
tmpValue.add(ammount);
}
for (int i = 0; i < tmpName.size(); i++) {
Log.d("DEBUG MESSAGE", tmpName.get(i) + ": " + tmpValue.get(i));
}
chartView = null;
chartView = executeChart(SumMenuActivity.this, tmpName, tmpValue);
Log.d("DEBUG MESSAGE", "megtörtént a repaint!" + chartView);
}
I have not used Achart but this is a simple pie chart implementation. You can refer the demo and it might help.
In this demo after you update the values, you need to call invalidate() to redraw the pie chart.
https://github.com/blessenm/PieChartDemo