No matter what variation of code to display the date is used it won't set the text of the TextView.
public void setDate (View view){
TextView dateView;
Date dNow = new Date();
String str = String.format("Current Date : %tc", dNow);
dateView = (TextView)findViewById(R.id.date_Text_View);
dateView.setText("The date is" + str);
}
Cheers,
Harris
After creating TextView onCreate(), you should call setDate() method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
TextView dateView = (TextView)findViewById(R.id.date_Text_View);
setDate(dateView);
}
public void setDate (TextView view){
String str = String.format("%tc", new Date());
view.setText("The date is " + str);
}
Related
Here dob is String value . How I will get a particular value from String. Please check my code I mention there were I need it.
public class MainActivity extends AppCompatActivity {
private EditText editTextDate;
private Button mButton;
private static final String DATE_FORMAT = "dd/MM/YYYY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
btnClick();
}
private void initView() {
editTextDate = findViewById(R.id.date);
}
private void btnClick() {
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String dob = editTextDate.getText().toString();
// dob is is a date like 25/05/1995
// I want to 1995 value. What will i do??
}
});
}
}
Although, you can go for splitting the string using a regex, but here, this is what you need to learn. SimpleDateFormat. This will give you a lot more control especially when you'll use time with it.
Java
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date yourDate = format.parse("25/05/1995");
Calendar yourCal = new Calendar.getInstance();
yourCal.setTime(yourDate);
Log.d("Tag","Day : "+ yourCal.get(Calendar.DAY_OF_MONTH));
Log.d("Tag","Month: " + yourCal.get(Calendar.MONTH) + 1);
Log.d("Tag","Year: " + yourCal.get(Calendar.YEAR));
Kotlin
val format = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val yourDate = format.parse("25/05/1995")
val yourCal: Calendar = Calendar.getInstance()
yourCal.time = yourDate!!
Log.d("Tag", "Day : " + yourCal[Calendar.DAY_OF_MONTH])
Log.d("Tag", "Month: " + yourCal.get(Calendar.MONTH) + 1)
Log.d("Tag", "Year: " + yourCal.get(Calendar.YEAR))
Remember, month starts from 0 for January so you've to +1 in that, And capital 'M' denotes month in java where as small 'm' denotes minutes. There are lots of formats for SimpleDateFormat, you can use any of them.
Just use the appropriate function.
String#split()
String dob = editTextDate.getText().split("/")[2]
I created buttons for display current time for start and stop parking and its work.
But when I clicked on the deductbtn, the apps on the phone will pop up and show "my Application 1 has stopped"
How can I fix this? Any help will be much appciated.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_info);
firebaseAuth = FirebaseAuth.getInstance();
parkBtn = (Button)findViewById(R.id.parkBtn);
stopparkBtn = (Button)findViewById(R.id.stopparkBtn);
deductBtn = (Button)findViewById(R.id.deductBtn);
timeResult = (TextView)findViewById(R.id.timeResult);
timeResult2 = (TextView)findViewById(R.id.timeResult2);
diffResult = (TextView)findViewById(R.id.diffResult);
parkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Date d = new Date();
SimpleDateFormat sdf1=new SimpleDateFormat("hh:mm a");
final String currentDateTimeString = sdf1.format(d);
timeResult.setText(currentDateTimeString);
}
});
stopparkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Date d1= new Date();
SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm a");
final String currentDateTimeString1 = sdf2.format(d1);
timeResult2.setText(currentDateTimeString1);
}
});
deductBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float totalTime = Float.parseFloat(timeResult2.getText().toString());
float totalTime1 = Float.parseFloat(timeResult.getText().toString());
final float timeUsage = totalTime - totalTime1;
diffResult.setText(String.valueOf(timeUsage));
}
});
}
}
The new code is here :
#Override
public void onClick(View view) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm a");
Date date1 = null;
try {
date1 = simpleDateFormat.parse(timeResult.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = simpleDateFormat.parse(timeResult2.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
String diffResult= DateUtils.getRelativeTimeSpanString(date1.getTime(), date2.getTime(), DateUtils.FORMAT_SHOW_TIME).toString();
deductBtn.setText(diffResult);
}
You are getting exception because
float totalTime = Float.parseFloat(timeResult2.getText().toString());
float totalTime1 = Float.parseFloat(timeResult.getText().toString());
Here, If you click this button after performing click on other buttons, then textview's text will be in the format hh:mm a
And if you click button for the first time without clicking other buttons , The strings will be empty
Both will throw exception
java.lang.NumberFormatException: Invalid float
You can use,
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm a");
date1 = simpleDateFormat.parse(timeResult2.getText().toString());
date2 = simpleDateFormat.parse(timeResult.getText().toString());
String diff= DateUtils.getRelativeTimeSpanString(date1.getTime(), date2.getTime(), DateUtils.HOUR_IN_MILLIS).toString();
Make sure that your textviews strings are not empty before doing it.
public class TestActvity extends AppCompatActivity implements View.OnClickListener {
Button next;
Button previous;
TextView textView;
int interval = 2;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
next = (Button) findViewById(R.id.next);
previous = (Button) findViewById(R.id.previous);
next.setOnClickListener(this);
previous.setOnClickListener(this);
textView = (TextView) findViewById(R.id.textView);
getDate(interval);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.next)
{
interval = interval + 7;
getDate(interval);
} else if (view.getId() == R.id.previous) {
interval = interval - 7;
getDate(interval);
}
}
public void getDate(int interval) {
try {
Calendar c = GregorianCalendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.add(Calendar.DAY_OF_WEEK, interval - 2);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String startDate = "", endDate = "";
startDate = df.format(c.getTime());
c.add(Calendar.DATE, 6);
endDate = df.format(c.getTime());
textView.setText(startDate + " to " + endDate);
Date date = new Date();
String modifiedDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
if ( endDate.compareTo(modifiedDate) > 0) {
Log.d("data", "" + "");
}
Log.d("data", "" + "");
} catch (Exception e) {
}
}
}
Using this code, i am displaying Monday to Sunday like
2017-7-3 to 2017-7-9 ,2017-7-10 to 2017-7-16 ,2017-7-17 to 2017-7-23
,2017-7-24 to 2017-7-30 ,2017-7-31 to 2017-8-5 ...
Receptively but what I want, if current week is
2017-7-24 to 2017-7-30
then when we click on next week it should display it should display only previous week please suggest me in this scenario I will compare date.
if (c.getTime().after(new Date())){
next.setVisibility(View.GONE);
}else {
next.setVisibility(View.VISIBLE);
}
apply this Condition and enjoy !!
i want to take the date that looks like that ("Year-mm-DD") from date picker in android studio and compare if it with the current date when i press a button.
public class UserMenu extends ActionBarActivity {
DatePicker date;
ImageButton next;
Date currentDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_menu);
date = (DatePicker) findViewById(R.id.datePicker);
next = (ImageButton) findViewById(R.id.nxt);
currentDate = new Date();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
String dateFormat = dateformat.format(new Date(date.getYear(), date.getMonth(), date.getDayOfMonth()));
String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(currentDate);
if (dateFormat.compareTo(nowDate) < 0) {
Toast.makeText(getApplicationContext(), "The date is too old", Toast.LENGTH_LONG);
} else {
Intent i = new Intent(UserMenu.this, UserMenuTime.class);
i.putExtra("date", dateFormat);
startActivity(i);
}
}
});
}
}
Use before and after methods to compare dates:
Date pickerDate = new Date(date.getYear(), date.getMonth(), date.getDayOfMonth());
if (pickerDate.before(currentDate)) {
Toast.makeText(getApplicationContext(), "The date is too old", Toast.LENGTH_LONG);
} else {
Intent i = new Intent(UserMenu.this, UserMenuTime.class);
i.putExtra("date", dateFormat);
startActivity(i);
}
I am working on an Android Activity that reads Date of Birth entered by the user and instantiates an object with the value. The date is then stored in an SQLite table. The problem is that I get a NULL date value when I query the table later for the Date.
The date is being received correctly by the constructor of the object. However, it returns NULL when queried for it later.
It will be great if you could point out the error.
Method that reads the Date, instantiates the object and stores in SQLite. The value is being read from EditText dob
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final EditText name = (EditText) findViewById(R.id.nameinput);
final EditText dob = (EditText) findViewById(R.id.dobinput);
final EditText mobile_no = (EditText) findViewById(R.id.mnuminput);
final EditText alt_no = (EditText) findViewById(R.id.altnuminput);
final EditText email_id = (EditText) findViewById(R.id.emailinput);
final EditText home_adr = (EditText) findViewById(R.id.homeadrinput);
final EditText off_adr = (EditText) findViewById(R.id.offadrinput);
final EditText notes = (EditText) findViewById(R.id.notesinput);
final TextView flag = (TextView) findViewById(R.id.insertflaglabel);
String name_converted = name.getText().toString();
String mobile_no_converted = mobile_no.getText().toString();
String alt_no_converted = alt_no.getText().toString();
String email_id_converted = email_id.getText().toString();
String home_adr_converted = home_adr.getText().toString();
String off_adr_converted = off_adr.getText().toString();
String notes_converted = notes.getText().toString();
DateFormat df = DateFormat.getDateInstance();
Date dob_converted = new Date(DateFormat.MEDIUM);
try {
dob_converted = df.parse(dob.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
Log.d("add_client", "Date read is " +dob_converted);
client client_new = new client(name_converted, dob_converted, mobile_no_converted, alt_no_converted, home_adr_converted, off_adr_converted, email_id_converted, notes_converted);
Context context = getBaseContext();
database_handler insert_client = new database_handler(context);
Log.d("add_client", "Date instantiated is " +client_new.getDOB());
insert_client.addClient(client_new);
flag.setText("Client Details Saved!");
}
});
}
Method that queries SQLite for Date of Birth using .getDOB()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_clientdetails);
Bundle extras = getIntent().getExtras();
Integer tab_id = 0;
if (extras != null) {
tab_id = (int) extras.getInt("client_id");
}
TextView namev = (TextView) findViewById(R.id.namevalue);
TextView mobnum = (TextView) findViewById(R.id.mnumvalue);
TextView date_ob = (TextView) findViewById(R.id.dobvalue);
TextView altnum = (TextView) findViewById(R.id.altnumvalue);
TextView off_addr = (TextView) findViewById(R.id.offadrvalue);
TextView home_addr = (TextView) findViewById(R.id.homeadrvalue);
TextView email_addr = (TextView) findViewById(R.id.emailvalue);
TextView notes_client = (TextView) findViewById(R.id.notesvalue);
Context c_displayclient = getBaseContext();
database_handler dhandle = new database_handler(c_displayclient);
String TAG = "display_clientdetails";
Log.d(TAG, "Value of ID is " +tab_id);
final client c_details = dhandle.getClient(tab_id);
namev.setText(c_details.getName());
mobnum.setText(c_details.getMobile_number());
altnum.setText(c_details.getAlt_num());
DateFormat datef = DateFormat.getDateInstance(DateFormat.MEDIUM);
Log.d("display_clientdetails", "Date of Birth is " +c_details.getDOB());
String text_date = datef.format(c_details.getDOB());
date_ob.setText(text_date);
Instantiation Code
// constructor
public client(String name,Date dob,String mobile_number,String alternate_number,String office_address, String home_address,String email_id,String notes)
{
this.name = name;
this.dob=dob;
Log.d("client", "dob received in client constructor is " +this.dob);
this.mobile_number = mobile_number;
this.alternate_number=alternate_number;
this.office_address=office_address;
this.home_address=home_address;
this.email_id=email_id;
this.notes=notes;
}
Method that returns the Date of Birth
// getting Date of Birth
public Date getDOB(){
Log.d("client", "Date returned is " +this.dob);
return this.dob;
}
Method that Adds a new entry to the Database Table
public void addClient(client client_instance) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, client_instance.getName()); // Client Name
values.put(KEY_MO_NO, client_instance.getMobile_number()); // Client Phone
values.put(KEY_DOB, client_instance.getDOB().toString());
values.put(KEY_ALT_NO, client_instance.getAlt_num());
values.put(KEY_OFF_ADR, client_instance.getOff_adr());
values.put(KEY_HOM_ADR, client_instance.getHome_adr());
values.put(KEY_EMAIL, client_instance.getEmail());
values.put(KEY_NOTES, client_instance.getNotes());
db.insert(TABLE_CLIENTS, null, values);
db.close(); // Closing database connection
}
Method for Getting Data from the Database
// Getting single contact
client getClient(int id) {
SQLiteDatabase db = this.getReadableDatabase();
client client_instance = new client();
String TAG ="database_handler";
Cursor cursor = db.query(TABLE_CLIENTS, new String[] {
KEY_NAME, KEY_MO_NO, KEY_DOB, KEY_ALT_NO, KEY_OFF_ADR, KEY_HOM_ADR, KEY_EMAIL, KEY_NOTES}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if(cursor != null) Log.d(TAG, "cursor is not null");
// if(cursor.moveToFirst()) Log.d(TAG, "move to first is true");
if (cursor != null && cursor.moveToFirst()) {
client_instance.setName(cursor.getString(0));
client_instance.setMobileNumber(cursor.getString(1));
//Convert Datefield from String to Date so that the setDOB method can accept it as argument
DateFormat dateform = DateFormat.getDateInstance(DateFormat.FULL);
Date d_of_b = new Date(DateFormat.FULL);
try {
d_of_b = dateform.parse(cursor.getString(2));
} catch (ParseException e) {
e.printStackTrace();
}
//Set Date of Birth
client_instance.setDOB(d_of_b);
client_instance.setAlt_num(cursor.getString(3));
client_instance.setOff_adr(cursor.getString(4));
client_instance.setHome_adr(cursor.getString(5));
client_instance.setEmail(cursor.getString(6));
client_instance.setNotes(cursor.getString(7));
Log.d(TAG, "Email is " +cursor.getString(3));
cursor.close();
}
return client_instance;
}
Method for Setting the Date of Birth into a new Client Instance
public void setDOB(Date dob){
this.dob = dob;
}
Your issue is you have to use the same Date format when you format & parse date.
You should use Specific date format such as "MM/dd/yyyy"
Your solution is
When you format Date ( When inserting client into SQLite)
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
String dobAsString = format.format ( dob_Date_object);
// Store dobAsString in SQLite
When you parse Date (When reading client from SQLite)
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
String dobAsString = // ... Read from SQLite
Date dob = format.parse(dobAsString);
You should not use String for store DATE data. You should use Long datatype (Convert Date to timestamp - long data type). See below reason:
If you use String: "06/12/2014" Greater than "03/12/2015": WRONG!!!
If you use Long: Long_timestamp("06/12/2014") Less than Long_timestamp("03/12/2015"): Correct