Calculating work time and cash - java

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);
}
});
}

Related

how can i show a total score to the player screen not using a Toast

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);
...........

What is the cause of the int variable problem?

I have a variable of its kind int.
I've allocated value in it through another value from within another object ,but there's a problem.
The problem is happening when i press the button 3
after i set the required time values for each object.
I'll show you the wrong message ,and the code used.
I want to change the code to work properly.
// Logcat:
java.lang.NullPointerException: Attempt to read from field 'int com.ahmedco.testcode2.TimePickerDialog.hourOfDay' on a null object reference
at com.ahmedco.testcode2.MainActivity$3.onClick(MainActivity.java:65)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
// class 1
public class MainActivity extends AppCompatActivity {
Button b1, b2, b3;
DialogFragment timePickerDialog1, timePickerDialog2;
int hourTimer1, hourTimer2, minuteTimer1, minuteTimer2;
String time1Format, time2Format, AM_PMTimer1, AM_PMTimer2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timePickerDialog1 = new TimePickerDialog(1);
timePickerDialog1.show(getSupportFragmentManager(), "timePicker");
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
timePickerDialog2 = new TimePickerDialog(2);
timePickerDialog2.show(getSupportFragmentManager(), "timePicker");
}
});
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hourTimer1 = ((TimePickerDialog) timePickerDialog1).hourOfDay;
hourTimer2 = ((TimePickerDialog) timePickerDialog2).hourOfDay;
minuteTimer1 = ((TimePickerDialog) timePickerDialog1).minute;
minuteTimer2 = ((TimePickerDialog) timePickerDialog2).minute;
AM_PMTimer1 = ((TimePickerDialog) timePickerDialog1).AM_PM;
AM_PMTimer2 = ((TimePickerDialog) timePickerDialog2).AM_PM;
//Log.i("trace1","test "+((TimePickerDialog) timePickerDialog1).hourOfDay);
//Log.i("trace2","test "+((TimePickerDialog) timePickerDialog2).hourOfDay);
time1Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer1;
time2Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer2;
Log.i("time1Format", "" + time1Format);
Log.i("time2Format", "" + time2Format);
}
});
}
}
// class 2
public class TimePickerDialog extends DialogFragment implements android.app.TimePickerDialog.OnTimeSetListener {
public String AM_PM = "";
public int hourOfDay = 0;
public int minute = 0;
public TimePickerDialog(int id) {
// currentEditText = id;
}
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new android.app.TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay_, int minute_) {
// "11:06 PM"
if (hourOfDay_ > 12) {
AM_PM = "PM";
hourOfDay_ = hourOfDay_ - 12;
} else {
AM_PM = "AM";
}
///Log.i("hourOfDay",""+hourOfDay_+":"+hourOfDay_+" "+AM_PM);
hourOfDay = hourOfDay_;
minute = minute_;
}
}
You having problem inside b3.setOnClickListener because you are not initialized object so you have to initialize objects timePickerDialog1 and timePickerDialog2 globally.
DialogFragment timePickerDialog1=new TimePickerDialog(1), timePickerDialog2=new TimePickerDialog(2);
or
b3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(timePickerDialog1==null)
timePickerDialog1=new TimePickerDialog(1);
if(timePickerDialog2==null)
timePickerDialog1=new TimePickerDialog(2);
hourTimer1 = ((TimePickerDialog) timePickerDialog1).hourOfDay;
hourTimer2 = ((TimePickerDialog) timePickerDialog2).hourOfDay;
minuteTimer1 = ((TimePickerDialog) timePickerDialog1).minute;
minuteTimer2 = ((TimePickerDialog) timePickerDialog2).minute;
AM_PMTimer1 = ((TimePickerDialog) timePickerDialog1).AM_PM;
AM_PMTimer2 = ((TimePickerDialog) timePickerDialog2).AM_PM;
//Log.i("trace1","test "+((TimePickerDialog) timePickerDialog1).hourOfDay);
//Log.i("trace2","test "+((TimePickerDialog) timePickerDialog2).hourOfDay);
time1Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer1;
time2Format = "" + hourTimer1 + ":" + minuteTimer1 + " " + AM_PMTimer2;
Log.i("time1Format", "" + time1Format);
Log.i("time2Format", "" + time2Format);
}
});
You declare your TimePickerDialog in the beginning (DialogFragment timePickerDialog1, timePickerDialog2;)
But only initialise it when Button 1 or 2 are pressed respectively
timePickerDialog2 = new TimePickerDialog(2);
Therefore timePickerDialog2is nulluntil Button 2 was pressed.
When trying to call .hourOfDay in Button 3 when timePickerDialog2has not been initialised yet, you get a NullPointerException. You can't call methods on an object that is null.

My android application crashes when i am trying to make objects invisble/visible - eclipse

I am trying to make objects (TextView, EditText, Button) invisble/visible and when i do this the application crashes. This part is causing the crash:
I added the share preference
EDIT: at the end the problem was that i didn't initialize the objects and I didnt notice because it was just some of it
public class Nutrition extends Activity implements android.view.View.OnClickListener {
TextView weight_tv;
TextView hight_tv;
TextView age_tv;
EditText weight_ed;
EditText hight_ed;
EditText age_ed;
Button calculate_bt;
TextView recommendation_tv;
TextView calories_tv;
TextView protien_tv;
TextView carbohydrate_tv;
TextView fat_tv;
Button change_values_bt;
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nutrition);
calculate_bt = (Button)findViewById(R.id.calculate_bt);
calculate_bt.setOnClickListener(this);
change_values_bt = (Button)findViewById(R.id.change_values_bt);
change_values_bt.setOnClickListener(this);
weight_tv = (TextView)findViewById(R.id.weight_tv);
hight_tv = (TextView)findViewById(R.id.hight_tv);
age_tv = (TextView)findViewById(R.id.age_tv);
weight_ed = (EditText)findViewById(R.id.weight_ed);
hight_ed = (EditText)findViewById(R.id.hight_ed);
age_ed = (EditText)findViewById(R.id.age_ed);
recommendation_tv = (TextView)findViewById(R.id.recommendation_tv);
calories_tv = (TextView)findViewById(R.id.calories_tv);
protien_tv = (TextView)findViewById(R.id.protien_tv);
carbohydrate_tv = (TextView)findViewById(R.id.carbohydrate_tv);
fat_tv = (TextView)findViewById(R.id.fat_tv);
SharedPreferences prefs = getSharedPreferences("com.example.shreddedacademy", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
int wv = prefs.getInt("weight", -1);
if(wv == -1)
show_calculate();
else
{
calculate();
show_change();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nutrition, menu);
return true;
}
public void show_calculate()
{
weight_ed.setText("");
hight_ed.setText("");
age_ed.setText("");
weight_tv.setVisibility(View.VISIBLE);
hight_tv.setVisibility(View.VISIBLE);
age_tv.setVisibility(View.VISIBLE);
weight_ed.setVisibility(View.VISIBLE);
hight_ed.setVisibility(View.VISIBLE);
age_ed.setVisibility(View.VISIBLE);
calculate_bt.setVisibility(View.VISIBLE);
recommendation_tv.setVisibility(View.INVISIBLE);
calories_tv.setVisibility(View.INVISIBLE);
protien_tv.setVisibility(View.INVISIBLE);
carbohydrate_tv.setVisibility(View.INVISIBLE);
fat_tv.setVisibility(View.INVISIBLE);
change_values_bt.setVisibility(View.INVISIBLE);
}
public void show_change()
{
weight_tv.setVisibility(View.INVISIBLE);
hight_tv.setVisibility(View.INVISIBLE);
age_tv.setVisibility(View.INVISIBLE);
weight_ed.setVisibility(View.INVISIBLE);
hight_ed.setVisibility(View.INVISIBLE);
age_ed.setVisibility(View.INVISIBLE);
calculate_bt.setVisibility(View.INVISIBLE);
recommendation_tv.setVisibility(View.VISIBLE);
calories_tv.setVisibility(View.VISIBLE);
protien_tv.setVisibility(View.VISIBLE);
carbohydrate_tv.setVisibility(View.VISIBLE);
fat_tv.setVisibility(View.VISIBLE);
change_values_bt.setVisibility(View.VISIBLE);
}
public void save()
{
SharedPreferences prefs = getSharedPreferences("com.example.shreddedacademy", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
int weight = Integer.parseInt(weight_ed.getText().toString());
int hight = Integer.parseInt(hight_ed.getText().toString());
int age = Integer.parseInt(age_ed.getText().toString());
editor.putInt("weight", weight);
editor.putInt("hight", hight);
editor.putInt("age", age);
editor.commit();
}
public void calculate()
{
SharedPreferences prefs = getSharedPreferences("com.example.shreddedacademy", Context.MODE_PRIVATE);
//SharedPreferences.Editor editor = prefs.edit();
int weight = prefs.getInt("weight", -1);
int hight = prefs.getInt("hight", -1);
int age = prefs.getInt("age", -1);
int calories = (int) ((10 * weight) + (6.25 * hight) - (5 * age) + 5);
int rmr = (int) (calories * 1.2 + 400);
String text_calories = String.valueOf(rmr);
calories_tv.setText("Consume " + text_calories + " calories per day");
int protien = weight * 2;
String protien_text = String.valueOf(protien);
protien_tv.setText(protien_text + " grams of protien per day");
String fat_text = String.valueOf(weight);
fat_tv.setText(fat_text + " grams of fat per day");
int carbohydrate = (protien * 4 + weight * 9) / 4;
String carbohydrate_text = String.valueOf(carbohydrate);
carbohydrate_tv.setText(carbohydrate_text + " grams of carbohydrate per day");
show_change();
}
#Override
public void onClick(View v) {
if(v.getId() == calculate_bt.getId())
{
if(weight_ed.length() > 0 && hight_ed.length() > 0 && age_ed.length() > 0)
{
save();
calculate();
show_change();
}
}
if(v.getId() == change_values_bt.getId())
{
show_calculate();
}
}
}
First I hope your variable is int so initialize it woth wv=0.The error is "Caused by: java.lang.NullPointerException" means your variable can not get anything from where you passed put debug point at all wv variable or put your this code in try-catch so you get the error.

Timer in Java program, countdown

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.

timePicker with multiple buttons

I hope someone can help me. I lack in OOP knowledge and am a newbie in android.
I have 6 buttons. Each button will call the timePicker and display the time on the button.
How do i want to differentiate each buttons?
Thank you.....
Here's the code..:
public class TabTwo extends Activity implements OnClickListener {
private Button btnBrfkst;
private Button btnMtea;
private Button btnLunch;
private Button btnAftea;
private Button btnDinner;
private Button btnSupper;
private Calendar mCalen;
private int hourOfDay;
private int minute;
private int ampm;
int timePickerInput ;
private static final int Time_PICKER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab_two);
btnBrfkst = (Button) findViewById(R.id.button1);
btnMtea = (Button) findViewById(R.id.button2);
btnLunch = (Button) findViewById(R.id.button3);
btnAftea = (Button) findViewById(R.id.button4);
btnDinner = (Button) findViewById(R.id.button5);
btnSupper = (Button) findViewById(R.id.button6);
mCalen = Calendar.getInstance();
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
btnBrfkst.setOnClickListener(this);
btnMtea.setOnClickListener(this);
btnLunch.setOnClickListener(this);
btnAftea.setOnClickListener(this);
btnDinner.setOnClickListener(this);
btnSupper.setOnClickListener(this);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_PICKER_ID:
return new TimePickerDialog(this, TimePickerListener,
hourOfDay, minute, false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener TimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
// while dialog box is closed, below method is called.
public void onTimeSet(TimePicker view, int hour, int minute) {
switch (timePickerInput) {
case R.id.button1:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
btnBrfkst.setText(hour12format + " : " + minute + " / " + ampmStr);
break;
case R.id.button2:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format2 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr2 = (ampm == 0) ? "AM" : "PM";
btnMtea.setText(hour12format2 + " : " + minute + " / " + ampmStr2);
break;
case R.id.button3:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format3 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr3 = (ampm == 0) ? "AM" : "PM";
btnLunch.setText(hour12format3 + " : " + minute + " / " + ampmStr3);
break;
case R.id.button4:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format4 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr4 = (ampm == 0) ? "AM" : "PM";
btnAftea.setText(hour12format4 + " : " + minute + " / " + ampmStr4);
break;
case R.id.button5:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format5 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr5 = (ampm == 0) ? "AM" : "PM";
btnDinner.setText(hour12format5 + " : " + minute + " / " + ampmStr5);
break;
case R.id.button6:
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format6 = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr6 = (ampm == 0) ? "AM" : "PM";
btnSupper.setText(hour12format6 + " : " + minute + " / " + ampmStr6);
break;
}
}
};
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
}
Your activity or fragment should implements View.OnClickListener.
Then each button should register each button like so:
Button buttonOne = (Button) findViewById(R.id.button_one);
Button buttonTwo = (Button) findViewById(R.id.button_two);
buttonOne.setOnClickListener(this);
buttonTwo.setOnClickListener(this);
Then in your onClick method:
#Override
public void onClick(View temp)
{
switch(temp.getId()) {
case R.id.button_one:
//do something
break;
case R.id.button_two:
//do something
break;
}
}
An other option is to set the method to be called in the layout file for each button using android:onClick="myMethodOne". This way you can call different methods if you want or even the same method and differentiate on ids like you do in the onClick methods.
Change this:
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
to
#Override
public void onClick(View v) {
timePickerInput = v.getId();
showDialog(Time_PICKER_ID);
}
You need to set the timerPickerInput to be the id of the button so you know which button to display the time in.

Categories

Resources