I want to implement a java countdown timer for my Android program but I don't know how should I do it. It should count the time from let's say 60 to 0 and at the end the program should end but the user needs to see how much time is left, so the timer should be visible all time. I managed to implement a "timer" for how long the game is accepting input but I don't understand how should I make a count down system. Here is my source file for the program that I made. Hope you guys can help me thanks in advance,
package com.example.mathcalcplus;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class PlayGame extends Activity implements OnClickListener {
ImageView image;
TextView question, answer, score, timeLeft;
int difLevel, operator1, operator2, finalAnswer=0, operation, scoreCount = 0, userAnswer=0;
final private int add = 0, sub = 1, div = 3, mul = 2;
String[] getOperation = { "+", "-", "*", "/"};
Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnClear, btnEnter;
Random rand;
String getQuestion, userInput;
long start;
long end;
boolean running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.play_game);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn3 = (Button) findViewById(R.id.btn3);
btn4 = (Button) findViewById(R.id.btn4);
btn5 = (Button) findViewById(R.id.btn5);
btn6 = (Button) findViewById(R.id.btn6);
btn7 = (Button) findViewById(R.id.btn7);
btn8 = (Button) findViewById(R.id.btn8);
btn9 = (Button) findViewById(R.id.btn9);
btn0 = (Button) findViewById(R.id.btn0);
btnClear = (Button) findViewById(R.id.clear);
btnEnter = (Button) findViewById(R.id.enter);
question = (TextView) findViewById(R.id.question);
answer = (TextView) findViewById(R.id.answer);
score = (TextView) findViewById(R.id.score);
image = (ImageView) findViewById(R.id.response);
timeLeft = (TextView) findViewById(R.id.timeLeft);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
btnClear.setOnClickListener(this);
btnEnter.setOnClickListener(this);
rand = new Random();
Bundle extras = getIntent().getExtras();
if(extras != null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) difLevel = passedLevel;
}
image.setVisibility(View.INVISIBLE);
choseQuestion();
start = System.currentTimeMillis();
end = start + 30*1000;
}
public void run(){
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.enter:
String getUserAnswer = answer.getText().toString();
if (!getUserAnswer.endsWith("?")){
userAnswer = Integer.parseInt(getUserAnswer.substring(1));
if (userAnswer == finalAnswer){
scoreCount++;
score.setText("Score=" + " " + scoreCount);
image.setImageResource(R.drawable.tick);
image.setVisibility(View.VISIBLE);
}
else{
scoreCount = 0;
score.setText("Score=" + " " + scoreCount);
image.setImageResource(R.drawable.cross);
image.setVisibility(View.VISIBLE);
}
finalAnswer =0;
choseQuestion();
getUserAnswer = "";
userAnswer = 0;
break;
}
else{
break;
}
case R.id.clear:
answer.setText("=?");
break;
default:
if (System.currentTimeMillis() < end){
int enteredNum = Integer.parseInt(v.getTag().toString());
if(answer.getText().toString().endsWith("?"))
answer.setText("="+enteredNum);
else
answer.append(""+enteredNum);
}
}
}
private void choseQuestion() {
answer.setText("=?");
operation = rand.nextInt(getOperation.length);
operator1 = getNumbers();
operator2 = getNumbers();
if (operation == sub){
while (operator2 > operator1){
operator1 = getNumbers();
operator2 = getNumbers();
}
}
if (operation == div){
while((double)operator1%(double)operator2 > 0 || (operator2 > operator1)){
operator1 = getNumbers();
operator2 = getNumbers();
}
}
switch(operation){
case add:
finalAnswer = operator1 + operator2;
break;
case sub:
finalAnswer = operator1 - operator2;
break;
case div:
finalAnswer = operator1 / operator2;
break;
case mul:
finalAnswer = operator1 * operator2;
break;
}
question.setText(operator1 + getOperation[operation] +operator2);
timeLeft.setText("Time :" + end);
}
private int getNumbers(){
int n = rand.nextInt(100) + 1;`enter code here`
return n;
}
}
Declare your CountDownTimer and you set the time range in miliseconds.
Call countDown method and your CountDownTimer is ready to go!
private final static int time = 10000;
private CountDownTimer timerCount;
public void countDown(){
countDown = (TextView) findViewById(R.id.countdown);
timerCount = new CountDownTimer(time, 1000) {
public void onTick(long millisUntilFinished) {
long tmp = millisUntilFinished / 1000;
countDown.setText(tmp + "");
}
public void onFinish() {
// Do your stuff
countDown.setText("0");
}
}.start();
}
And your .xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/questionList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/menu"
android:orientation="vertical"
android:weightSum="4" >
<TextView
android:id="#+id/title"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:textSize="14sp"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/countdown"
android:layout_gravity="right"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</TextView>
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Here is the example.
Refer to this link for countdowntimer.
Related
I made a higher lower game . if the player guess the number he get a specific number of points depending on how many tryes he had
I wrote the code, i have the total but i dont know how to display it in a textview or plain text , anything but no toast.
Here is the code:
package com.markusappcompany.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int total =0;
int score = 20;
int nr= 1;
int randomNumber;
public void generateRandomNumber(){
Random rand = new Random();
randomNumber = rand.nextInt(20)+1;
}
public void clickFunction(View view){
EditText editText = (EditText) findViewById(R.id.editText);
int guessValue = Integer.parseInt(editText.getText().toString());
String message;
if(guessValue > randomNumber)
{
message = "Mai mic!";
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
nr= nr +1;
score = score - 2;
} else if( guessValue < randomNumber) {
message = "Mai mare!";
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
nr = nr +1;
} else {
total = total+score;
if (nr == 1) {
message = "YAY! Ai ghicit din prima! Incearca din nou" ;
Toast.makeText(this, message + "+" + score, Toast.LENGTH_LONG).show();
generateRandomNumber();
score = 20;
} else {
message = "YAY! Incearca din nou! Ai ghicit din " ;
Toast.makeText(this, message + " " + nr +" incercari" + "+" + score + " " + total, Toast.LENGTH_LONG).show();
here the total is showed in a Toast. I want it to be showed on the screen as a text permanently.
generateRandomNumber();
nr = 1;
score = 20;
}
}
Log.i("Entered value", editText.getText().toString());
Log.i("info", Integer.toString(randomNumber));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateRandomNumber();
}
}
add a textView in your layout, add android:id="totalScore" in your layout to the
textView
in your java get reference to your textView
TextView tv = findViewById(R.id.totalScore);
and set your desired string
tv.setText("score here");
In your activity_main.xml add this TextView
<TextView
android:id = "#+id/text_view"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
/>
In your MainActivity class in onCreate() method
class MainActivity extends......
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find textview
textView = findViewById(R.id.text_view);
generateRandomNumber();
}
}
Now set the total score to the textView
.........
} else {
message = "YAY! Incearca din nou! Ai ghicit din " ;
String text = message + " " + nr +" incercari" + "+" + String.valueOf(score) + " " + String.valueOf(total);
textView.setText(text);
...........
I have a main activity where you can send a log to a database, and a log activity where you can view them and delete them. Everything works expect when I try and delete a single log, the program crashes and the error is saying that it can't find the column "identity" to delete it.
Main Activity:
package com.software.roux.diabcalc;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
public class MainActivity extends AppCompatActivity {
SharedPreferences mPrefs;
SharedPreferences logPrefs;
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
boolean rb0 = settings.getBoolean("accepted", false);
if(rb0 == true){
setTitle("MyInsulin");
mPrefs=this.getSharedPreferences("settings", 0);
logPrefs=this.getSharedPreferences("logs", 0);
final EditText a1 = (EditText) findViewById(R.id.add1);
final EditText a2 = (EditText) findViewById(R.id.add2);
final double bolusdose = Double.parseDouble(mPrefs.getString("bolus", "0"));
final double correctiondose = Double.parseDouble(mPrefs.getString("correction", "0"));
final double targetlow = Double.parseDouble(mPrefs.getString("low", "0"));
final double targethigh = Double.parseDouble(mPrefs.getString("high", "0"));
final double correctto = Double.parseDouble(mPrefs.getString("corrset", "0"));
String bolusString = mPrefs.getString("bolus", "0");
String corrString = mPrefs.getString("correction", "0");
String lowString = mPrefs.getString("low", "0");
String highString = mPrefs.getString("high", "0");
String correcttonum = mPrefs.getString("corrset", "0");
EditText b1 = (EditText)findViewById(R.id.bolus);
b1.setText(bolusString);
b1.setEnabled(false);
EditText b2 = (EditText)findViewById(R.id.correction);
b2.setText(corrString);
b2.setEnabled(false);
EditText b3 = (EditText)findViewById(R.id.targetlow);
b3.setText(lowString);
b3.setEnabled(false);
EditText b4 = (EditText)findViewById(R.id.targethigh);
b4.setText(highString);
b4.setEnabled(false);
EditText b5 = (EditText)findViewById(R.id.correcttonum);
b5.setText(correcttonum);
b5.setEnabled(false);
Button b6 = (Button)findViewById(R.id.setter);
b6.setEnabled(false);
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
db = openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS zlogtable('identity VARCHAR',bslevel VARCHAR,carbs VARCHAR,result VARCHAR);");
a1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentlevelst = a1.getText().toString();
String carbseatenst = a2.getText().toString();
if (currentlevelst.length() >= 1) {
if (carbseatenst.length() >= 1) {
Double currentlevel = Double.parseDouble(a1.getText().toString());
Double carbseaten = Double.parseDouble(a2.getText().toString());
double firststep = 0;
if (currentlevel > targethigh) {
firststep = ((currentlevel - correctto) / correctiondose);
} else if (currentlevel < targetlow) {
firststep = ((currentlevel - targethigh) / correctiondose);
} else {
firststep = 0;
}
double secondstep = carbseaten / bolusdose;
double firstplussecond = firststep + secondstep;
BigDecimal result = new BigDecimal(firstplussecond, MathContext.DECIMAL64);
result = result.setScale(2, RoundingMode.CEILING);
if (result.compareTo(BigDecimal.ZERO) > 0) {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("Recommended Dose: " + result + " Units");
Button b8 = (Button) findViewById(R.id.logsave);
b8.setEnabled(true);
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("No Insulin Needed");
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
a2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentlevelst = a1.getText().toString();
String carbseatenst = a2.getText().toString();
if (currentlevelst.length() >= 1) {
if (carbseatenst.length() >= 1) {
Double currentlevel = Double.parseDouble(a1.getText().toString());
Double carbseaten = Double.parseDouble(a2.getText().toString());
double firststep = 0;
if (currentlevel > targethigh) {
firststep = ((currentlevel - correctto) / correctiondose);
} else if (currentlevel < targetlow) {
firststep = ((currentlevel - targethigh) / correctiondose);
} else {
firststep = 0;
}
double secondstep = carbseaten / bolusdose;
double firstplussecond = firststep + secondstep;
BigDecimal result = new BigDecimal(firstplussecond, MathContext.DECIMAL64);
result = result.setScale(2, RoundingMode.CEILING);
if (result.compareTo(BigDecimal.ZERO) > 0) {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("Recommended Dose: " + result + " Units");
Button b8 = (Button) findViewById(R.id.logsave);
b8.setEnabled(true);
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("No Insulin Needed");
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}else{
showDialog(0);
}}
public void addclickb(View b) throws InterruptedException {
if (b.getId() == R.id.add2) {
final EditText a1 = (EditText) findViewById(R.id.add1);
final EditText a2 = (EditText) findViewById(R.id.add2);
final double bolusdose = Double.parseDouble(mPrefs.getString("bolus", "0"));
final double correctiondose = Double.parseDouble(mPrefs.getString("correction", "0"));
final double targetlow = Double.parseDouble(mPrefs.getString("low", "0"));
final double targethigh = Double.parseDouble(mPrefs.getString("high", "0"));
final double correctto = Double.parseDouble(mPrefs.getString("corrset", "0"));
a2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String currentlevelst = a1.getText().toString();
String carbseatenst = a2.getText().toString();
if (currentlevelst.length() >= 1) {
if (carbseatenst.length() >= 1) {
Double currentlevel = Double.parseDouble(a1.getText().toString());
Double carbseaten = Double.parseDouble(a2.getText().toString());
double firststep = 0;
if (currentlevel > targethigh) {
firststep = ((currentlevel - correctto) / correctiondose);
} else if (currentlevel < targetlow) {
firststep = ((currentlevel - targethigh) / correctiondose);
} else {
firststep = 0;
}
double secondstep = carbseaten / bolusdose;
double firstplussecond = firststep + secondstep;
BigDecimal result = new BigDecimal(firstplussecond, MathContext.DECIMAL64);
result = result.setScale(2, RoundingMode.CEILING);
if (result.compareTo(BigDecimal.ZERO) > 0) {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("Recommended Dose: " + result + " Units");
Button b8 = (Button) findViewById(R.id.logsave);
b8.setEnabled(true);
} else {
TextView t = (TextView) findViewById(R.id.answerobj);
t.setText("No Insulin Needed");
}
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
public void noweditable(View a) {
if (a.getId() == R.id.editbutton) {
EditText b1 = (EditText)findViewById(R.id.bolus);
EditText b2 = (EditText)findViewById(R.id.correction);
EditText b3 = (EditText)findViewById(R.id.targetlow);
EditText b4 = (EditText)findViewById(R.id.targethigh);
EditText b5 = (EditText)findViewById(R.id.correcttonum);
Button b6 = (Button)findViewById(R.id.setter);
Button b7 = (Button)findViewById(R.id.editbutton);
b1.setEnabled(true);
b2.setEnabled(true);
b3.setEnabled(true);
b4.setEnabled(true);
b5.setEnabled(true);
b6.setEnabled(true);
b7.setEnabled(false);
}
}
public void setclick(View b) {
if (b.getId() == R.id.setter) {
EditText b1 = (EditText)findViewById(R.id.bolus);
if (b1.length() > 0) {
String bolussave = "" + b1.getText().toString();
SharedPreferences.Editor mEditor1 = mPrefs.edit();
mEditor1.putString("bolus", bolussave).commit();
}
EditText b2 = (EditText)findViewById(R.id.correction);
if (b2.length() > 0) {
String corrsave = "" + b2.getText().toString();
SharedPreferences.Editor mEditor2 = mPrefs.edit();
mEditor2.putString("correction", corrsave).commit();
}
EditText b3 = (EditText)findViewById(R.id.targetlow);
if (b3.length() > 0) {
String lowsave = "" + b3.getText().toString();
SharedPreferences.Editor mEditor3 = mPrefs.edit();
mEditor3.putString("low", lowsave).commit();
}
EditText b4 = (EditText)findViewById(R.id.targethigh);
if (b4.length() > 0) {
String highsave = "" + b4.getText().toString();
SharedPreferences.Editor mEditor4 = mPrefs.edit();
mEditor4.putString("high", highsave).commit();
}
EditText b5 = (EditText)findViewById(R.id.correcttonum);
if (b4.length() > 0) {
String corrsetsave = "" + b5.getText().toString();
SharedPreferences.Editor mEditor5 = mPrefs.edit();
mEditor5.putString("corrset", corrsetsave).commit();
}
b1.setEnabled(false);
b2.setEnabled(false);
b3.setEnabled(false);
b4.setEnabled(false);
b5.setEnabled(false);
Button b6 = (Button)findViewById(R.id.setter);
Button b7 = (Button)findViewById(R.id.editbutton);
b6.setEnabled(false);
b7.setEnabled(true);
}
}
public void logview(View b){
if(b.getId() == R.id.logview)
{
Intent myIntent = new Intent(MainActivity.this, Settings.class);
MainActivity.this.startActivity(myIntent);
}
}
public void logsave(View b){
if(b.getId() == R.id.logsave)
{
EditText l1 = (EditText)findViewById(R.id.add1);
EditText l2 = (EditText)findViewById(R.id.add2);
TextView l3 = (TextView)findViewById(R.id.answerobj);
SharedPreferences.Editor mEditor6 = mPrefs.edit();
int incrementer = mPrefs.getInt("increment",0);
incrementer++;
mEditor6.putInt("increment", incrementer).commit();
db=openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
db.execSQL("INSERT INTO zlogtable VALUES('"+incrementer+"','"+l2.getText()+"','"+
l1.getText()+"','"+l3.getText()+"');");
Button b8 = (Button)findViewById(R.id.logsave);
b8.setEnabled(false);
b8.setText("Saved To Log");
}
}
protected Dialog onCreateDialog(int id){
// show disclaimer....
// for example, you can show a dialog box...
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Legal Notice: The content provided through this app is for informational purposes only and does not constitute medical advice. Reliance on any information provided by this application is solely at your own risk.")
.setCancelable(false)
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// and, if the user accept, you can execute something like this:
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("accepted", true);
// Commit the edits!
editor.commit();
}
})
.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//nm.cancel(R.notification.running); // cancel the NotificationManager (icon)
System.exit(0);
}
});
AlertDialog alert = builder.create();
return alert;
}
}
Log Activity:
package com.software.roux.diabcalc;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Settings extends AppCompatActivity {
SQLiteDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setTitle("My Logs");
db=openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
Cursor c=db.rawQuery("SELECT * FROM zlogtable", null);
if(c.getCount()==0)
{
System.out.print("Error");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
final TextView logfield = new TextView(this);
final LinearLayout layout = (LinearLayout) findViewById(R.id.loghold);
final LinearLayout layout1 = new LinearLayout(this);
final int identifier = c.getInt(0);
logfield.append("Blood Sugar Level: "+c.getString(2)+"\n");
logfield.append("Carbs Eaten: "+c.getString(1)+"\n");
logfield.append(""+c.getString(3)+"\n");
final Button deleter = new Button(this);
deleter.setText("Delete");
deleter.setTextSize(12);
layout1.addView(logfield);
layout1.addView(deleter);
layout.addView(layout1);
deleter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
layout1.removeView(deleter);
layout1.removeView(logfield);
db=openOrCreateDatabase("logDB", Context.MODE_PRIVATE, null);
db.execSQL("DELETE FROM zlogtable WHERE identity = "+identifier+" ");
}
});
}
TextView log1 = (TextView) findViewById(R.id.log1);
log1.setText(buffer.toString());
}
public void switchclick(View a) {
if (a.getId() == R.id.backbutton) {
Intent myIntent = new Intent(Settings.this, MainActivity.class);
Settings.this.startActivity(myIntent);
}
}
}
Looks like there is no column named 'identity' in your database. Can you check the column name for your db table.
Rotwang commented and found an error with this statement, I removed the string markers and it worked perfectly:
This is wrong: "CREATE TABLE IF NOT EXISTS zlogtable('identity VARCHAR'. Remove the ' string markers.
I have 2 textviews, 1 editbox and 1 button in my xml.
In my code, this line is not working:
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
But next line (else statement) is working and In both cases (if & else statement) it shows else function toast ("Wrong").
Here is my code:
public class GameActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
Random r = new Random();
int i = r.nextInt(10 - 2) + 2;
tv.setText(i +"");
Random r1 = new Random();
int j = r1.nextInt((9 - 2) + 1) + 2;
tv2.setText(j +"");
int a = Integer.parseInt(tv.getText().toString());
int b = Integer.parseInt(tv2.getText().toString());
int result = a*b;
String str = String.valueOf(result);
EditText txt4 = (EditText) findViewById(R.id.editText1);
String c = txt4.getText().toString();
if(TextUtils.isEmpty(txt4.getText().toString())) {
txt4.setError("Please enter your answer");
return;
}
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(GameActivity.this, "wrong",Toast.LENGTH_LONG).show();
}
txt4.setText("");
}
});
}
Try this,
I got result
public class Test extends AppCompatActivity {
Button b1;
TextView t1,t2;
EditText e1;
int a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
b1 = (Button) findViewById(R.id.button2);
t1=(TextView) findViewById(R.id.textView4);
t2=(TextView) findViewById(R.id.textView5);
e1=(EditText) findViewById(R.id.editText);
Random r = new Random();
int i = r.nextInt(10 - 2) + 2;
t1.setText(i +"");
Random r1 = new Random();
int j = r1.nextInt((9 - 2) + 1) + 2;
t2.setText(j +"");
a = Integer.parseInt(t1.getText().toString());
b = Integer.parseInt(t2.getText().toString());
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int result = a*b;
String str = String.valueOf(result);
String c = e1.getText().toString();
if(TextUtils.isEmpty(c)) {
e1.setError("Please enter your answer");
return;
}
if(c.equals(str)){
Toast.makeText(Test.this, "Alright",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Test.this, "wrong",Toast.LENGTH_LONG).show();
}
e1.setText("");
}
});
}}
Instead of
String str = String.valueOf(result);
you should use
String str = Integer.toString(result);
My question is, how do I make a save file using a text file. I want to be able to save the game and to load even after the phone has been restarted.
So what I'm asking is how to make a save file using text file.
public class MainActivity extends AppCompatActivity {
ImageButton Button,Button2,Button3,Button4,Button5,Button6,Button7,Button8,Button9,Button10;
long count = 0;
MediaPlayer mp, mp_pilla,mp_slua;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textview = (TextView) findViewById(R.id.textView);
mp = MediaPlayer.create(MainActivity.this, R.raw.nyaaw);
mp_pilla = MediaPlayer.create(MainActivity.this, R.raw.pillabli);
mp_slua = MediaPlayer.create(MainActivity.this, R.raw.slua);
Button = (ImageButton) findViewById(R.id.myButton);
Button2 = (ImageButton) findViewById(R.id.myButton2);
Button3 = (ImageButton) findViewById(R.id.myButton3);
Button4 = (ImageButton) findViewById(R.id.myButton4);
Button5 = (ImageButton) findViewById(R.id.myButton5);
Button6 = (ImageButton) findViewById(R.id.myButton6);
Button7 = (ImageButton) findViewById(R.id.myButton7);
Button8 = (ImageButton) findViewById(R.id.myButton8);
Button9 = (ImageButton) findViewById(R.id.myButton9);
Button10 = (ImageButton) findViewById(R.id.myButton10);
textview.setText("0");
ImageButton buttonsak = (ImageButton) findViewById(R.id.myButton);
ImageButton buttonsak2 = (ImageButton) findViewById(R.id.myButton2);
ImageButton buttonsak3 = (ImageButton) findViewById(R.id.myButton3);
ImageButton buttonsak4 = (ImageButton) findViewById(R.id.myButton4);
ImageButton buttonsak5 = (ImageButton) findViewById(R.id.myButton5);
ImageButton buttonsak6 = (ImageButton) findViewById(R.id.myButton6);
ImageButton buttonsak7 = (ImageButton) findViewById(R.id.myButton7);
ImageButton buttonsak8 = (ImageButton) findViewById(R.id.myButton8);
ImageButton buttonsak9 = (ImageButton) findViewById(R.id.myButton9);
ImageButton buttonsak10 = (ImageButton) findViewById(R.id.myButton10);
View.OnClickListener clicker = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.myButton:
count++;
mp.start();
textview.setText("" + count);
break;
case R.id.myButton2:
if (count >= 50) {
count += 5;
mp_slua.start();
textview.setText("" + count);
}
break;
case R.id.myButton3:
if (count >= 100) {
count += 10;
mp_pilla.start();
textview.setText("" + count);
}
break;
case R.id.myButton4:
if (count >= 500) {
count += 20;
mp_slua.start();
textview.setText("" + count);
}
break;
case R.id.myButton5:
if (count >= 2000) {
count += 50;
mp_slua.start();
textview.setText("" + count);
}
break;
case R.id.myButton6:
if (count >= 5000) {
count += 100;
mp.start();
textview.setText("" + count);
}
break;
case R.id.myButton7:
if (count >= 10000) {
count += 200;
mp_slua.start();
textview.setText("" + count);
}
break;
case R.id.myButton8:
if (count >= 30000) {
count += 500;
mp_pilla.start();
textview.setText("" + count);
}
break;
case R.id.myButton9:
if (count >= 100000) {
count += 1000;
mp.start();
textview.setText("" + count);
}
break;
case R.id.myButton10:
if (count >= 250000) {
count += 2500;
mp_pilla.start();
textview.setText("" + count);
}
break;
default:
break;
}
}
};
buttonsak.setOnClickListener(clicker);
buttonsak2.setOnClickListener(clicker);
buttonsak3.setOnClickListener(clicker);
buttonsak4.setOnClickListener(clicker);
buttonsak5.setOnClickListener(clicker);
buttonsak6.setOnClickListener(clicker);
buttonsak7.setOnClickListener(clicker);
buttonsak8.setOnClickListener(clicker);
buttonsak9.setOnClickListener(clicker);
buttonsak10.setOnClickListener(clicker);
}
Use SharePreference to save data like this:
SharedPreferences.Editor editor = getSharedPreferences(SAVE_GAME, MODE_PRIVATE).edit();
editor.putString("game", "saved");
editor.commit();
and get the info like this:
SharedPreferences prefs = getSharedPreferences(SAVE_GAME, MODE_PRIVATE);
String restoredText = prefs.getString("game", null);
if (restoredText != null) {
String name = prefs.getString("game", "state");// "state" is the default value.
}
As #Mariano said: SharedPreferences is a good place to save things. The advantage of SharedPreferences is that it doesn't require any additional permissions.
There are other choices though, depending on your needs. You can write to external storage (which requires the WRITE_EXTERNAL) permission and perhaps much more interesting for you is using the service that Google provides for saving game state. There are some nice examples on there for you to follow.
I want to calculate time of working and cash earned (lets say its 20 ILS per hour - that's why I am multiplying by 20 in my Application.)
I use SharedPreferences so I can get out from the Application and it will still remember when I pressed the start button, also I am using Calendar.getInstance() but when I am getting the hours I am using 12 hours format so I will not have problems of calculating working time (if I began in 8am and finished 9pm, working time will be finish minus started, 9-8 and that's one hour so it will be wrong).
I used INTs in the beginning but I kept getting zero hours working because you cannot work 0.3 hours in INTs, it will cut it to zero, I changed to Doubles but surprisingly there is no getDouble or putDouble in SharedPreferences so I switched to Floats but I am getting Errors now and my Application crashes.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("myPrefsKey", 0);
textView = (TextView) findViewById(R.id.textView);
buttonStart = (Button) findViewById(R.id.start);
buttonStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "onClick: starting");
c = Calendar.getInstance();
begmin = c.get(Calendar.MINUTE);
beghour = c.get(Calendar.HOUR_OF_DAY);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("key1", begmin);
edit.putInt("key2", beghour);
}
});
buttonStop = (Button) findViewById(R.id.stop);
buttonStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "onClick: stopping");
Calendar c = Calendar.getInstance();
finmin = c.get(Calendar.MINUTE);
finhour = c.get(Calendar.HOUR_OF_DAY);
if (finhour >= beghour)
workhour = finhour - beghour;
else
workhour = 12 - beghour + finhour;
workmin = finmin - begmin;
hourcashto = (float)(workhour * 20);
mincashto = (float)(20 * (workmin / 60));
cashto = hourcashto + mincashto;
cash = prefs.getFloat("key", 0);
cash = cash + cashto;
SharedPreferences.Editor edit = prefs.edit();
edit.putFloat("key", cash);
edit.commit();
textView.setText("cash now: " + cashto + " cash total including today: " + cash + " \n" + "Time today: " + workhour + ":" + workmin);
}
});
}
Here is the Logcat output:
09-01 19:44:19.811 17344-17344/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: firstappdevelopment.work, PID: 17344
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float
at android.app.SharedPreferencesImpl.getFloat(SharedPreferencesImpl.java:253)
at firstappdevelopment.work.MainActivity$2.onClick(MainActivity.java:57)
at android.view.View.performClick(View.java:5254)
at android.view.View$PerformClick.run(View.java:21179)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6837)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:115)
I am sorry if it is half a logcat, I used search for "MainActivity" as there is auto scroll in Android Studio Logcat and I couldn't get to the crash and copy. The line MainActivity.java:57 refers to:
cash = prefs.getFloat("key", 0);
From what I understood, it says cash is an int but look at my constructor(?):
private static final String TAG = "ServicesDemo";
private Button buttonStart, buttonStop;
private int begmin, beghour, finmin, finhour, workhour, workmin;
private float cash, cashto, hourcashto, mincashto;
private Calendar c;
private TextView textView;
private SharedPreferences prefs;
Thank you all for helping.
Edit, Full Code+XML
package firstappdevelopment.work;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends Activity {
private static final String TAG = "ServicesDemo";
private Button buttonStart, buttonStop;
private int begmin, beghour, finmin, finhour, workhour, workmin;
private float cash, cashto, hourcashto, mincashto;
private Calendar c;
private TextView textView;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("myPrefsKey", 0);
textView = (TextView) findViewById(R.id.textView);
buttonStart = (Button) findViewById(R.id.start);
buttonStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "onClick: starting");
c = Calendar.getInstance();
begmin = c.get(Calendar.MINUTE);
beghour = c.get(Calendar.HOUR_OF_DAY);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("key1", begmin);
edit.putInt("key2", beghour);
}
});
buttonStop = (Button) findViewById(R.id.stop);
buttonStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "onClick: stopping");
Calendar c = Calendar.getInstance();
finmin = c.get(Calendar.MINUTE);
finhour = c.get(Calendar.HOUR_OF_DAY);
if (finhour >= beghour)
workhour = finhour - beghour;
else
workhour = 12 - beghour + finhour;
workmin = finmin - begmin;
hourcashto = (float)(workhour * 20);
mincashto = (float)(20 * (workmin / 60));
cashto = hourcashto + mincashto;
cash = prefs.getFloat("key", 0f);
cash = cash + cashto;
SharedPreferences.Editor edit = prefs.edit();
edit.putFloat("key", cash);
edit.commit();
textView.setText("cash now: " + cashto + " cash total including today: " + cash + " \n" + "Time today: " + workhour + ":" + workmin);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="#+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="START"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total:"
android:layout_alignTop="#+id/stop"
android:layout_toRightOf="#+id/stop"
android:layout_toEndOf="#+id/stop"
/>
<Button
android:id="#+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP"
android:layout_alignTop="#+id/start"
android:layout_toRightOf="#+id/start"
android:layout_toEndOf="#+id/start" />
</RelativeLayout>
So from the error you receive ClassCastException you are attempting to pass a default value of 0 from SharedPreferences if the value does not exist.
Change cash = prefs.getFloat("key", 0) to cash = prefs.getFloat("key", 0.0)
Since you have this exception:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Float
your problem is here:
cash = prefs.getFloat("key", 0);
must be:
cash = prefs.getFloat("key", 0.0f);
or probably your variable cash is defined as int! you have to change to:
float cash;
More info about getFloat() method.
So you know that the problem is here:
cash = prefs.getFloat("key", 0)
I think your code is fine!
But, as you said that you were initially storing some integer value in the shared-preferences for "key". Did you remove those values?
I will suggest you to try just try to change cash = prefs.getFloat("key", 0) to cash = prefs.getFloat("key_new", 0). That might be silly issue which you overlooked!
Note, if there is a problem of 0 or 0f or 0.0f in cash = prefs.getFloat("key_new", 0), then it would give you a compile time error.
It is happening because in prefs = getSharedPreferences("myPrefsKey", 0); 0 is a int. Using 0.0 will solve the problem as it is a float. Corrected code -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("myPrefsKey", 0.0); // CODE CHANGED HERE
textView = (TextView) findViewById(R.id.textView);
buttonStart = (Button) findViewById(R.id.start);
buttonStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "onClick: starting");
c = Calendar.getInstance();
begmin = c.get(Calendar.MINUTE);
beghour = c.get(Calendar.HOUR_OF_DAY);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt("key1", begmin);
edit.putInt("key2", beghour);
}
});
buttonStop = (Button) findViewById(R.id.stop);
buttonStop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "onClick: stopping");
Calendar c = Calendar.getInstance();
finmin = c.get(Calendar.MINUTE);
finhour = c.get(Calendar.HOUR_OF_DAY);
if (finhour >= beghour)
workhour = finhour - beghour;
else
workhour = 12 - beghour + finhour;
workmin = finmin - begmin;
hourcashto = (float)(workhour * 20);
mincashto = (float)(20 * (workmin / 60));
cashto = hourcashto + mincashto;
cash = prefs.getFloat("key", 0);
cash = cash + cashto;
SharedPreferences.Editor edit = prefs.edit();
edit.putFloat("key", cash);
edit.commit();
textView.setText("cash now: " + cashto + " cash total including today: " + cash + " \n" + "Time today: " + workhour + ":" + workmin);
}
});
}