Android: Display time using simpledateformat - android

I am trying to display the time that a user enters, either in a toast or using a basic println command. If the time is in the correct format, I want to enter it in a database along with the current time.
Here is what I have so far:
public void addListenerOnButton ()
{
spinner_hours = (Spinner)findViewById(R.id.hours);
spinner_minutes = (Spinner)findViewById(R.id.minutes);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Date time;
String enteredTime= String.valueOf(spinner_hours.getSelectedItem())+String.valueOf(spinner_minutes.getSelectedItem())+"00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
try {
time= format.parse(enteredTime);
System.out.println(enteredTime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Toast.makeText(MainActivity.this,
// "Your alarm has been set for : " + time,
// Toast.LENGTH_SHORT).show();
}
});
}
If I put the toast (commented below) inside the try block, it doesnt show up when I run the app. If I put a system.out.println it does not print anything. How do I print the entered time?
Also, I want to enter the current time in the same format ("HH:mm:ss") in the database. Any ideas on how to do that?

It's probably throwing an exception, since System.out.println should work. Try replacing this:
String enteredTime= String.valueOf(spinner_hours.getSelectedItem())+String.valueOf(spinner_minutes.getSelectedItem())+"00";
by this:
String enteredTime= String.valueOf(spinner_hours.getSelectedItem())+ ":" + String.valueOf(spinner_minutes.getSelectedItem())+":00";
It seems you're missing the : between hour and minutes and before 00 and the parsing is failing.

First try to print the value got from the Spinner
System.out.println(spinner_hours.getSelectedItem().toString());
System.out.println(spinner_minutes.getSelectedItem().toString());
If this doesn't has any value then the problem is here.

Related

How to manage viewmodel

I have an activity that has a view model. When I call 2 methods of that view model first execute second method. Why?
How can I manage that methods?
This is onCreate of the activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news_letter);
dbViewModel = new ViewModelProvider(this).get(DBViewModel.class);
dbViewModel.getLastUpdate().observe(this, s -> {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
try {
Date date = format.parse(s);
timeStamp = (int)date.getTime() / 1000;
getAllNews(BaseCodeClass.CompanyID, timeStamp);
} catch (ParseException e) {
e.printStackTrace();
}
});
dbViewModel.getAllNews().observe(this, newsLetters ->
{
Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
});
}
In this method first dbViewModel.getAllNews() is executed then dbViewModel.getLastUpdate()
When you observe a LiveData, it will call the onChanged method on its observers when the data is ready or when the data changes. When you observe two or more LiveDatas in a certain order, it doesn't mean that the observers will be called in that order as well. It will happen sometime when the data is ready. That's exactly the behavior of observable fields like LiveData.
If you want to read those values in that exact order and only once, you can call getValue() and get the value right away instead of observing them:
String s = dbViewModel.getLastUpdate().getValue();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
try {
Date date = format.parse(s);
timeStamp = (int)date.getTime() / 1000;
getAllNews(BaseCodeClass.CompanyID, timeStamp);
} catch (ParseException e) {
e.printStackTrace();
}
var newsLetters = dbViewModel.getAllNews().getValue();
Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
Those values will be read in that order, but they won't be called again if the LiveData values change.

Get date from Edittext to DayDecorator

first of all thanks for reading this :)
Here is my problem.
I got an EditText (User date input) and i want to get a colored background on my CustomCalander for that day using DayDecorator.
//EditText I want to get the date
huablauf = (EditText)getActivity().findViewById(R.id.huablauf);
//adding calendar day decorators
List<DayDecorator> decorators = new ArrayList<>();
decorators.add(new Markierung());
calendarView.setDecorators(decorators);
calendarView.refreshCalendar(currentCalendar);
//class Markierung
private class Markierung implements DayDecorator {
EditText huablauf=(EditText)getActivity().findViewById(R.id.huablauf);
#Override
public void decorate(DayView dayView) {
// I know I have to get my String to a date and then get it to
// dayView.getDate()! But my code didnĀ“t work
dayView.getDate();
int color = Color.parseColor("#f9acb8");
dayView.setBackgroundColor(color);
}
Hope you can understand my problem and anybody can help :)
Thx from Bavaria
Try this:
#Override
public void decorate(DayView dayView) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
try{
if(dayView.getDate().equals(dateFormat.parse(huablauf.getText().toString()))){
int color = Color.parseColor("#f9acb8");
dayView.setBackgroundColor(color);
}
} catch (Exception e){
//Handle exception.
}

date display in listview in android

I am trying to display a date in descending order in listview in android... I have written a program... It is showing it correctly, but when the first date of the month coming, the last month date are not displaying only one date is showing... What is the reason? How do I improve my code? Please guide me..
my code is here...
public void datesadd()
{
listview.setAdapter(new ListAdapter(this));
cc1=Calendar.getInstance();
int mon1=cc1.getTime().getDate();
Date dd=new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
while(mon1>=count)
{ pos=0;
line=new HashMap<String,String>();
String cdat=String.valueOf(cc1.get(Calendar.DATE));
#SuppressWarnings("deprecation")
String mons=String.valueOf(cc1.get(Calendar.MONTH));
String day1=String.valueOf(cc1.getTime().getDay());
#SuppressWarnings("deprecation")
String year1=String.valueOf(cc1.get(Calendar.YEAR));
try {
dd=format.parse(year1+"-"+mons+"-"+cdat);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
line.put("yeari", year1);
line.put("mont",mons);
line.put("dayi",dd.toString().substring(0, 3));
line.put("datei",cdat);
mon1--;
cc1.add(Calendar.DATE, -1);
Log.v("", "line");
disp.add(line);
// here disp is ArrayList<Hashmap<String,String>> object, i was declared it on top of my main program
}
}
I don't think you're going about date iteration right -- you're just iterating over the value in miliseconds.
Consider this:
/* From your code I'm not sure what count is, but you get the idea, you need
* a Date object here or you can just use a for() loop if you know the number
* |
* V */
while (cc1.getTime().after(count)) {
cc1.add(Calendar.DAY_OF_YEAR /*or month, year, whatever*/, -1);
// and then continue with your own code
line = new HashMap<String,String>();
String cdat = String.valueOf(cc1.get(Calendar.DATE));
// ...
}

displaying toast in conditional statements in android

i have created an app which insert data to sql server. i made column NAME as unique key.
i want that if i enter same name by edittext to insert...it should give a toast message.
but it's not happening. i cann't understand where i have made error.
in connection to server there is no problem. the only thing is i have to display Toast msg if i entered same name again.
my code is.......
public void onClick(View v) {
// TODO Auto-generated method stub
String myloc=loc.getText().toString();
String myname=name.getText().toString();
String myphone=phone.getText().toString();
initilize();
ResultSet rs;
try{
Statement statement=connect.createStatement();
rs=statement.executeQuery("SELECT * FROM FORM1");
List<Map<String,String>>data=null;
data=new ArrayList<Map<String,String>>();
while(rs.next()){
Map<String,String>datanum=new HashMap<String,String>();
datanum.put("a", rs.getString("NAME"));
data.add(datanum);
}
if(data.contains(myname)){
Toast.makeText(c, myname+" Already stored: please choose different one", Toast.LENGTH_LONG).show();
}
else{
insert(myname,myphone,myloc);
}
}catch(Exception e){
Log.e("ERROR", e.getMessage());
}
}
plzz guys...help me someone...
With data.contains(myname) you are trying to check if there is myname of type String in your data varible, but, in fact, your data have type List<Map<String,String>>, so when you are invoking contains(Object object) method passing a String, you are performing equals operation between Map<String,String> and String, which clearly would always result false. So I would suggest you either write something like this
List<String> data = new ArrayList<String>();
while(rs.next()) {
data.add(rs.getString("NAME"));
}
if(data.contains(myname)){
Toast.makeText(c, myname+" Already stored: please choose different one", Toast.LENGTH_LONG).show();
}
or there is a better way, just change your query to SELECT * FROM FORM1 WHERE NAME = myname and check if your result set is empty.

Get date/time with SimpleDateFormat

folks!
I've got such date entry:
<pubDate>23/06/2011 11:57</pubDate>
I try to parse it:
mDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
item_tag.getChild("pubDate").setEndTextElementListener(new EndTextElementListener() {
#Override
public void end(String body) {
date= new GregorianCalendar(0,0,0).getTime();
try {
date=mDateFormat.parse(body);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
But I get something like that: 23/57/2011 11:57 I get minutes instead of month value
What's wrong with my code?
Your code looks OK. Check out what do you really pass to this method, or just check what will happen if you insert line like:
body = "23/06/2011 11:57";
As shown in examples here, you should use '-' instead of '/' when instantiating a mask.

Categories

Resources