Using shared preferences to store high score - java

It gives me a error cannot resolve symbol sharedpreferences, I'm trying to add a high score for every time the user take the quiz it records the high score of the quiz. I dont know what happen. Please help me with this one and I'll help you with ur reputation.
package com.example.quiz;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
public class CS_Assembly_Easy extends Activity{
TextView topscore;
public static final String mypreference = "mypref";
public static final String Topscore = "topKey";
ArrayList<Question> quesList;
ArrayList<Question> toSelectFrom; // <--- HERE
int score = 0;
int qid = 0;
int lives = 5;
int round = 1;
int timer;
Question currentQ;
TextView txtQuestion, times, scored, livess, rounds;
Button button1, button2, button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_assembly_easy);
CS_Assembly_QuizHelper db = new CS_Assembly_QuizHelper(this); // my question bank class
quesList = db.getAllQuestions();
toSelectFrom = new ArrayList<Question>(); // <--- HERE
toSelectFrom.addAll(quesList); // <--- HERE
Random random = new Random();// this will fetch all quetonall questions
currentQ = toSelectFrom.get( random.nextInt(toSelectFrom.size())); // the current question <-- edited here too.
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <--- HERE
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// the textview in which will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
rounds = (TextView) findViewById(R.id.round);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
CounterClass timer = new CounterClass(60000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore) > score) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
public void Save(View view) {
String n = topscore.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Topscore, n);
editor.commit();
}
public void clear(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
topscore.setText("");
}
public void Get(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore)) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText(" Score : " + score);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.correct,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("CORRECT");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
} else if(lives > -10){
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.wrong,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("WRONG");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
else {
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
{
}
if (qid < 10) {
// if questions are not over then do this
Random random = new Random();
currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size())); // <<--- HERE
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <<--- AND HERE
setQuestionView();
round++;
rounds.setText(" Question:" + round + "/10");
} else {
// if over do this
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onBackPressed() {
return;
}
}

sharedpreferences is not defined in your CS_Assembly_Easy class.
Try changing your code to this:
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);

Related

SharedPreference not updating

SharedPreference not updating (changing). Please help. I'm a starter so I cannot figure it out. Please explain, not just code. Here is the MainActivity.java, where I need the preference and colorPicker.java, where I choose the color.
MainActivity.java:
package com.example.alexsoft.tictactoe;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
boolean turn = true;
int color = 0;
Button A1, B1, C1, A2, B2, C2, A3, B3, C3;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
A1 = (Button) findViewById(R.id.A1);
B1 = (Button) findViewById(R.id.B1);
C1 = (Button) findViewById(R.id.C1);
A2 = (Button) findViewById(R.id.A2);
B2 = (Button) findViewById(R.id.B2);
C2 = (Button) findViewById(R.id.C2);
A3 = (Button) findViewById(R.id.A3);
B3 = (Button) findViewById(R.id.B3);
C3 = (Button) findViewById(R.id.C3);
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
color = prefs.getInt("com.example.alexsoft.tictactoe", R.color.colorAccent);
changeAspect(color);
}
#Override
public void onResume() {
super.onResume();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
color = prefs.getInt("com.example.alexsoft.tictactoe", R.color.colorAccent);
changeAspect(color);
}
#Override
public void onStop() {
super.onStop();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
prefs.edit().putInt("com.example.alexsoft.tictactoe", color).apply();
}
#Override
public void onBackPressed() {
// super.onBackPressed();
//Creating an alert dialog to logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Do you want to exit?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
menu.getItem(1).setIcon(R.mipmap.ic_cached_white_24dp);
switch(Color.rgb(Color.red(color), Color.green(color), Color.blue(color))) {
case R.color.colorPrimary:
menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
case R.color.yellow:
menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
case R.color.lightBlue:
menu.getItem(1).setIcon(R.mipmap.ic_cached_black_24dp);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.resGame:
restartBtn();
return true;
case R.id.setAsp:
Intent it = new Intent(getBaseContext(), colorPicker.class);
startActivity(it);
return true;
case R.id.aboutBtn:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("About");
alertDialog.setMessage("Tic Tac Toe, verison 1.0, created by Alex Sandulescu");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
return true;
case R.id.resStats:
TextView xCount = (TextView) findViewById(R.id.xCount);
TextView oCount = (TextView) findViewById(R.id.oCount);
TextView roundsPlayed = (TextView) findViewById(R.id.roundsPlayed);
xCount.setText("0");
oCount.setText("0");
roundsPlayed.setText("0");
case R.id.cMode:
if (item.isChecked()) {
//item.setChecked(false);
AlertDialog nYet = new AlertDialog.Builder(MainActivity.this).create();
nYet.setMessage("Not ready yet!");
nYet.setTitle("Message");
nYet.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
nYet.show();
} else {
//item.setChecked(true);
AlertDialog nYet = new AlertDialog.Builder(MainActivity.this).create();
nYet.setMessage("Not ready yet!");
nYet.setTitle("Message");
nYet.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
nYet.show();
}
}
return false;
}
public void btnClick(View v) {
Button b = (Button) v;
if (b.isEnabled()) {
if (turn == true)
b.setText("X");
else
b.setText("0");
b.setEnabled(false);
turn = !turn;
checkForWinner();
}
}
private void checkForWinner() {
String winner = "";
boolean ok = false;
if (A1.getText().equals(B1.getText()) && A1.getText().equals(C1.getText()) && !A1.getText().equals("")) {
ok = true;
winner = A1.getText().toString();
A1.setTextColor(Color.RED);
B1.setTextColor(Color.RED);
C1.setTextColor(Color.RED);
} else if (A2.getText().equals(B2.getText()) && A2.getText().equals(C2.getText()) && !A2.getText().equals("")) {
ok = true;
winner = A2.getText().toString();
A2.setTextColor(Color.RED);
B2.setTextColor(Color.RED);
C2.setTextColor(Color.RED);
} else if (A3.getText().equals(B3.getText()) && A3.getText().equals(C3.getText()) && !A3.getText().equals("")) {
ok = true;
winner = A3.getText().toString();
A3.setTextColor(Color.RED);
B3.setTextColor(Color.RED);
C3.setTextColor(Color.RED);
} else if (A1.getText().equals(A2.getText()) && A1.getText().equals(A3.getText()) && !A1.getText().equals("")) {
ok = true;
winner = A1.getText().toString();
A1.setTextColor(Color.RED);
A2.setTextColor(Color.RED);
A3.setTextColor(Color.RED);
} else if (B1.getText().equals(B2.getText()) && B1.getText().equals(B3.getText()) && !B1.getText().equals("")) {
ok = true;
winner = B1.getText().toString();
B1.setTextColor(Color.RED);
B2.setTextColor(Color.RED);
B3.setTextColor(Color.RED);
} else if (C1.getText().equals(C2.getText()) && C1.getText().equals(C3.getText()) && !C1.getText().equals("")) {
ok = true;
winner = C1.getText().toString();
C1.setTextColor(Color.RED);
C2.setTextColor(Color.RED);
C3.setTextColor(Color.RED);
} else if (A1.getText().equals(B2.getText()) && A1.getText().equals(C3.getText()) && !A1.getText().equals("")) {
ok = true;
winner = A1.getText().toString();
A1.setTextColor(Color.RED);
B2.setTextColor(Color.RED);
C3.setTextColor(Color.RED);
} else if (A3.getText().equals(B2.getText()) && A3.getText().equals(C1.getText()) && !A3.getText().equals("")) {
ok = true;
winner = A3.getText().toString();
A3.setTextColor(Color.RED);
B2.setTextColor(Color.RED);
C1.setTextColor(Color.RED);
}
if (ok) {
Toast.makeText(this, winner + " won!", Toast.LENGTH_LONG).show();
if (winner.equals("X")) {
TextView tcount = (TextView) findViewById(R.id.xCount);
tcount.setText(Integer.toString(Integer.parseInt(tcount.getText().toString()) + 1));
} else {
TextView tcount = (TextView) findViewById(R.id.oCount);
tcount.setText(Integer.toString(Integer.parseInt(tcount.getText().toString()) + 1));
}
A1.setEnabled(false);
B1.setEnabled(false);
C1.setEnabled(false);
A2.setEnabled(false);
B2.setEnabled(false);
C2.setEnabled(false);
A3.setEnabled(false);
B3.setEnabled(false);
C3.setEnabled(false);
}
}
public void restartBtn() {
remakeGame();
TextView rplayed = (TextView) findViewById(R.id.roundsPlayed);
rplayed.setText(Integer.toString(Integer.parseInt(rplayed.getText().toString()) + 1));
}
private void remakeGame() {
A1.setText("");
B1.setText("");
C1.setText("");
A2.setText("");
B2.setText("");
C2.setText("");
A3.setText("");
B3.setText("");
C3.setText("");
//
A1.setTextColor(Color.BLACK);
B1.setTextColor(Color.BLACK);
C1.setTextColor(Color.BLACK);
A2.setTextColor(Color.BLACK);
B2.setTextColor(Color.BLACK);
C2.setTextColor(Color.BLACK);
A3.setTextColor(Color.BLACK);
B3.setTextColor(Color.BLACK);
C3.setTextColor(Color.BLACK);
//
A1.setEnabled(true);
B1.setEnabled(true);
C1.setEnabled(true);
A2.setEnabled(true);
B2.setEnabled(true);
C2.setEnabled(true);
A3.setEnabled(true);
B3.setEnabled(true);
C3.setEnabled(true);
//
turn = true;
}
public void changeAspect(int color) {
if (color != 0) {
A1.setBackgroundColor(color);
B1.setBackgroundColor(color);
C1.setBackgroundColor(color);
A2.setBackgroundColor(color);
B2.setBackgroundColor(color);
C2.setBackgroundColor(color);
A3.setBackgroundColor(color);
B3.setBackgroundColor(color);
C3.setBackgroundColor(color);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(color));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[2] *= 0.8f;
color = Color.HSVToColor(hsv);
window.setStatusBarColor(color);
}
}
}
}
colorPicker.java:
package com.example.alexsoft.tictactoe;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class colorPicker extends Activity {
public int color = 0;
String xCount, oCount, roundsPlayed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker);
}
public void onColorConfirm(View v) {
ImageView img = (ImageView) v;
ColorDrawable s = (ColorDrawable) img.getDrawable();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putInt("com.example.alexsoft.tictactoe", color).apply();
finish();
}
#Override
public void onStop() {
super.onStop();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
prefs.edit().putInt("com.example.alexsoft.tictactoe", color).apply();
}
}
The problem is you are not updating the value of color anywhere in your colorPicker activity. The value of color remains 0 all the time.
SOLUTION:
Update color value before storing it into SharedPreferences.
Update your code as below:
public class colorPicker extends Activity {
public int color = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_color_picker);
}
public void onColorConfirm(View v) {
ImageView img = (ImageView) v;
ColorDrawable s = (ColorDrawable) img.getDrawable();
SharedPreferences prefs = this.getSharedPreferences(
"com.example.alexsoft.tictactoe", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
// Update color value
color = SOME_VALUE;
// Store
ed.putInt("com.example.alexsoft.tictactoe", color).apply();
finish();
}
}
Hope this will help~

how to delay the process/incrementation in Android

I'm creating a android quiz application and what I want to do and know is how to delay the process or incrementation
i want to delay 2seconds before it adds another question
here is my code, i have qid++ there which will add question after the user answer a question. I want to delay it for 2 seconds.
package com.example.quiz;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class CS_Assembly_Easy extends Activity{
ArrayList<Question> quesList;
ArrayList<Question> toSelectFrom; // <--- HERE
int score = 0;
int qid = 0;
int lives = 5;
int round = 1;
int timer;
Question currentQ;
TextView txtQuestion, times, scored, livess, rounds;
Button button1, button2, button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_assembly_easy);
CS_Assembly_QuizHelper db = new CS_Assembly_QuizHelper(this); // my question bank class
quesList = db.getAllQuestions();
toSelectFrom = new ArrayList<Question>(); // <--- HERE
toSelectFrom.addAll(quesList); // <--- HERE
Random random = new Random();// this will fetch all quetonall questions
currentQ = toSelectFrom.get( random.nextInt(toSelectFrom.size())); // the current question <-- edited here too.
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <--- HERE
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
livess = (TextView) findViewById(R.id.livess);
// the textview in which will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
rounds = (TextView) findViewById(R.id.round);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
CounterClass timer = new CounterClass(60000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
}
public void getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText(" Score : " + score);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.correct,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("CORRECT");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
} else if(lives > 1){
lives--;
livess.setText("Lives: " + lives);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.wrong,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("WRONG");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
else {
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
{
}
if (qid < 10) {
// if questions are not over then do this
Random random = new Random();
currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size())); // <<--- HERE
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <<--- AND HERE
setQuestionView();
round++;
rounds.setText(" Question:" + round + "/10");
} else {
// if over do this
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onBackPressed() {
return;
}
}
You might try scheduling a Runnable with Handler.postDelayed(runnable, timeInMilliseconds)
Put the code that should be delayed inside a Runnable.run() method like this:
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// TODO your code here
}
}, 2000L);
See this link Android sleep() without blocking UI
you can use :
handler=new Handler();
Runnable r=new Runnable() {
public void run() {
//your code here
}
};
handler.postDelayed(r, 2000); // waiting for 2s

Android CountDown Timer in Quiz Application

I have made a quiz application which include 5 questions. I have made a ResultActivity page which displays result of the quiz.
I have added a countDown timer of 20 sec for each question. When the Countdown timer finishes it moves to the next question automatically. When the questions are finished it should move to the ResultActivity page to display result.
I have only one issue...
Afetr reaching my last Question..if i does not select any answer and timer is finished the applicaton is not moving to my ResultActivity page..The timer is getting started again and again on the same question until i select any option
Here is my code:
QuizActivity.java
package com.example.triviality;
import java.util.LinkedHashMap;
import java.util.List;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends Activity {
List<question> quesList;
public static int score, correct, wrong, wronganswers;
public boolean isCorrect;
static int qid = 0;
int totalCount = 5;
Question currentQ;
TextView txtQuestion;
RadioGroup radioGroup1;
RadioButton rda, rdb, rdc;
Button butNext;
TextView rt;
boolean nextFlag = false;
boolean isTimerFinished = false;
static LinkedHashMap lhm = new LinkedHashMap();
MyCountDownTimer countDownTimer = new MyCountDownTimer(10000 /* 20 Sec */,
1000);
// final MyCountDownTimer timer = new MyCountDownTimer(20000,1000);
public static String[] Correctanswers = new String[5];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
DbHelper db = new DbHelper(this);
quesList = db.getAllQuestions();
currentQ = quesList.get(qid);
txtQuestion = (TextView) findViewById(R.id.textView1);
rda = (RadioButton) findViewById(R.id.radio0);
rdb = (RadioButton) findViewById(R.id.radio1);
rdc = (RadioButton) findViewById(R.id.radio2);
butNext = (Button) findViewById(R.id.button1);
// radioGroup1=(RadioGroup)findViewById(R.id.radioGroup1);
setQuestionView();
// timer.start();
rt = (TextView) findViewById(R.id.rt);
rt.setText("20");
countDownTimer.start();
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countDownTimer.cancel();
if (getNextQuestion(false)) {
// Start The timer again
countDownTimer.start();
}
}
});
}
private void setQuestionView() {
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
Log.e("Times up", "Times up");
countDownTimer.cancel();
if (getNextQuestion(false)) {
// Start The timer again
countDownTimer.start();
}
}
#Override
public void onTick(long millisUntilFinished) {
rt.setText((millisUntilFinished / 1000) + "");
Log.e("Second Gone", "Another Second Gone");
Log.e("Time Remaining", "seconds remaining: " + millisUntilFinished
/ 1000);
}
}
boolean getNextQuestion(boolean c) {
nextFlag = true;
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
// grp.clearCheck();
RadioButton answer = (RadioButton) findViewById(grp
.getCheckedRadioButtonId());
if (rda.isChecked() || rdb.isChecked() || rdc.isChecked()) {
qid++;
Log.d("yourans", currentQ.getANSWER() + " " + answer.getText());
grp.clearCheck();
// wronganswers=
if (!c && currentQ.getANSWER().equals(answer.getText())) {
correct++;
} else {
lhm.put(currentQ.getQUESTION(), currentQ.getANSWER());
wrong++;
}
if (qid < 5) {
currentQ = quesList.get(qid);
setQuestionView();
} else {
score = correct;
Intent intent = new Intent(QuizActivity.this,
ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next Intent
startActivity(intent);
return false;
}
} else {
lhm.put(currentQ.getQUESTION(), currentQ.getANSWER());
qid++;
if (qid < 5) {
currentQ = quesList.get(qid);
//currentQ.getANSWER().equals(wrong);
wrong++;
Log.e("yourans", currentQ.getANSWER());
setQuestionView();
}
// wrong++;
// Log.e("Without Any Selection ", "without "+wrong);
// Toast.makeText(getApplicationContext(),
// "Please select atleast one Option",Toast.LENGTH_SHORT).show();
}
return true;
}
}
ResultActivity.java:
package com.example.triviality;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ResultActivity extends Activity {
Button restart;
Button check;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
TextView t=(TextView)findViewById(R.id.textResult);
TextView t1=(TextView)findViewById(R.id.textResult1);
TextView t2=(TextView)findViewById(R.id.textResult2);
restart=(Button)findViewById(R.id.restart);
check=(Button)findViewById(R.id.check);
StringBuffer sb=new StringBuffer();
sb.append("Correct ans: "+QuizActivity.correct+"\n");
StringBuffer sc=new StringBuffer();
sc.append("Wrong ans : "+QuizActivity.wrong+"\n");
StringBuffer sd=new StringBuffer();
sd.append("Final Score : "+QuizActivity.score);
t.setText(sb);
t1.setText(sc);
t2.setText(sd);
QuizActivity.correct=0;
QuizActivity.wrong=0;
check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in=new Intent(getApplicationContext(),CheckActivity.class);
startActivity(in);
}
});
restart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//QuizActivity quiz=new QuizActivity();
// TODO Auto-generated method stub
Intent intent=new Intent(getApplicationContext(),QuizActivity.class);
QuizActivity.lhm.clear();
QuizActivity.qid=0;
startActivity(intent);
//quiz.countDownTimer.onTick(19);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_result, menu);
return true;
}
}
This is because Your return false statement will never be reached if the user has made no choice:
if (rda.isChecked() || rdb.isChecked() || rdc.isChecked()){}
in this if else statement You will return false later. But if none is selected, You automatically will return true because the code block inside this statement above will not be rached. And then in Your timer You say:
if (getNextQuestion(false)) {
// Start The timer again
countDownTimer.start();
}
getNextQuestion is allways true if the user makes no choice, so the timer starts again and again.

Eclipse(Android) - unfortunately HelloWorld has stopped working

I get that error message everytime I try running my program. I have a fairly simple program, with two buttons. If you press one button it subtracts 1 from a number. If you press the add button it adds 1 to the number. I have no compiling errors and I'm fairly new to android. Any help would be great... Thanks!
Here is my code: (The main activity).
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView numberText = (TextView) findViewById(R.id.number);
numberText.setText(String.valueOf(0));
Button.OnClickListener listenerAdd = new Button.OnClickListener() {
#Override
public void onClick(View v) {
TextView numberText = (TextView) findViewById(R.id.number);
switch(v.getId()) {
case R.id.HomeScreenChangeAdd: {
String currText = numberText.getText().toString();
int curNumb = Integer.parseInt(currText);
int newNumb = curNumb +1;
String newText = String.valueOf(newNumb);
numberText.setText(newText);
break;
}
}
}
};
Button.OnClickListener listenerSub = new Button.OnClickListener() {
#Override
public void onClick(View v) {
TextView numberText = (TextView) findViewById(R.id.number);
switch(v.getId()) {
case R.id.HomeScreenChangeSub: {
String currText = numberText.getText().toString();
int curNumb = Integer.parseInt(currText);
int newNumb = curNumb -1;
String newText = String.valueOf(newNumb);
numberText.setText(newText);
break;
}
}
}
};
((Button) findViewById(R.id.HomeScreenChangeAdd)).setOnClickListener(listenerAdd);
((Button) findViewById(R.id.HomeScreenChangeSub)).setOnClickListener(listenerSub);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Make sure
R.id.number,
R.id.HomeScreenChangeAdd, and
R.id.HomeScreenChangeSub
are included in R.layout.activity_main.
There is nothing else in your code that could crash the app at startup.

How to count number of asked questions?

I have this activity with question and 4 possible answers, and after each user answer it reloads itself with another question. I placed a textView in the bottom right corner with start value of 1/10 (rezultat.setText(counter+"/10");). I want to increase that value to 2/10, 3/10 and so on, after each question, but I don't know where to put counter++; in my code, and I tried everywhere. Here's my code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class Kviz extends Activity implements View.OnClickListener{
Runnable mLaunchTask = new Runnable() {
public void run() {
startActivity(getIntent());
}
};
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
finish();
}
};
Button bIzlazIzKviza, bOdgovor1, bOdgovor2, bOdgovor3, bOdgovor4;
TextView question, proba, rezultat;
int counter = 1;
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
mHandler.postDelayed(mLaunchTaskFinish, 1200);
mHandler.postDelayed(mLaunchTask,1000);
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
}else{
mHandler.postDelayed(mLaunchTaskFinish, 2200);
mHandler.postDelayed(mLaunchTask,2000);
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.POGRESANODGOVOR");
startActivity(i);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.kviz);
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanje = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
bIzlazIzKviza = (Button) findViewById(R.id.bIzlazIzKviza);
rezultat = (TextView) findViewById(R.id.tvBrojPitanja);
question = (TextView) findViewById(R.id.tvPitanje);
bOdgovor1 = (Button) findViewById(R.id.bOdgovor1);
bOdgovor2 = (Button) findViewById(R.id.bOdgovor2);
bOdgovor3 = (Button) findViewById(R.id.bOdgovor3);
bOdgovor4 = (Button) findViewById(R.id.bOdgovor4);
bOdgovor1.setTypeface(dugmad);
bOdgovor2.setTypeface(dugmad);
bOdgovor3.setTypeface(dugmad);
bOdgovor4.setTypeface(dugmad);
bIzlazIzKviza.setTypeface(dugmad);
rezultat.setTypeface(dugmad);
question.setTypeface(pitanje);
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getTestData();
question.setText(c.getString(1));
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
Collections.shuffle(labels);
bOdgovor1.setText(labels.get(0).option);
bOdgovor1.setTag(labels.get(0));
bOdgovor1.setOnClickListener(clickListener);
bOdgovor2.setText(labels.get(1).option);
bOdgovor2.setTag(labels.get(1));
bOdgovor2.setOnClickListener(clickListener);
bOdgovor3.setText(labels.get(2).option);
bOdgovor3.setTag(labels.get(2));
bOdgovor3.setOnClickListener(clickListener);
bOdgovor4.setText(labels.get(3).option);
bOdgovor4.setTag(labels.get(3));
bOdgovor4.setOnClickListener(clickListener);
rezultat.setText(counter+"/10");
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
bIzlazIzKviza.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void onClick(View v) {
}
}
what is the mean of "each user answer it reloads itself with another question." ? Are you using different Activities for diff question ?
You can use same activity for all the questions, when user press any of answer's button, just call a method
public void nextQuestion() {
counter++;
question.setText("");
bOdgovor1.setText("");
bOdgovor2.setText("");
bOdgovor3.setText("");
bOdgovor4.setText("");
//reset your next question and all four options here
rezultat.setText(counter + "/10");
}
It's hard to test from here, but it looks like adding counter++ before the line
Answer ans = (Answer) v.getTag();
Should work fine, as this sets counter to increment whenever the button that seems to be responsible for answering questions is clicked. Remember that you'll also need to call
rezultat.setText(counter+"/10");
Again, to update the text to reflect the new value of counter.
To expand my problem a little bit. I did manage to count questions with counter class, it goes to 2/10, but because I reload my activity after each question, my textView also reloads to 1/10. I think that's the main cause of my problem.

Categories