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.
Related
I'm creating an app for doctor's appointment.. So I want to see the booked appointments records in the listview for different activities with a delete button to delete a specific record..
this is my code for making appointments...
that is Appo.java
package com.example.medilyf;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class Appo extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet, confirm, seeappo;
TextView tvw, text, receiver_msg;
DBHelper myDB;
CheckBox android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appo);
tvw = findViewById(R.id.textView1);
eText = findViewById(R.id.editText1);
myDB = new DBHelper(Appo.this);
android = findViewById(R.id.checkBox);
angular = findViewById(R.id.checkBox1);
java = findViewById(R.id.checkBox2);
python = findViewById(R.id.checkBox3);
text = findViewById(R.id.txt);
Button btn = findViewById(R.id.getbtn);
receiver_msg =findViewById(R.id.textView5);
// create the get Intent object
Intent intent = getIntent();
String str = intent.getStringExtra("dr_name");
// display the string into textView
receiver_msg.setText(str);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(Appo.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet = findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt = eText.getText().toString();
tvw.setText(txt);
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result ="";
if (android.isChecked()) {
result += "\n9:00 - 10:30";
}
if (angular.isChecked()) {
result += "\n10:30 -11:30";
}
if (java.isChecked()) {
result += "\n11:30 -12:30";
}
if (python.isChecked()) {
result += "\n2:00 - 3:00";
}
text.setText(result);
}
});
confirm = findViewById(R.id.confirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String time = text.getText().toString();
String date = tvw.getText().toString();
if (str.equals("")) {
Toast.makeText(Appo.this, "Blank values", Toast.LENGTH_SHORT).show();
} else {
boolean booking = myDB.insertData2(str, time, date);
if (booking) {
Toast.makeText(Appo.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Appo.this, "Booking not confirmed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox:
str = checked?"9:00 - 10:30 Selected":"9:00 - 10:30 Deselected";
break;
case R.id.checkBox1:
str = checked?"10:30 -11:30 Selected":"10:30 -11:30 Deselected";
break;
case R.id.checkBox2:
str = checked?"11:30 -12:30 Selected":"11:30 -12:30 Deselected";
break;
case R.id.checkBox3:
str = checked?"2:00 - 3:00 Selected":"2:00 - 3:00 Deselected";
break;
}
Toast.makeText(Appo.this, str, Toast.LENGTH_SHORT).show();
}
}
This is the code for sqlite database... that is DBHelper.java
package com.example.medilyf;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class DBHelper extends SQLiteOpenHelper {
public static final String col1="name";
public static final String col2="username";
public static final String col3="email";
public static final String col4="PhoneNo";
public static final String col5="password";
public static final String NAME = "name";
public static final String PHONE = "phone";
public static final String col6="Appointment_id ";
public static final String col7="full_Name ";
public static final String col9="Doc_name ";
public static final String col12="ATime ";
public static final String col8="Phone_Number";
public DBHelper(#Nullable Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(name Text, username Text primary key, email Text, PhoneNo Text, password Text)");
myDB.execSQL("create table appo(Dr Text,time Text, date Text)");
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int oldVersion, int newVersion) {
myDB.execSQL("Drop Table if exists users");
myDB.execSQL("Drop Table if exists appo");
}
public boolean insertData(String name, String username, String email, String PhoneNo, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col1,name);
contentValues.put(col2,username);
contentValues.put(col3,email);
contentValues.put(col4,PhoneNo);
contentValues.put(col5,password);
long result = myDB.insert("users",null,contentValues);
return result != -1;
}
public boolean insertData2(String Dr, String time, String date){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Dr",Dr);
contentValues.put("time",time);
contentValues.put("date",date);
long result = myDB.insert("appo",null,contentValues);
return result != -1;
}
public boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?", new String[] {username});
return cursor.getCount() > 0;
}
public boolean checkusernamepassword(String username, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?", new String[] {username,password});
return cursor.getCount() > 0;
}
}
Can anyone help me with the code to retrieve and display the records of the appointment for another activity in list view..???
I am making a timer as part of my app. I followed a tutorial, and made some modifications to the program to better suit my needs. However, when I run the app, I get the default value of the timerTextView (defined in xml), or just random numbers. What is going wrong?
Update: Here is the coomplete code for the activity:
public class Main7Activity extends AppCompatActivity {
private TextView countDownText;
private CountDownTimer countDownTimer;
//private long timeLeftInMilliseconds = 1000*60*60*24*7*1;
public TextView textView3;
public TextView textView4;
public TextView textView5;
public TextView textView6;
public long timeLeftInMilliseconds;
//private int daysToGo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main7);
textView3 = (TextView) findViewById(R.id.testText);
textView4 = (TextView) findViewById(R.id.testText2);
textView5 = (TextView) findViewById(R.id.testText3);
textView6 = (TextView) findViewById(R.id.testText4);
//textView3.setText(Integer.toString(Main6Activity.progress2));
Calendar now = Calendar.getInstance();
textView3.setText("LMP date : " + Main6Activity.textView.getText());
int currentDayOfYear = now.get(Calendar.DAY_OF_YEAR);
//Day of year is the LMP date
now.set(Calendar.DAY_OF_YEAR, Main6Activity.progress2);
int lmpDate = now.get(Calendar.DAY_OF_YEAR);
//Day of year is due date
now.add(Calendar.DAY_OF_YEAR, 7*40);
textView4.setText("Due Date: " + now.get(Calendar.DATE) + "-"
+ (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.YEAR));
int dueDate = now.get(Calendar.DAY_OF_YEAR);
if (dueDate < 365 && lmpDate > 82){
dueDate = dueDate + (365);
}
if (lmpDate<82 && lmpDate>49){
dueDate = dueDate + lmpDate;
}
if (lmpDate<50) {
textView5.setText("Congratulations on Delivery");
}
else {
textView5.setText(Integer.toString(dueDate));
}
//textView5.setText(now.getTime().toString());
//int currentDayOfYear = Calendar.DAY_OF_YEAR;
int daysToGo = dueDate - currentDayOfYear;
textView6.setText(Integer.toString(daysToGo));
timeLeftInMilliseconds = 1000*60*60*24*daysToGo;
countDownText = (TextView) findViewById(R.id.weeks);
startTimer();
}
public void startTimer(){
countDownTimer = new CountDownTimer(timeLeftInMilliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMilliseconds = millisUntilFinished;
updateTimer();
}
#Override
public void onFinish() {
}
}.start();
}
public void updateTimer(){
int weeks = (int) timeLeftInMilliseconds / 604800000;
int days = (int) (timeLeftInMilliseconds % 604800000) / 86400000;
//int hours = (int) (timeLeftInMilliseconds % 86400000) / 3600000;
//int minutes = (int) (timeLeftInMilliseconds % 3600000) / 60000;
int seconds = (int) (timeLeftInMilliseconds % 60000) / 1000;
String timeLeftText;
timeLeftText = "";
if (weeks < 10) timeLeftText += "0";
timeLeftText += weeks;
timeLeftText += ":";
if (days < 10) timeLeftText += "0";
timeLeftText += days;
//timeLeftText += ":";
//if (hours < 10) timeLeftText += "0";
//timeLeftText += hours;
//timeLeftText += ":";
//timeLeftText += minutes;
//timeLeftText += ":";
if (seconds < 10) timeLeftText += "0";
timeLeftText += seconds;
countDownText.setText(timeLeftText);
}
public void editInfo(View v){
Intent intent = new Intent(Main7Activity.this, Main6Activity.class);
startActivity(intent);
}
}
I also need the timer to run in the background. Will this code do that?
Thanks.
Try to declare those variables :
Handler countHandler ;
Runnable countRunnable ;
private final long INTERVAL = 1000 ; // this the interval period which the timer will be triggered each time
Then change your method like this :
public void startTimer(){
countHandler = new Handler() ;
countRunnable = new Runnable() {
#Override
public void run() {
updateTimer();
timeLeftInMilliseconds= timeLeftInMilliseconds - INTERVAL ;
if(timeLeftInMilliseconds>=0){
countHandler.postDelayed(this, INTERVAL) ;
} else {
cancelTimer(); // here timer is finished
}
}
} ;
countHandler.post(countRunnable) ;
}
public void cancelTimer(){
countHandler.removeCallbacks(countRunnable);
}
Try the code below.
Timer_Service.java
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
public class Timer_Service extends Service {
public static String str_receiver = "your_package_name.receiver";
private Handler mHandler = new Handler();
Calendar calendar;
SimpleDateFormat simpleDateFormat;
String strDate;
Date date_current, date_diff;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
private Timer mTimer = null;
public static final long NOTIFY_INTERVAL = 1000;
Intent intent;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);
intent = new Intent(str_receiver);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
strDate = simpleDateFormat.format(calendar.getTime());
Log.e("strDate", strDate);
twoDatesBetweenTime();
}
});
}
}
public String twoDatesBetweenTime() {
try {
date_current = simpleDateFormat.parse(strDate);
} catch (Exception e) {
}
try {
date_diff = simpleDateFormat.parse(mpref.getString("data", ""));
} catch (Exception e) {
}
try {
long diff = date_current.getTime() - date_diff.getTime();
int int_hours = Integer.valueOf(mpref.getString("hours", ""));
long int_timer = TimeUnit.HOURS.toMillis(int_hours);
long long_hours = int_timer - diff;
long diffSeconds2 = long_hours / 1000 % 60;
long diffMinutes2 = long_hours / (60 * 1000) % 60;
long diffHours2 = long_hours / (60 * 60 * 1000) % 24;
if (long_hours > 0) {
String str_testing = diffHours2 + ":" + diffMinutes2 + ":" + diffSeconds2;
Log.e("TIME", str_testing);
fn_update(str_testing);
} else {
mEditor.putBoolean("finish", true).commit();
mTimer.cancel();
}
} catch (Exception e) {
mTimer.cancel();
mTimer.purge();
}
return "";
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Service finish", "Finish");
}
private void fn_update(String str_time) {
intent.putExtra("time", str_time);
sendBroadcast(intent);
}
}
Your Timer.java activity:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Timer extends AppCompatActivity implements View.OnClickListener {
private Button btn_start, btn_cancel;
private TextView tv_timer;
String date_time;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
EditText et_hours;
SharedPreferences mpref;
SharedPreferences.Editor mEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
init();
}
private void init() {
btn_start = (Button) findViewById(R.id.btn_timer);
tv_timer = (TextView) findViewById(R.id.tv_timer);
et_hours = (EditText) findViewById(R.id.et_hours);
btn_cancel = (Button) findViewById(R.id.btn_cancel);
btn_start.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
mpref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
mEditor = mpref.edit();
try {
String str_value = mpref.getString("data", "");
if (str_value.matches("")) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
if (mpref.getBoolean("finish", false)) {
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
} else {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
tv_timer.setText(str_value);
}
}
} catch (Exception e) {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_timer:
if (et_hours.getText().toString().length() > 0) {
int int_hours = Integer.valueOf(et_hours.getText().toString());
if (int_hours <= 24) {
et_hours.setEnabled(false);
btn_start.setEnabled(false);
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
date_time = simpleDateFormat.format(calendar.getTime());
mEditor.putString("data", date_time).commit();
mEditor.putString("hours", et_hours.getText().toString()).commit();
Intent intent_service = new Intent(getApplicationContext(), Timer_Service.class);
startService(intent_service);
} else {
Toast.makeText(getApplicationContext(), "Please select the value below 24 hours", Toast.LENGTH_SHORT).show();
}
/*
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 5, NOTIFY_INTERVAL);*/
} else {
Toast.makeText(getApplicationContext(), "Please select value", Toast.LENGTH_SHORT).show();
}
break;
case R.id.btn_cancel:
Intent intent = new Intent(getApplicationContext(), Timer_Service.class);
stopService(intent);
mEditor.clear().commit();
et_hours.setEnabled(true);
btn_start.setEnabled(true);
tv_timer.setText("");
break;
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String str_time = intent.getStringExtra("time");
tv_timer.setText(str_time);
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(Timer_Service.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Your activity_timer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/et_hours"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:hint="Hours"
android:inputType="time" />
<Button
android:id="#+id/btn_timer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/btn_cancel"
android:text="Start Timer" />
<Button
android:id="#+id/btn_cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="cancel timer" />
<TextView
android:id="#+id/tv_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="00:00:00"
android:textColor="#000000"
android:textSize="25dp" />
</RelativeLayout>
Resource reference: this link.
You need to do some modifications according to your requirement. The countdown will continue even if you close the app.
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
So... I'm building a little app that stores a time value when the user sets one from the TimePicker buttons. Since the android TimePicker has two values currentHour and currentMinute I figure I need to create two strings (one for the hour one for the minute) then concatonate them into a single string which can be displayed as a time value.
Pretty simple, right?
As of now I've come up with the source below - and I feel like I almost have the TimePicker connected to the string for the time value however I have 3 issues:
timePicker cannot be resolved AddEditCountry.java line 104
minEdit cannot be resolved or is not a field AddEditCountry.java line 37
timePicker cannot be resolved AddEditCountry.java line 103
...not to mention the TimePicker buttons don't change the (combined currentHour and currentMinute) string.
^ - The BIG problem
AddEditCountry.java
import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TimePicker;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
private TimePicker minEt;
public static final String KEY_BUNDLE_TIME = "time";
public static final String KEY_BUNDLE_MIN = "min";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
minEt = (TimePicker) findViewById(R.id.minEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
timeEt.setCurrentHour(extras.containsKey(KEY_BUNDLE_TIME) ? extras.getInt(KEY_BUNDLE_TIME) : 0);
minEt.setCurrentMinute(extras.getInt("min"));
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString(),
minEt.getCurrentMinute().toString(),
codeEt.getText().toString(),
timePicker.getCurrentHour().toString(),
timePicker.getCurrentMinute().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString(),
minEt.getCurrentMinute().toString(),/* Storing as String*/
codeEt.getText().toString());
}
}
}
DatabaseConnector.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseConnector {
public static final String KEY_BUNDLE_TIME = "time";
public static final String KEY_BUNDLE_MIN = "min";
private static final String DB_NAME = "WorldCountries";
private SQLiteDatabase database;
private DatabaseOpenHelper dbOpenHelper;
public DatabaseConnector(Context context) {
dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1);
}
public void open() throws SQLException
{
//open database in reading/writing mode
database = dbOpenHelper.getWritableDatabase();
}
public void close()
{
if (database != null)
database.close();
}
public void insertContact(String name, String cap, String code, String time, String min)
{
ContentValues newCon = new ContentValues();
newCon.put("name", name);
newCon.put("cap", cap);
newCon.put("time", time);
newCon.put("min", min);
newCon.put("code", code);
newCon.put(AddEditCountry.KEY_BUNDLE_TIME, time);
newCon.put(AddEditCountry.KEY_BUNDLE_MIN, min);
open();
database.insert("country", null, newCon);
close();
}
public void updateContact(long id, String name, String cap,String code, String time, String min)
{
ContentValues editCon = new ContentValues();
editCon.put("name", name);
editCon.put("cap", cap);
editCon.put("time", time);
editCon.put("min", min);
editCon.put("code", code);
editCon.put(AddEditCountry.KEY_BUNDLE_TIME, time);
editCon.put(AddEditCountry.KEY_BUNDLE_MIN, min);
open();
database.update("country", editCon, "_id=" + id, null);
close();
}
public Cursor getAllContacts()
{
return database.query("country", new String[] {"_id", "name"},
null, null, null, null, "name");
}
public Cursor getOneContact(long id)
{
return database.query("country", null, "_id=" + id, null, null, null, null);
}
public void deleteContact(long id)
{
open();
database.delete("country", "_id=" + id, null);
close();
}
}
There are quite a few issues in the code.
First, you don't need separate TimePicker widgets for hour and minute. So remove minEt from your code as well as from layout file.
Second, timePicker variable is not declared in the class. Use timeEt instead.
Third, i couldn't find minEdit variable in the class and if its declared in the layout then the compiler shouldn't complain. Anyways remove it as you don't need it.
You may want to take a look at a working example of using TimePicker. Check this out.
Sample Activity:
public class TimePickerActivity extends Activity {
public static final int DIALOG_TIME = 100;
private TextView timeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
timeText = new TextView(this);
setContentView(timeText);
}
#Override
protected void onResume() {
super.onResume();
showDialog(DIALOG_TIME);
}
#Override
protected Dialog onCreateDialog(final int id) {
switch(id) {
case DIALOG_TIME:
Calendar cal = Calendar.getInstance();
TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
timeText.setText(hourOfDay+":"+minute);
}
};
return new TimePickerDialog(this, mTimeSetListener, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), true);
}
return super.onCreateDialog(id);
}
}
I've created a database which stores the currentHour and currentMinute from a timepicker but I'd like to display it in 12 hour format instead of 24 format and my current implemenation of
timeEt.setIs24HourView(false);
isn't working.
P.S.
The 0 integer is also missing from the current minute so the time displays as 14:3 instead of 14:03 [correct 24 hour format] or 2:03 [correct 12 hour format]
Help!
NoobNinja
import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TimePicker;
public class AddEditCountry extends Activity {
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_country);
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
else
{
dbConnector.updateContact(rowID,
nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
}
}
To get a leading 0 for the display of the minutes you could use something like this:
DecimalFormat df = new DecimalFormat ("00");
String minutes = df.format(min);
And to calculate the 12-hour format why don't you just subtract 12 hours if necessary?