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
Related
I'm currently learning android app development and on the very beginning phase. I built this game and now i want to set store and display high score as Textview on my screen. I'd really appreciate if anyone could help me out. thanks!
package com.princeghimire.clickmeter;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
TextView tv_time, tv_clicks;
Button b_start, b_click;
CountDownTimer timer;
int time = 10;
int clicks = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setLogo(R.drawable.iconnn);
getSupportActionBar().setDisplayUseLogoEnabled(true);
tv_time = (TextView) findViewById(R.id.tv_time);
tv_clicks = (TextView) findViewById(R.id.tv_clicks);
b_start = (Button) findViewById(R.id.b_start);
b_click = (Button) findViewById(R.id.b_click);
b_start.setEnabled(true);
b_click.setEnabled(false);
timer = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
time--;
tv_time.setText("Time: " + time);
}
#Override
public void onFinish() {
b_start.setEnabled(true);
b_click.setEnabled(false);
tv_time.setText("Time: 10" );
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Time's Up Buddy!");
builder.setMessage("Your Score Is: " + clicks);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
// finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
};
b_click.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
clicks++;
// switchh.start();
tv_clicks.setText("Your Clicks: " + clicks);
}
});
b_start.setOnClickListener(new View.OnClickListener(){
public void onClick (View v){
timer.start();
b_start.setEnabled(false);
b_click.setEnabled(true);
clicks = 0;
time = 10;
tv_time.setText("Time: " + time);
tv_clicks.setText("Your Clicks: " + clicks);
}
});
}
public void onBackPressed()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to EXIT?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
Basically this is the procedure:
Create instance of SharedPreferences and SharedPreferences.Edit SharedPreferences sharedPref = .... AND SharedPreferences.Edit editor = .....
Call this in where your game ends if (sharedPref.getInt("highscore",0) < clicks) { editor.putInt("highscore",clicks).apply() }
The above code will first check the last score you saved in "highscore" key and if your current clicks is higher it will replace it with it, and if this is the first game so the default value will be taken as 0 so the first game's score will be saved as highscore unless its 0 again.
I've made almost the same game, its Taplay and on PlayStore btw.
Good Luck.
You can use SharedPreferences, I suggest you to use Sqlite if you want to keep track of the user game statistics.
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);
on the homepage of my app i have edittexts that represent counters for each row in my list. whenever i change activity and return back to my main screen all the numbers disappear, the same happens when I close the app and open it again. How do i make the numbers stay?
My main activity where I call the row layout with the edittexts
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MyActivity extends Activity implements MyAdapterInterface{
private CustomCursorAdapter customAdapter;
public ListView list1;
//instantiating the database class
com.example.rory.dripdrop.DBAdapter db = new com.example.rory.dripdrop.DBAdapter(this);
public MyActivity mMyActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
mMyActivity = this;
//button and listener for add activity
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Add.class);
startActivity(i);
}
});
//button and listener for delete activity
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
//button and listener for update activity
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//handler function for custom adapter, found example online to help with this
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
list1.setAdapter(customAdapter);
}
});
}
public void onResume()
{
super.onResume();
//update list
addData();
}
//refreshes data base when main page is resumed
public void addData()
{
//handler function for custom adapter, found example online to help with this
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
list1.setAdapter(customAdapter);
}
});
}
//chaning the running total
public void updateLitres(int value)
{
EditText editLitres = (EditText)findViewById(R.id.edit1);
//EditText myEditText2 = (EditText)findViewById(R.id.edit2);
editLitres.setText(String.valueOf(value));
//myEditText2.setText(String.valueOf(value));
}
public void updateCost(double value)
{
EditText editCost = (EditText)findViewById(R.id.edit2);
String.format("%.2f", value);
editCost.setText("€" + String.valueOf(value));
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
My custom adapter for the rows
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomCursorAdapter extends CursorAdapter {
//public int counter = 0;
public ArrayList<Integer> counter;
public ArrayList<Integer> counter2;
private MyAdapterInterface mMyInterface;
public CustomCursorAdapter(Context context, Cursor cursor, MyAdapterInterface myInterface) {
//instantiating the values
super(context, cursor);
this.context = context;
this.mMyInterface = myInterface;
//array to sort each value per row
counter = new ArrayList<Integer>();
counter2 = new ArrayList<Integer>();
//default all counters to 0
for(int i=0; i<cursor.getCount(); i++)
{
counter.add(0);
counter2.add(0);
}
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, final Cursor cursor) {
//getting the first value for the custom row (the item name)
TextView textViewItemName = (TextView) view.findViewById(R.id.item1);
textViewItemName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final int litres = Integer.parseInt(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
//editText for custom row
final EditText runningTotal = (EditText) view.findViewById(R.id.runningTotal);
//setting up the plus button
final Button plusButton = (Button)view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos;
private int counter2;
public void onClick(View v) {
//code to change the value of the editText and the array, not working
//cursor.getPosition() returns the position in the list
counterPos = counter.get(cursor.getPosition());
//increments the number at counterPos
counterPos = counterPos + litres;
//incrementing the edittext
//counter2 = counter.get(cursor.getPosition());
counter2++;
//set the new value to the array position
counter.set(cursor.getPosition(), counterPos);
//changes the editText in middle of row
runningTotal.setText(Integer.toString(counter2));
//sends counterPos to the interface for the running total
mMyInterface.updateLitres(counterPos);
mMyInterface.updateCost(counterPos * 0.00488);
}
});
//setting up the minus button
final Button minusButton = (Button)view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos = 0;
private int counter2;
public void onClick(View v) {
//code to change the value of the editText and the array, not working
counterPos = counter.get(cursor.getPosition());
//increments the number at counterPos
counterPos = counterPos + litres;
//incrementing the edittext
//counter2 = counter.get(cursor.getPosition());
counter2--;
//set the new value to the array position
counter.set(cursor.getPosition(), counterPos);
//changes the editText in middle of row
runningTotal.setText(Integer.toString(counter2));
//sends counterPos to the interface for the running total
mMyInterface.updateLitres(counterPos);
mMyInterface.updateCost(counterPos * 0.00488);
}
});
}
}
You should have a look here You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html, I used this and helped me get through it, You need to save each edit text that you want to save. and as for each row I would suggest making an array or loop for saving the edit boxes in the rows
didn't read your code bro, but answering in concern to your question title :
override onStop and save the data to Shared Preferences, its very easy to use:
//To save your data
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
//to extract your data in onCreate or whenever you feel like:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
You will want to look into SharedPreferences, once you do you will basically be saving your values in SharedPreferences in an onPause() / onDestroy() method, and then in your onResume() / onCreate() methods you will retrieve the previously stored data
Edit: You can retrieve a string from an EditText in the following way
String toStore = EditText.getText().toString();
and then store it
getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);
so...
public void onPause(){
super.onPause();
String toStore = EditText.getText().toString();
getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);
}
public void onResume(){
super.onResume();
String toStore = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY", "defaultStringIfNothingFound");
EditText.setText(toStore);
}
You may use onSavedInstanceState and onRestoreInstanceState methods of activity !
So in onSavedInstanceState (called before your activity pauses) you may save your `EditText' values to the bundle,
And restore them back in onRestoreInstance state.
You can use the link by #Kaique for more reference,
and also this answer https://stackoverflow.com/a/16769864/826657 and all related answers here.
You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html
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.
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.