Hello all, I would like my number (resultat) seems like this ###,###,###.00. Into (resultat) in the String.valueOf from the below phrase of the below Java Code. Thanks for your answers.
result.setText("the rent is " + String.valueOf(resultat) + " currency");
package albencreation.realestateapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Rent extends AppCompatActivity {
EditText price = null;
EditText profit = null;
TextView result = null;
Button envoyer = null;
Button close = null;
Button info = null;
Button clear = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rent);
price = (EditText) findViewById(R.id.price);
profit = (EditText) findViewById(R.id.profit);
result = (TextView) findViewById(R.id.result);
envoyer = (Button) findViewById(R.id.buttcalculate);
close = (Button) findViewById(R.id.buttclose);
info = (Button) findViewById(R.id.buttinfo);
clear = (Button) findViewById(R.id.buttclear);
envoyer.setOnClickListener(envoyerListener);
close.setOnClickListener(closeListener);
info.setOnClickListener(infoListener);
clear.setOnClickListener(clearListener);
}
private OnClickListener envoyerListener = new OnClickListener() {
#Override
public void onClick(View v) {
String p = price.getText().toString();
String o = profit.getText().toString();
float pValue;
if (p.isEmpty()) {
pValue = 0;
} else {
pValue = Float.valueOf(p);
}
float oValue;
if (o.isEmpty()) {
oValue = 0;
} else {
oValue = Float.valueOf(o);
}
float resultat = oValue * pValue / 100;
result.setText("the rent is " + String.valueOf(resultat) + " currency");
}
};
private OnClickListener closeListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, MainActivity.class);
startActivity(jumpage);
}
};
private OnClickListener infoListener = new OnClickListener() {
#Override
public void onClick(View v) {
Intent jumpage = new Intent(Rent.this, Inforent.class);
startActivity(jumpage);
}
};
private OnClickListener clearListener = new OnClickListener() {
#Override
public void onClick(View v) {
price.getText().clear();
profit.getText().clear();
String defaut = "result rent";
result.setText(defaut);
}
};
}
Use DecimalFormat to format the string as you like. For integer values use # and for decimal places use 0
DecimalFormat formatter = new DecimalFormat("###,###,###.00");
String resultString = formatter.format(resultat);
result.setText("the rent is " + resultString + " currency");
try this :
import java.text.DecimalFormat;
float f = YourValue;
DecimalFormat decimalFormat = new DecimalFormat("#.##");
float twoDigitsF = Float.valueOf(decimalFormat.format(f));
This code for show Two Dights Hope will help you
Related
I am writing a small math's quiz with 10 questions per level. I'm trying to write a 10 second timer which has the following functions:
Moves to the next question when it runs out and restarts the timer
Restarts when a question is entered
My issue is that regardless of how I write this code, I cannot access the timer from both the "onFinish()" function as well as the rest of the program. such as "onCorrect()" I need to be able to cancel and restart an existing timer initialised in "onCreate()" however I can't then access that timer through a MyCountDownTimer class or function (I've tried using both to no avail.)
My code is below with comments to show where I need the timers to work.
package com.example.myapplication;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class Level2 extends AppCompatActivity {
int score = 0;
int q = 1;
TextView value;
TextView q_num;
TextView timer_label = findViewById(R.id.Timer);
/*public class MyCountDownTimer extends CountDownTimer {
TextView timer_label = findViewById(R.id.Timer);
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
onDone();
}
#Override
public void onTick(long millisUntilFinished) {
int temp = (int)millisUntilFinished/1000;
//do what ever You want
timer_label.setText(String.format(getResources().getString(R.string.timer_string),String.valueOf(temp)));
}
}
#Override
*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level2);
q = 1;
//MyCountDownTimer t = new MyCountDownTimer(11000,1000);
Button b1 = findViewById(R.id.option1);
Button b2 = findViewById(R.id.option2);
Button b3 = findViewById(R.id.option3);
Button b4 = findViewById(R.id.option4);
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
//
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); //bellow setSupportActionBar(toolbar);
getSupportActionBar().setCustomView(R.layout.action_layout);
//Gives action bar style
value = findViewById(R.id.score_value);
q_num = findViewById(R.id.question_number);
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b1.getText();
onCheck(ans,score);
}
});
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b2.getText();
onCheck(ans,score);
}
});
b3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b3.getText();
onCheck(ans,score);
}
});
b4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ans = (String) b4.getText();
onCheck(ans,score);
}
});
}
public void onCheck(String ans, int score) {
TextView ans_data = findViewById(R.id.answer_data);
String correct = (String) ans_data.getText();
if (ans.contains(correct)) {
onCorrect(score);
}
else{
onWrong();
}
}
public void onCorrect(int temp){
//t.cancel()
//t.start()
temp++;
score = temp;
q++;
if(q >= 11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
value.setText(String.valueOf(score));
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
public void onDone(){
//t.start()
q++;
if(q>=11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
else{
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
}
public void onWrong(){
//t.cancel()
//t.start
q++;
if(q>=11){
if(score >2){
complete(score);
}
else{
Intent i = new Intent(Level2.this, ne.class);
startActivity(i);
}
}
else{
q_num.setText(String.valueOf(q));
Random first = new Random();
int upperbound = 100;
int random_id = first.nextInt(upperbound);
selectData(random_id);
}
For reference;
onCheck() checks if the answer is right
onCorrect() is right
onWrong() is wrong
onDone() is when the timer runs out
The root of my issue is that I cannot put t into onDone as it's called by the MyCountDownTimer class which doesn't have access to the t called in onCreate.
Declare MyCountDownTimer t outside of onCreate() as a global variable.
I need your help to find an error in my "test" android application.
Until I create the second function "setProgessBar" the app runs without error, but now the error occur everytime. To comment the function call out has no effect.
Here is the code:
package my.timer;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Timer1 extends AppCompatActivity {
private int arrayPosition = 0;
private long timeValue = 0;
private boolean indicator = false;
private double progress;
private final String[] actions = {"Phase1" , "Phase2" , "Phase3" , "Phase4"};
private final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer1);
final Button startButton = (Button) findViewById(R.id.startButton);
final TextView text1 = (TextView) findViewById(R.id.textView3);
final TextView text2 = (TextView) findViewById(R.id.actionParameter);
startButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text2.setText(actions[arrayPosition]);
text1.setText("" + timeValue + "");
new CountDownTimer(240000, 100) {
public void onTick(long millisUntilFinished) {
timeValue = (millisUntilFinished / 1000) % 4;
text1.setText("" + timeValue + "");
if (timeValue == 3 && indicator){
if (arrayPosition < 3){
arrayPosition++;
} else {
arrayPosition = 0;
}
indicator = false;
setProgressBar(arrayPosition);
text2.setText(actions[arrayPosition]);
}
if (timeValue == 1){
indicator = true;
}
}
public void onFinish() {
text1.setText("Geschafft :)");
}
}.start();
}
});
}
private void setProgressBar(int progressStatus) {
switch (progressStatus){
case 0:
progress = progress + 0.25;
break;
case 2:
progress = progress - 0.25;
break;
}
progressBar.setProgress((int)progress);
}
}
Many thanks in advance
Tim
I need a system that will execute this code every second. I've been looking for a while and still can't find any ways that work. I'm quite new to Java programming and programming for android so any help will be greatly appreciated.
Values n = new Values();
double num = n.getNum();
double adder = n.getAdder();
if(adder>=1) {
num += (adder * 0.1);
}
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(num + "");
n.setNum(num);
Also, I'm importing values from a Values class that looks like this,
package com.example.durtle02.durtle02;
public class Values {
double num;
double cost = 30;
double adder;
public double getNum() {
return num;
}
public void setNum(double num) {
this.num = num;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public double getAdder() {
return adder;
}
public void setAdder(double adder) {
this.adder = adder;
}
}
EDIT
MainActivity.java
package com.example.durtle02.durtle02;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.Time;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//making game values accessible
final Values n = new Values();
//Loading The button for adding
final Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double num = n.getNum();
num++;
TextView tt = (TextView) findViewById(R.id.textView1);
n.setNum(num);
tt.setText(n.getNum() + "");
}
});
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double num = n.getNum();
double cost = n.getCost();
double adder = n.getAdder();
if (num >= cost) {
num -= cost;
cost = cost * 1.35;
adder++;
cost = Math.round(cost);
n.setNum(num);
n.setCost(cost);
n.setAdder(adder);
TextView tl = (TextView) findViewById(R.id.textView3);
tl.setText(n.getCost() + "");
TextView tk = (TextView) findViewById(R.id.textView4);
tk.setText(n.getAdder() + " Adders");
TextView tt = (TextView) findViewById(R.id.textView1);
tt.setText(n.getNum() + "");
TextView tp = (TextView) findViewById(R.id.textView2);
tp.setText((n.getAdder() * 0.1) + "/s");
}
}
});
countDownTimer.start();
}
// Do something each second in a time frame of 60 seconds.
CountDownTimer countDownTimer = new CountDownTimer(60000, 100) {
public void onTick(long millisUntilFinished) {
Values n = new Values();
double num = n.getNum();
double adder = n.getAdder();
if(adder>=1) {
num += (adder * 0.1);
}
num++;
n.setNum(num);
}
public void onFinish() {
countDownTimer.start(); // restart again.
}
};
/*
//---------------------------------------------------------------
Values n = new Values();
double num = n.getNum();
double adder = n.getAdder();
if(adder>=1) {
num += (adder * 0.1);
}
TextView t = (TextView) findViewById(R.id.textView1);
t.setText(num + "");
n.setNum(num);
//--------------------------------------------------------------
*/
}
I think you can use CountDownTimer, something like this:
// Do something each second in a time frame of 60 seconds.
CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
// For every second, do something.
doSomething();
}
public void onFinish() {
countDownTimer.start(); // restart again.
}
}.start();
If your activity is in the foreground, the following code will do.
Handler mHandler= new Handler()
final Runnable runnable = new Runnable() {
#Override
public void run() {
// do your stuff here, called every second
mHandler.postDelayed(this, 1000);
}
};
// start it with:
mHandler.post(runnable);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to get values from a patient registration form into my database. But each time when I click on Submit button, application stops with following message:
Unfortunately. Application has stopped.
Logcat details are:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
My code for the same is as follows:
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TimePicker;
public class indoor_patient extends Activity{
public EditText sr_no, patient_name, consultant_name, ref_dr, department,
rel_name, rel_no, arr_date, arr_time;
Button submit;
ImageButton datepicker, timepicker;
Calendar cal;
int day, month, year;
int hour, min;
static final int TIME_DIALOG_ID = 1;
static final int DATE_DIALOG_ID = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.indoor_patient_tbl);
sr_no = (EditText) findViewById(R.id.etSrNo);
patient_name = (EditText) findViewById(R.id.etPatientName);
consultant_name = (EditText) findViewById(R.id.etConsultantDr);
ref_dr = (EditText) findViewById(R.id.etRefDr);
department = (EditText) findViewById(R.id.etDepartment);
rel_name = (EditText) findViewById(R.id.etRelativeName);
rel_no = (EditText) findViewById(R.id.etRelContact);
arr_date = (EditText) findViewById(R.id.etArrDate);
arr_time = (EditText) findViewById(R.id.etArrTime);
submit = (Button) findViewById(R.id.btnIndoorSubmit);
cal = Calendar.getInstance();
day = cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
datepicker = (ImageButton) findViewById(R.id.imgBtnDate);
datepicker.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
hour = cal.get(Calendar.HOUR_OF_DAY);
min = cal.get(Calendar.MINUTE);
timepicker = (ImageButton) findViewById(R.id.imgBtnTime);
timepicker.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new dbwork().execute();
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, datePickerListener, year, month,
day);
case TIME_DIALOG_ID:
return new TimePickerDialog(this, timePickerListener, hour, min,
false);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
arr_date.setText(selectedDay + "/" + (selectedMonth + 1) + "/"
+ selectedYear);
}
};
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
int hour;
String am_pm;
if (hourOfDay > 12) {
hour = hourOfDay - 12;
am_pm = "PM";
} else {
hour = hourOfDay;
am_pm = "AM";
}
arr_time.setText(hour + ":" + min + " " + am_pm);
}
};
}
And my database connectivity file is as follows:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
public class dbwork extends AsyncTask<Void, String, String> {
indoor_patient ins=new indoor_patient();
String webUrl = "http://10.0.3.2:8084/data_web/indoorPatient.jsp?sr_no="
+ ins.sr_no.getText().toString()
+ ""
+ ins.patient_name.getText().toString()
+ ""
+ ins.consultant_name.getText().toString()
+ ""
+ ins.ref_dr.getText().toString()
+ ""
+ ins.department.getText().toString()
+ ""
+ ins.rel_name.getText().toString()
+ ""
+ ins.rel_no.getText().toString()
+ ""
+ ins.arr_date.getText().toString()
+ ""
+ ins.arr_time.getText().toString() + "&submit=Submit";
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
StringBuffer strbuffer=new StringBuffer("");
String line="";
try {
URL url=new URL(webUrl);
HttpURLConnection hurl;
hurl=(HttpURLConnection)url.openConnection();
BufferedInputStream bis;
bis=new BufferedInputStream(hurl.getInputStream());
InputStream is;
is=bis;//implicit casting // from downward to upward
InputStreamReader isr;
isr=new InputStreamReader(is);
BufferedReader br;
br=new BufferedReader(isr);
//reading html form
while ((line = br.readLine()) != null) {
strbuffer.append(line);
}
bis.close();
is.close();
isr.close();
br.close();
hurl.disconnect();
}
catch(Exception ex)
{
ex.printStackTrace();
}
return strbuffer.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
You can't just instantiate your Activity and access the TextView members on it. This doesn't make any sense:
indoor_patient ins=new indoor_patient();
String webUrl = "http://10.0.3.2:8084/data_web/indoorPatient.jsp?sr_no="
+ ins.sr_no.getText().toString()
Instead you could figure out what your webUrl is in your onClick() method and pass in the complete URL as a parameter to the AsyncTask:
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String webUrl = "http://10.0.3.2:8084/data_web/indoorPatient.jsp?sr_no="
+ ins.sr_no.getText().toString()
+ ""
+ ins.patient_name.getText().toString()
+ ""
+ ins.consultant_name.getText().toString()
+ ""
+ ins.ref_dr.getText().toString()
+ ""
+ ins.department.getText().toString()
+ ""
+ ins.rel_name.getText().toString()
+ ""
+ ins.rel_no.getText().toString()
+ ""
+ ins.arr_date.getText().toString()
+ ""
+ ins.arr_time.getText().toString() + "&submit=Submit";
new dbwork().execute(webUrl);
}
});
Then change your AsyncTask to something like this:
public class dbwork extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String webUrl = params[0];
// TODO Auto-generated method stub
StringBuffer strbuffer=new StringBuffer("");
// ...
When you execute indoor_patient ins=new indoor_patient();, it doesn't mean that you call onCreate(). So all EditText components are null.
My application shut down unexpectedly, I don't really know what the problem is. I'm new to programming java. I tried the 'try', 'catch' and 'finally' methods.
Here is the code:
package com.eqsec.csaba;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class EqsecActivity extends Activity {
/** Called when the activity is first created. */
Button solve;
EditText vA, vB, vC;
TextView solution;
int discriminant, iA, iB, iC;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
solve = (Button) findViewById(R.id.bSolve);
vA = (EditText) findViewById(R.id.etA);
vB = (EditText) findViewById(R.id.etB);
vC = (EditText) findViewById(R.id.etC);
solve.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try{
String A = vA.getText().toString();
iA = Integer.parseInt(A);
String B = vB.getText().toString();
iB = Integer.parseInt(B);
String C = vC.getText().toString();
iC = Integer.parseInt(C);
solution.setText("Yout total is " + iA);
}catch (ArithmeticException e) {
e.printStackTrace();
}
}
});
}
}
Please help me, i want to write an android application, which can solve some math problems.
You have to catch NumberFormatException instead of ArithmeticException.
And initialize solution variable before. Like:
solution = (TextView) findViewById(R.id.solution);
Full code will be:
package com.eqsec.csaba;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class EqsecActivity extends Activity {
/** Called when the activity is first created. */
Button solve;
EditText vA, vB, vC;
TextView solution;
int discriminant, iA, iB, iC;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
solve = (Button) findViewById(R.id.bSolve);
vA = (EditText) findViewById(R.id.etA);
vB = (EditText) findViewById(R.id.etB);
vC = (EditText) findViewById(R.id.etC);
solution = (TextView) findViewById(R.id.solution);
solve.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try{
String A = vA.getText().toString();
iA = Integer.parseInt(A);
String B = vB.getText().toString();
iB = Integer.parseInt(B);
String C = vC.getText().toString();
iC = Integer.parseInt(C);
solution.setText("Yout total is " + iA);
}catch (NumberFormatException e) {
e.printStackTrace();
}
}
});
}
}
Try this:
solve.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String A = vA.getText().toString();
iA = Integer.ValueOf(A);
String B = vB.getText().toString();
iB = Integer.ValueOf(B);
String C = vC.getText().toString();
iC = Integer.ValueOf(C);
// intialize solution
solution.setText("Yout total is " + String.ValueOf(iA));
//This is not the total yet
}
});