How do you convert a DatePicker value to a String?
Currently I have a TextView setup, which the DatePicker passes its value to. Its displayed fine. Using that String to pass to a SQLite database isn't working however and returns
android.widget.TextView#41258880
When the databases fields are pulled up. I am currently taking the value and passing it to a string within the following TRY/Catch statement:
case R.id.btnUpdateDB:
boolean worked = true;
try {
String dbWeight = curWeight.getText().toString();
String dbWaist = curWaist.getText().toString();
String dbChest = curChest.getText().toString();
String dbLegs = curLegs.getText().toString();
String dbArms = curArms.getText().toString();
String dbDate = displayDate.toString();
Stats entry = new Stats(MainActivity.this);
entry.open();
entry.createEntry(dbWeight, dbWaist, dbChest, dbLegs, dbArms, dbDate);
entry.close();
break;
I feel that the following line is incorrect:
String dbDate = displayDate.toString();
You called the method toString directly on the widget. According to the source code it prints :
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
That's why you get :
android.widget.TextView#41258880
You have to do instead :
String dbDate = displayDate.getText().toString();
if displayDate is TextView You get its value just like You do with other fields before
String dbDate = displayDate.getText().toString();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
String dateFormat = dateformat.format(new Date(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()));
Related
I am trying to create a named query for all the stringified arguments. This was how my stringified method was:
public Collection<Companypermcache> findExpiredPerms() {
String date = DateUtils.getSQLDate(DateUtils.getToday());
StringBuffer qbe = new StringBuffer("select cpc from Companypermcache cpc");
qbe.append(" where cpc.expire < '"+date+"'");
return super.findByQuery(qbe.toString());
}
I convert this to named query like below
String date = DateUtils.getSQLDate(DateUtils.getToday());
StringBuffer qbe = new StringBuffer("select cpc from Companypermcache cpc");
qbe.append(" where cpc.expire < :date");
return super.findByQuery(qbe.toString(),"date",date);
}
But this generates
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
at org.hibernate.type.descriptor.java.JdbcTimestampTypeDescriptor.unwrap(JdbcTimestampTypeDescriptor.java:24)
at org.hibernate.type.descriptor.sql.TimestampTypeDescriptor$1.doBind(TimestampTypeDescriptor.java:48)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:74)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:248)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:52)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:627) ...
Exception.
However If I update the named query like below I don't have any exception and everything looks good.
String date = DateUtils.getSQLDate(DateUtils.getToday());
DateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
Date edate = simpleDateFormat.parse(date);
StringBuffer qbe = new StringBuffer("select cpc from Companypermcache cpc");
qbe.append(" where cpc.expire < :date");
return super.findByQuery(qbe.toString(),"date",edate);
}
However I really did not understand the difference and and the need of parsing.I have many place in my project where I am using getSQLDate(), So I am concerned whether I want to parse all those dates?
In addition to that type for edate in my table is DATETIME
Why we need to parse the Date when we pass a date as argument to named query????
I am running below command manager procedure in Microstrategy but it does not convert the string into date, tried lot of options. Can someone please assist?
*********** PROCEDURE***************************************
String sQuery = "LIST ALL SUBSCRIPTIONS FOR SCHEDULE \"" + sScheduleName + "\" FOR PROJECT \"" + projectName + "\";";
ResultSet oSubs=executeCapture(sQuery);
oSubs.moveFirst();
while(!oSubs.isEof()){
String sSubsName = oSubs.getFieldValueString(DisplayPropertyEnum.GUID);
ResultSet RecList = executeCapture("LIST ALL PROPERTIES FOR SUBSCRIPTION GUID " +sSubsName+ " FOR PROJECT \"projectname\";");
RecList.moveFirst();
while(!RecList.isEof()){
ResultSet oResultSetSubProps = (ResultSet)RecList.getResultCell(SUBSCRIPTION_RESULT_SET).getValue();
oResultSetSubProps.moveFirst();
while(!oResultSetSubProps.isEof())
{
String d1 = oResultSetSubProps.getFieldValueString(DisplayPropertyEnum.EXPIRATIONDATE);
// the below few lines in red return nothing, its unable to convert to Date as it is unable to recognize the Expiration date in the String format.
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("M/dd/yyyy");
String dateInString = d1;
Date date = formatter.parse(dateInString);
printOut(formatter.format(date));
oResultSetSubProps.moveNext();
}
RecList.moveNext();
}
oSubs.moveNext();
}
This worked for me. The string was neither empty, nor null and no even blank but it would still not parse it so i had to use the length of the string.
java.text.DateFormat formatter = new java.text.SimpleDateFormat("M/d/yyyy",Locale.US);
String dateInString = d1;
if(d1.trim().length()>0)
{
Date date = formatter.parse(dateInString);
if(todaydate.compareTo(date)>0)
{
printOut(name+";"+formatter.format(date));
}
}
if(d1.contains("/"))
{
Date EDate=new Date(d1);
Date today= new Date();
if(d1.compareTo(today)<0)
{
printOut("Expired");
}
}
else
{
printOut("Active");
}
//blank or null values can be handled in Else condition instead.. Hope it helps..
I'm probably being stupid here...but I need help with this one! Basically i need to do a .contains("message") to determine if the key already contains the incoming message.
Thanks in advance!
EDIT: Just as a note, i do not want it to do anything if it already exists! Currently its not adding it to the list.
EDIT2: the date will not matter for the incoming message because the incoming message does not have the date portion.
private Map<Integer,List<String>> map = new HashMap<Integer,List<String>>();
public synchronized void addToProblemList(String incomingMessage, int storeNumber){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
if(map.get(storeNumber)==null){
map.put(storeNumber, new ArrayList<String>());
}
for(String lookForText : map.get(storeNumber)){
if(lookForText.contains(incomingMessage)){
}else if(!lookForText.contains(incomingMessage)){
map.get(storeNumber).add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
}
}
}
It used to look like this, but it always added it:
public synchronized void addToProblemList(String incomingMessage, int storeNumber){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
if(map.get(storeNumber)==null){
map.put(storeNumber, new ArrayList<String>());
}
if(map.get(storeNumber).contains(incomingMessage)==true){
//Do nothing
}
if (map.get(storeNumber).contains(incomingMessage)==false){
map.get(storeNumber).add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
}
What you are adding to the list is a key of the store number and an empty array list,
So the first message for the store you add to the list is empty, therefore your for loop will not execute as it has no elements to iterate.
So add this
if(map.get(storeNumber)==null){
ArrayList<String> aList = new ArrayList<String>();
aList.add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
map.put(storeNumber, aList);
}
Note map.get(storeNumber).contains(incomingMessage)==true you dont need to boolean comparison here as contains() returns a boolean.
The reason this original approach of yours wouldn't have worked is doing a List.contains() means you are doing an check to see if the list contains an exact matching string which it would not have since when you have added the String it also contained "\nTime of incident: "+formattedDate+"\n... which I suspect would not have matched just incomingMessage
You have this:
for(String lookForText : map.get(storeNumber)){
if(lookForText.contains(incomingMessage)){
}else if(!lookForText.contains(incomingMessage)){
map.get(storeNumber).add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
}
}
Try this instead:
List<String> messages = map.get(storeNumber);
if(!messages.contains(incomingMessage)){
map.get(storeNumber).add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
}
I am creating an excel sheet in c: with this name ABC_0607 and it also get created as shown below..
String outputDir = "C:/Report/";
FileOutputStream fw = new FileOutputStream(new File(outputDir, "ABC_0607.xls"));
Now as I am recieving this files on a daily basis and need to be stored in c: drive
so I want to modify it name a little bit that is combination of filename+MM/DD/YYYY
so if today date is 3-July-2013 so file name should be like ABC_0607-MM/DD/YYYY that is ABC_0607-07/03/2013.
PLease advise how to achieve this
You can use this method to retrieve the name of your file:
public String getFileNameFrom(String name) {
String currDate = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
return name + "-" + currDate;
}
Use a StringBuilder initialized with the name of the file.Format the Date using a DateFormat and append the String to it. Put the entire logic inside a method so that it can be reused without code duplication.
I have following code to create name for log file, it can be hourly, daily or minutely(lol)
SimpleDateFormat ymd = new SimpleDateFormat("yyyy_MM_dd");
SimpleDateFormat ymdh = new SimpleDateFormat("yyyy_MM_dd_HH");
SimpleDateFormat ymdhm = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
Calendar dt = Calendar.getInstance();
dt.setTimeInMillis(moment);
String fName;
if (_splitType == SPLIT_HOUR)
fName = ymdh.format(dt.getTime());
else if (_splitType == SPLIT_MINUTE)
fName = ymdhm.format(dt.getTime());
else
fName = ymd.format(dt.getTime());
I'm creating an email using String Template but when I print out a date, it prints out the full date (eg. Wed Apr 28 10:51:37 BST 2010). I'd like to print it out in the format dd/mm/yyyy but don't know how to format this in the .st file.
I can't modify the date individually (using java's simpleDateFormatter) because I iterate over a collection of objects with dates.
Is there a way to format the date in the .st email template?
Use additional renderers like this:
internal class AdvancedDateTimeRenderer : IAttributeRenderer
{
public string ToString(object o)
{
return ToString(o, null);
}
public string ToString(object o, string formatName)
{
if (o == null)
return null;
if (string.IsNullOrEmpty(formatName))
return o.ToString();
DateTime dt = Convert.ToDateTime(o);
return string.Format("{0:" + formatName + "}", dt);
}
}
and then add this to your StringTemplate such as:
var stg = new StringTemplateGroup("Templates", path);
stg.RegisterAttributeRenderer(typeof(DateTime), new AdvancedDateTimeRenderer());
then in st file:
$YourDateVariable; format="dd/mm/yyyy"$
it should work
Here is a basic Java example, see StringTemplate documentation on Object Rendering for more information.
StringTemplate st = new StringTemplate("now = $now$");
st.setAttribute("now", new Date());
st.registerRenderer(Date.class, new AttributeRenderer(){
public String toString(Object date) {
SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
return f.format((Date) date);
}
});
st.toString();
StringTemplate 4 includes a DateRenderer class.
My example below is a modified version of the NumberRenderer on the documentation on Renderers in Java
String template =
"foo(right_now) ::= << <right_now; format=\"full\"> >>\n";
STGroup g = new STGroupString(template);
g.registerRenderer(Date.class, new DateRenderer());
ST st = group.getInstanceOf("foo");
st.add("right_now", new Date());
String result = st.render();
The provided options for format map as such:
"short" => DateFormat.SHORT (default)
"medium" => DateFormat.MEDIUM
"long" => DateFormat.LONG
"full" => DateFormat.FULL
Or, you can use a custom format like so:
foo(right_now) ::= << <right_now; format="MM/dd/yyyy"> >>
You can see these options and other details on the DateRenderer Java source here
one very important fact while setting date format is to use "MM" instead of "mm" for month. "mm" is meant to be used for minutes. Using "mm" instead of "MM" very generally introduces bugs difficult to find.