date display in listview in android - 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));
// ...
}

Related

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.
}

How to get Time range in array using android

I have an array which having time ranges like below,
String[] str ={"6.30 AM","6.10 AM","10.00 PM","7.00 PM"};
i want to get the minimum time and maximum time in above array such as "6.10 AM" and "10.00 PM".i can find out using sorting but it takes long time.Is any other method avail.Guide me,Below i sorted like,
String[] str ={"1:0 PM","2:0 AM","3:0 PM",.....};
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa", Locale.getDefault());
Date TimeToCompare = null,Time1 = null;
for(int i=0;i<10;i++)
{
TimeToCompare=sdf.parse(str[i]);
for(int j=i+1;j<10;j++)
{
Time1=sdf.parse(str[j]);
if(TimeToCompare.after(Time1))
{
//sorting
}
}
}
This solution makes one pass through the array, keeping track of the min and max times. Runs in O(n).
double maxTime = 0.0;
double minTime = 0.0;
for(String s : str) {
String[] parts = str.split(" ");
double time = Double.parse(parts[0]);
if (parts[1].equals("PM")) {
time += 12;
}
if (time > maxTime) {
maxTime = time;
}
if (time < minTime) {
minTime = time;
}
}
// convert doubles back into strings and print
Date-Time Values
When working with date-time values, it's usually best to work with them as date-time values.
Parse the strings as date-time values, collect them, sort the collection, and retrieve the first and last elements in collection to get earliest & latest values. Convert back to strings if needed.
Joda-Time & java.time
You can easily parse the strings to create date-time objects.
However avoid using the bundled java.util.Date & .Calendar classes in Java as they are notoriously troublesome. Furthermore, they always combine date and time-of-day while in your case you have only a time-of-day.
Use either Joda-Time or the new java.time package in Java 8. Both offer a day-of-time only class, LocalTime.
Example Code
Example code using Joda-Time 2.3.
Convert your array to Collection as I prefer to not work with arrays.
String[] strings = { "6.30 AM", "6.10 AM", "10.00 PM", "7.00 PM" };
List<String> stringList = Arrays.asList( strings );
Create an empty collection to collect our LocalTime objects as we instantiate them.
List<LocalTime> localTimes = new ArrayList<>();
Create a formatter to parse your particular string format. By the way, if you can change the source of these strings, I suggest creating strings in 24-hour format without the "AM/PM", akin to the standard ISO 8601 format.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "h'.'mm aa" );
Loop through our collection of strings, parsing each one. Store the new LocalTime instance in a collection.
for ( String string : stringList ) {
LocalTime localTime = formatter.parseLocalTime( string );
localTimes.add( localTime );
}
Sort the collection of LocalTime objects, to determine the earliest and latest.
Collections.sort( localTimes ); // Ascending order. Earliest first, latest last.
Retrieve the earliest and latest.
LocalTime earliest = localTimes.get( 0 );
LocalTime latest = localTimes.get( localTimes.size() - 1 );
Dump to console.
System.out.println( "localTimes: " + localTimes );
if ( !( localTimes.isEmpty() ) ) {
System.out.println( "earliest: " + formatter.print( earliest ) );
System.out.println( "latest: " + formatter.print( latest ) );
}
When run…
localTimes: [06:10:00.000, 06:30:00.000, 19:00:00.000, 22:00:00.000]
earliest: 6.10 AM
latest: 10.00 PM
Here's a sample solution picked from ggreiner #
How to sort a list of time strings in Java or Groovy
String[] str ={"6.30 AM","6.10 AM","10.00 PM","7.00 PM"};
List<String> times = Arrays.asList(str); // convert int to list
Collections.sort(times, new MyComparator()); // use a custom comparator
Log.i("Min time is ",""+times.get(0));
Log.i("Max Time is ",""+times.get(times.size()-1));
Custom Comparator
class MyComparator implements Comparator<String>
{
private DateFormat primaryFormat = new SimpleDateFormat("h.mm a");
#Override
public int compare(String time1, String time2){
return timeInMillis(time1) - timeInMillis(time2);
}
public int timeInMillis(String time){
return timeInMillis(time, primaryFormat);
}
// in milliseconds
private int timeInMillis(String time, DateFormat format) {
Date date = null ;
try {
date = format.parse(time); //
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (int)date.getTime();
}
}
// Try this way,hope this will help you to solve your problem.
String[] str =new String[]{"6.30 AM","6.10 AM","10.00 PM","7.00 PM"};
ArrayList<Double> list = new ArrayList<Double>();
HashMap<Double,String> map = new HashMap<Double, String>();
for (int i=0;i<str.length;i++){
list.add(Double.parseDouble(str[i].split(" ")[0]));
map.put(Double.parseDouble(str[i].split(" ")[0]),str[i]);
}
System.out.println("Min >> " +map.get(Collections.min(list)));
System.out.println("Max >> "+map.get(Collections.max(list)));
Can you use these, But you may need some pre-arragments
Collections.max(arrayList);
Collections.min(arrayList);
Depending on how you're originally filling the array of values, like are you getting the long from the system then you could compare those. Or create an class that holds the value part and the AM or PM seperately like a flag or something, so then sort between AM and PM then values. I dabbled a lot with java date and calendars, and just use JodaTime. It's convenient!

Sort list with string dates

I have a small problem. I have a ArrayList listOfSData where every element is some like a date: for example:
[30-03-2012, 28-03-2013, 31-03-2012, 2-04-2012, ...]
Now I was wondering how can I sort this list. I mean I want to sort to this
[28-03-2013, 30-03-2012, 31-03-2012, 2-04-2012, etc].
This list must have String values. How can I sort this list? Help me because I have no idea how can I do that.
You will need to implement a Comparator<String> object that translates your strings to dates before comparing them. A SimpleDateFormat object can be used to perform the conversion.
Something like:
class StringDateComparator implements Comparator<String>
{
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
public int compare(String lhs, String rhs)
{
return dateFormat.parse(lhs).compareTo(dateFormat.parse(rhs));
}
}
Collections.sort(arrayList, new StringDateComparator());
here is a small example based on your input. This could be done with a few lines less, but I thought this would be better to understand. Hope it helps.
List<String> values = new ArrayList<String>();
values.add("30-03-2012");
values.add("28-03-2013");
values.add("31-03-2012");
Collections.sort(values, new Comparator<String>() {
#Override
public int compare(String arg0, String arg1) {
SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yyyy");
int compareResult = 0;
try {
Date arg0Date = format.parse(arg0);
Date arg1Date = format.parse(arg1);
compareResult = arg0Date.compareTo(arg1Date);
} catch (ParseException e) {
e.printStackTrace();
compareResult = arg0.compareTo(arg1);
}
return compareResult;
}
});
At first already given answers are write, but that decisions they are not very fast.
Standard java Collections.sort use timsort. In average case it takes O(n*log(n)) comparations, so your custom comparator will call O(n*log(n)) times.
If performance is important for you, for example if you have large array you can do following things:
Convert string dates to int or long timestamps. This takes O(n) operation. And then you just sort array of longs or integers. Comparation of two atomic int are MUCH faster than any comparator.
If you want to get MORE speed for this sort, you can use use Radix sort (http://en.wikipedia.org/wiki/Radix_sort). I takes much memory but we can optimize it. As I see you don't need to specify time of day. So the range of values is not very big.
At firts pass (O(n)) you can convert date to integer value, with next assumptions:
1970 01 01 is start date (or more specific time if you know it) and encode like 1
lets max date is 2170 01 01
all month have 31 day. So You get 31*12 = 372 values per year
And than you can just sort array of integers using radix sort. Sorting values with 200 years range takes only 200 * 372 * 4 = 297600 bytes for merge sort array, but you get O(2 * n) complexisty.
Here is a method I wrote for ordering an array of objects by their time parameter. It's done by comparing 2 String times every time, this can be easily adjusted for your date comparison by changing the pattern parameter to: "dd-MM-yyyy"
int repositorySize = tempTasksRepository.size();
int initialRepositorySize = repositorySize;
Task soonTask = tempTasksRepository.get(0);
String pattern = "HH:mm";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
for (int i= 0; i < initialRepositorySize; i++)
{
for (int j= 0; j < repositorySize; j++)
{
Task tempTask = tempTasksRepository.get(j);
try
{
Date taskTime = simpleDateFormat.parse(tempTask.getTime());
Date soonTaskTime = simpleDateFormat.parse(soonTask.getTime());
// Outputs -1 as date1 is before date2
if (taskTime.compareTo(soonTaskTime) == -1)
{
soonTask = tempTask;
}
}
catch (ParseException e)
{
Log.e(TAG, "error while parsing time in time sort: " + e.toString());
}
}
tasksRepository.add(soonTask);
tempTasksRepository.remove(soonTask);
if ( tempTasksRepository.size() > 0 )
{
soonTask = tempTasksRepository.get(0);
}
repositorySize--;
Try to use SimpleDateFormat with "d-MM-yyyy" pattern:
1. Create SimpleDateFormat
2. Parse listOfSData string array to java.util.Date[]
3. Sort date array using Arrays.sort
4. Convert Date[] to string array using the same SimpleDateFormat

Android: Display time using simpledateformat

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.

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