getInstance Calendar time displaying wrong (12:2am) (under 10 minute error) - Java for Android App Development

Hello.
so i have a onClick that fetches the current time and displays it in a textView box.
The problem comes at (for instance) 12:02am.
The problem is, it displays as 12:2am. missing the first 0. The original code i had didnt have working am/pm, and 12:02am would display as 0:02am(but the rest of the day was in twelve hour format and displayed fine.)
i fixed those, commented in this code below. This currently shows the time as 12:2am
Code:
final Calendar c5 = Calendar.getInstance();
int hour5 = c5.get(Calendar.HOUR_OF_DAY);
int minute5 = c5.get(Calendar.MINUTE);
String a4="am";
if(hour5>=12){
hour5=hour5-12;
a4="pm";
}
//I put this in to get midnight right
if (hour5 <1){
hour5=12;
{
t6.append("12"+c5.get(Calendar.HOUR_OF_DAY)+" ");
}
}
//^^^^^^^^^^^^^^^^^^^
else {
t6.append("0"+c5.get(Calendar.HOUR)+" ");
};
//I have tried stuffing this in with the hour else/if, no dice
if( minute5 < 10)
{
t6.append("0"+minute5+" ");
}
//I've removed and moved this section, took out all the different sections,
//added and remov ed brackets just cuz. most display 12:2am
else {
t6.append(minute5 + " ");
}
{
t6.setText(hour5 + ":" + minute5 + a4);
}
};
Setting it like this, and playing around with the minute5 section, I was able to get it to display 120 02. No thats not a typo. no am/pm, no :, So it wasnt that much better, and i seem to not be able to get back to that point right now.
Yes i searched around a bunch and tried differnet answers, This is the closest i can get though.
If anyone has this code working laying around somewhere it would be much appreciated.
:fingers-crossed:
thanks

out of ideas said:
Hello.
so i have a onClick that fetches the current time and displays it in a textView box.
The problem comes at (for instance) 12:02am.
The problem is, it displays as 12:2am. missing the first 0. The original code i had didnt have working am/pm, and 12:02am would display as 0:02am(but the rest of the day was in twelve hour format and displayed fine.)
i fixed those, commented in this code below. This currently shows the time as 12:2am
Code:
final Calendar c5 = Calendar.getInstance();
int hour5 = c5.get(Calendar.HOUR_OF_DAY);
int minute5 = c5.get(Calendar.MINUTE);
String a4="am";
if(hour5>=12){
hour5=hour5-12;
a4="pm";
}
//I put this in to get midnight right
if (hour5 <1){
hour5=12;
{
t6.append("12"+c5.get(Calendar.HOUR_OF_DAY)+" ");
}
}
//^^^^^^^^^^^^^^^^^^^
else {
t6.append("0"+c5.get(Calendar.HOUR)+" ");
};
//I have tried stuffing this in with the hour else/if, no dice
if( minute5 < 10)
{
t6.append("0"+minute5+" ");
}
//I've removed and moved this section, took out all the different sections,
//added and remov ed brackets just cuz. most display 12:2am
else {
t6.append(minute5 + " ");
}
{
t6.setText(hour5 + ":" + minute5 + a4);
}
};
Setting it like this, and playing around with the minute5 section, I was able to get it to display 120 02. No thats not a typo. no am/pm, no :, So it wasnt that much better, and i seem to not be able to get back to that point right now.
Yes i searched around a bunch and tried differnet answers, This is the closest i can get though.
If anyone has this code working laying around somewhere it would be much appreciated.
:fingers-crossed:
thanks
Click to expand...
Click to collapse
I haven't worked with the Calendar object yet, but it is a lot easier with Android's Time() object like this:
(This is a method that creates a filename like this:
Code:
filename_2013_05_30_110330
)
Code:
import android.text.format.Time;
private String setTime(){
Time now = new Time();
now.setToNow(); // gets the current time
char seperator= '_';
String filename = getString(R.string.filename) + seperator + Integer.toString(now.year)
+ seperator + Integer.toString(now.month+1) + seperator + Integer.toString(now.monthDay)
+ seperator + Integer.toString(now.hour) + Integer.toString(now.minute) + Integer.toString(now.second);
return filename;
}
You can use the now.hour but I think it shows in 24 hours system, use
Code:
int hour5 = now.hour;
if(hour5>12){
a4 = "pm";
hour5 = hour5-12;
} else {
a4 = "am";
}

Related

Need C# xml ready/write example - Stummped!

OK I am writing my first Mobile 6 App, based on compact framework 2, obviously finding some differences from Framwork vs compact when dealing with reading and writting simple values to xml;
Here is what I want to do: write two textbox values to xml as follows:
<settings>
<hostip>192.168.0.14</hostip>
<hostport>8011</hostport>
</settings>
So I got the above accomplished using the following code:
--------------------
string hstip = "";
string hstport = "";
hstip = this.HostIP.Text.ToString();
hstport = this.HostPort.Text.ToString();
XmlWriterSettings xml_settings = new XmlWriterSettings();
xml_settings.Indent = true;
xml_settings.OmitXmlDeclaration = false;
xml_settings.Encoding = Encoding.UTF8;
xml_settings.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter xml = XmlTextWriter.Create(GetApplicationDirectory() + @"\settings.xml", xml_settings))
{
xml.WriteStartElement("settings");
//xml.WriteStartAttribute("hostip", "");
xml.WriteElementString("hostip", hstip);
//xml.WriteString(hstip);
//xml.WriteEndAttribute();
xml.WriteElementString("hostport", hstport);
//xml.WriteStartAttribute("hostport", "");
//xml.WriteString(hstport);
//xml.WriteEndAttribute();
xml.WriteEndElement();
//ds.WriteXml(xml);
xml.Close();
}
-----------end of write code------------
Now the part I am stumped on as I have tried all varietions to get the data back into the textboxes, I either get and exception or blank values in the textboxes.
Here is the code:
------------------
private void SrvSettings_Load(object sender, EventArgs e)
{
XmlReaderSettings xml_settings = new XmlReaderSettings();
xml_settings.IgnoreComments = true;
xml_settings.IgnoreProcessingInstructions = true;
xml_settings.IgnoreWhitespace = true;
xml_settings.CloseInput = true;
try
{
using (XmlReader xml = XmlTextReader.Create(GetApplicationDirectory() + @"\settings.xml", xml_settings))
{
xml.ReadStartElement("settings");
xml.Read();
xml.ReadElementString(,,)
//xml.ReadToFollowing("hostip");
this.HostIP.Text = xml.GetAttribute("hostip","");
//this.HostIP.Text = xml.GetAttribute("hostip");
//xml.ReadToFollowing("hostport");
this.HostPort.Text = xml.GetAttribute("hostport","");
// Close it out----------------
xml.ReadEndElement();
xml.Close();
//ds.ReadXml(xml);
// }
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(
ex.ToString(), "Error Loading IP settings");
}
}
------------end of read code
obviously I get an exception with this:
"System.xml.xmlexception:
"Text" is an invalid XmlNoteType. Line 2, posistion 11 at
System.xml.xmlReader.ReadEndElement()"
-----
I suspect I need to use ReadElementString, but I have tried and no workie...
Somebody have an example/class for both reading and writing per my requirements above, I would really appreciate the help..
Use XmlDocument
Try using the XmlDocument instead. It's alot easier to use for simple xml reading/writing.
Well Partially working now - I get the Hostport populated but for some reason hostip is blank even though it appears it falls through it in the case statement.. wierd..
DataSet ds = new DataSet();
XmlReaderSettings xml_settings = new XmlReaderSettings();
xml_settings.IgnoreComments = true;
xml_settings.IgnoreProcessingInstructions = true;
xml_settings.IgnoreWhitespace = true;
xml_settings.CloseInput = true;
try
{
using (XmlReader xml = XmlTextReader.Create(GetApplicationDirectory() + @"\settings.xml", xml_settings))
{
xml.MoveToContent();
xml.ReadStartElement("settings");
while (xml.Read())
{
//xml.Read();
switch (xml.Name)
{
case "hostip":
HostIP.Text = xml.ReadString(); <--I get Blank text
break;
case "hostport":
HostPort.Text = xml.ReadString(); <--POpulated OK
break;
default:
break;
}
// Close it out----------------
//xml.ReadEndElement();
}
xml.Close();
//ds.ReadXml(xml);
// }
}
}
Solved, Had to remove the line: xml.ReadStartElement("settings");
Thanks..
Just out of curiosity, what will your app do ?
I'm writing a WPF Windows App that monitors Server Services, IPs, Websites for up or down status; buiding a client server component to it, so the end goal will be to use the mobile app to connect to the host and download status on said servers being monitored and populate them in a listview whith thier up or done status.
Simple app but still in the works.
if you can make it customizable (to set up parametres, adreses) it wil be useful for many website administrators
a cool little app

[Q] Searching through flat files

Hello,
Does anyone knows of a good resource where I can learn how to search/find through a flat file? I have a flat file that each character in the row is separated by a space (ex: 01242 PHXX) and all I am trying to do is search for the first characters (01242) but display the second set of characters (PHXX). I been searching online and so far I have gotten as far as being able to display the content of the flat file but nothing specific on how to go about doing what I am trying to do.
Any advice will be greatly appreciated.
Have you looked at StringTokenizer()?
http://developer.android.com/reference/java/util/StringTokenizer.html
Gene Poole said:
Have you looked at StringTokenizer()?
http://developer.android.com/reference/java/util/StringTokenizer.html
Click to expand...
Click to collapse
Thanks!! It helped so much. I to looked deeper into StringTokenizer and using several of tutorials I was able to exactly do what I was looking for:
Code:
InputStream file = getResources().openRawResource(R.raw.file_raw_data);
Scanner scan = new Scanner(file);
search = (int) search1;
outer_loop:
while (scan.hasNextLine()) {
String line = scan.nextLine();
StringTokenizer st = new StringTokenizer(line, " ");
while (st.hasMoreTokens()) {
String word = st.nextToken();
String test1 = st.nextToken();
if (word.equals(search)) {
Firstconvert.setText(test1);
break outer_loop;
} else {
Firstconvert.setText("Not Found");
}
}
}
scan.close();
It may not be perfect but at least its a very good start. Thank you so much again!!

[Q] DatePickerDialog cancelclick

Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
cTrox said:
Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
Click to expand...
Click to collapse
the "checked" solution in that example seems wrong to me. but the second one people voted up seems correct.
You can also set the onDissmissListener which will catch if the user backs out with the back key ( recommended for user friendliness )
have a look here:
http://developer.android.com/refere...id.content.DialogInterface.OnDismissListener)
Also, since DatePickerDialog is a subclass of AlertDialog, you can set the buttons the same way:
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
That should get you started but feel free to post back if you get stuck again. And post the code you are using.
Also, one other thing, it might be useful to keep a private reference to your dialog in your activity class.
All those examples (in the API docs and tutorials) always show a new dialog created when "onCreateDialog(int ID)" is called by the OS on your activity and they never save any sort of reference to it. They give you just enough code to hang yourself
Anyways, while this is a perfectly normal way to do things, it doesnt give you a chance to follow what is actually happening with the dialog. It also makes it harder to reference your dialog from elsewhere in the activity.
Keeping a reference, and exploring the onPrepareDialog(int ID) method are good for learning what the OS is doing with your dialog. (IMHO)
hth
Thanks a lot for your answers. But I still can't figure out how to do it.
Here's my current Code:
Code:
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datePicker, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
// do some more stuff...
}
};
Code:
protected Dialog onCreateDialog(int id) {
Calendar cDate = Calendar.getInstance();
int cyear = cDate.get(Calendar.YEAR);
int cmonth = cDate.get(Calendar.MONTH);
int cday = cDate.get(Calendar.DAY_OF_MONTH);
switch(id){
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
}
return null;
}
With that I can just call showDialog(DATE_DIALOG_ID); and I get the dialog. Now, where do I have to implement this OnDismissListener and how?
Thanks!
there are lots of ways to do this but I broke it out into several parts so hopefully it seems more obvious what is happening.
Code:
//here's our field reference we could use later or reuse or whatever
private DatePickerDialog dateDialog = null;
protected Dialog onCreateDialog(int id)
{
//your calendar code here... just removed to save space
switch(id)
{
case DATE_DIALOG_ID:
dateDialog = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
dateDialog.setButton ( DialogInterface.BUTTON_NEGATIVE, android.R.string.cancel, cancelBtnListener );
dateDialog.setOnDismissListener ( listener );
break;
}
return dateDialog;
}
//our dismiss listener
protected DialogInterface.OnDismissListener dismissListener = new OnDismissListener( )
{
@Override
public void onDismiss ( DialogInterface dialog )
{
// do your thang here
}
};
//our click listener
protected DialogInterface.OnClickListener cancelBtnListener = new OnClickListener( )
{
@Override
public void onClick ( DialogInterface dialog, int which )
{
dialog.dismiss ( );
// since we dismiss here, the next listener to get called
// is the dismiss listener. now we'll have consistent behavoir
}
};
Ah thank you very much! I was always confused, where to set the Button and the OnDismissListener.
It works perfectly like that!

[REQ] MODE10 Editor for Sense 3.0

Hello developers,
While working on the Sense 3.0 port we have across a new format scene used by HTC in thier next Sense 3.0 version. I know it must be a annotation from thier older m9 format which use to be in the Windows Mobile 6.5 Manila or Sense.
We @ HTC Desire HD forums are working hard to crack open this format but its just proving to be impossible as these files according to some are the one's responsible for the resolution on other devices.
I thereby would like to request anyone with some knowledge about this new format come forward, and share his ideas and discussions in this thread. And thus making the new challenge given by HTC to developers like us. If anyone has any information any thoughts please comment and dont please do not hesitate to share your ideas and thoughts about it.
Mode10
What is mode10?
HTC is using a new format in their next Sense version that is being currently employed in the 3rd Generation devices like HTC Sensation, HTC EVO 3D, HTC Flyer. This file is resposible for according to current knowldege for the proper resolution and display of Sense items and widgets on the screen.
What we know until now ?
Diamondback @ HTC Desire HD has made a program which analyses the values inside the .m10 format files and had found out that these files might be resposible for the screen resolution.
Why it is important ?
Most of the devices here have a WVGA,HVGA or a lower resolutions whereas HTC has deployed the new Sense 3.0 only on the qHD screens and is lieing to us that this new Sense will only work on the new Dual Core devices. Capychimp @ HTC Desire HD has successfully ported the rom to a WVGA resolution but the rosie.apk and the other Sense widgets related to it are not showing up properly on the WVGA screen. In order to make these work we need to modify some strings inside the .m10 files.
Seems lik no one is interdted in porting the new sense rom on thier devices!!!
Sent from my Desire HD using XDA Premium App
I would've though this would apply to all older HTC phones like HD2, Desire etc. too... Perhaps the devs from those phones would chime in to crack this thing open?
I originally found the hex values (in little endian DWORDs) for the qHD resolution (960x540) in the m10 files -- C0 03 00 00 1C 02 00 00. With that, Diamondback and Tremmard tested by changing the values but found that it did not change anything. Diamondback then found another value which is a 960x530 one which he (or Tremmard) tested and found it to offset the container (hence the 'progress' of lockscreen posted in DHD forum -- i.e. centering of the lockscreen).
We also know the file ID in the header is the "!01m" bytes. If we could add more tech info to this thread, perhaps we could get more ppl adding more stuff as we go along.
Hi guys,
Even if zachs_xda ruined my nickname DiamondBack and me are working on a m10 'extractor' software, to be able to edit and customize m10 files.
Be patient, developpement goes pretty fast, so I think you'll get some results in the days/weeks to come
here is my code to convert dec to m10 and back;
Code:
Public Int ConvertToDec(String in){
//String out = (Integer.decode("0x" + backToNormal(in)).toString());
return int i = Integer.parseInt(backToNormal(in),16);
}
public String ConvertToM10(Int in) {
String hexstr = Integer.toHexString(in);
Return format(hexstr.toUpperCase());
}
public static String backToNormal(String in) {
char[] buf1 = in.replaceAll(" ", "").replaceAll("0000", "").toCharArray();
char[] buf2 = new char[buf1.length];
for (int i = 0; i < buf1.length - 1; i++) {
try {
buf2[i + 1] = buf1[i];
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
}
buf2[0] = buf1[buf1.length - 1];
}
String out = "";
if (buf2[buf2.length - 1] == '0') {
for (int i = 0; buf2.length - 1 > i; i++) {
out += buf2[i];
}
} else {
for (int i = 0; buf2.length> i; i++) {
out += buf2[i];
}
}
return out;
}
public static String format(String in) {
String out = in;
if (in.getBytes().length % 2 == 0) {
} else {
out = in + "0";
}
return addSpaces(revert(out)) + "00 00";
}
public static char[] revert(String in) {
char[] out = in.toCharArray();
char[] buf = in.toCharArray();
for (int i = 0; in.length() - 1 > i; i++) {
try {
out[i] = buf[i + 1];
} catch (Exception e) {
System.out.println(e);
}
out[out.length - 1] = buf[0];
}
return out;
}
public static String addSpaces(char[] in) {
char[] buf = new char[(int) (in.length * 1.5)];
try {
for (int i = 0, j = 0; buf.length > i; i++, j++) {
try {
if (j % 2 == 0 && j != 0) {
buf[i] = ' ';
i++;
}
buf[i] = in[j];
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
}
}
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
}
String out = "";
for (int i = 0; buf.length > i; i++) {
out += buf[i];
}
return out;
}
Hey guys,
it's done! The first version of our (Flemmard and me) M10Editor is released.
Check out the original thread here.

Http request incomplete response

hi folks,
here is the code and I've seen basically the same thing from several sources, I compare with them all and it doesn't seem to be any problem with it:
Code:
private static String HttpCall(String url) throws URISyntaxException,
IOException {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
Log.d("Pristina", "URL: " + url);
Log.d("Pristina", sb.toString());
return sb.toString();
} finally {
if (in != null) {
in.close();
}
}
}
I'm pretty much getting an HttpClient, HttpGet and HttpResponse, getting the InputStream out of it and returning it as a String... it was supposed to be piece of cake.
I'm using this to get a JSON object from a Wordpress blog which have the JSON plugin installed.
I tried the URL on my desktop chrome browser and the response is absolutely perfect, no problems. Most of the time the response from this code is fine too, it was working fine a few days ago... but now the response comes incomplete... I mean.. the string out of it is going fine as a JSON object and all of a sudden it's over. It end's as:
Code:
"width" : 500,
"height" : 500
}
}
}, {
"id" : 37525,
"url" :
no if's no buts... it's giving me the correct info and it says it will give me a url and that's it... the string is over!
From stack overflow someone suggested using EntityUtils.toString(response.getEntity()); and I still can't get a valid response. In this blogpost http://blog.dahanne.net/2009/08/16/how-to-access-http-resources-from-android/ the guy shows a few ways of doing an Http request I tried the 1st one and the final string I get it's still incomplete.
I would normally think it's something wrong with the JSONplugging installed on the server.. but the response is just fine from Chrome browser.
any ideas ??? I really don't know what else to do.
up!
anyone? please.... I've been desperate trying to find a solution for days now!
Just to "close" the post.
at the end was a mix of LogCat only showing a mix of X chars and a problem in a completely different point in my parser!
also at the end I found out this:
Code:
ret = new String(EntityUtils.toString(entity));
being a much cleaner code than the stupid loops.
if any forum moderator sees this feel free to close the thread.

Categories

Resources