I'm trying to modify an existing notepad example from the Android Developer site. I have a database with an existing column named CREATED_DATE(of the note) but the data for that column is presented as System.currentTimeMillis(). This is all good and probably in line with conventions since it's created by the developers.
But my problem is that I want to present the date in a ListView using the format "30 sep". My problem, how do I convert the data to that format before presenting it in the ListView? Right now I'm using this kind of adapter:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.noteslist_item, cursor,
new String[] { Notes.TITLE, Notes.CREATED_DATE }, new int[] { R.id.note_title, R.id.note_date });
setListAdapter(adapter);
Now, I've figured out how to convert currentTimeMillis() to today's date but how can I convert the data coming from the cursor before I toss it into the adapter?
If I understand your question correctly, take a look at the Date and SimpleDateFormat classes in order to convert your ms long into a String representation.
(There are lots of examples on stackoverflow on how to actually use those classes)
You have to change the ViewBinder. Have a look at this Changing values from Cursor using SimpleCursorAdapter
It helped me..
Related
On the material page I found the following example for AutoCompleteTextView:
int layoutItemId = android.R.layout.simple_dropdown_item_1line;
String[] dogArr = getResources().getStringArray(R.array.dogs_list);
List<String> dogList = Arrays.asList(dogsArr);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, layoutItemId, dogList);
AutoCompleteTextView autocompleteView =
(AutoCompleteTextView) findViewById(R.id.autocompleteView);
autocompleteView.setAdapter(adapter);
Source: https://materialdoc.com/components/autocomplete/
What is the point of this part:
List<String> dogList = Arrays.asList(dogsArr);
Why turning it into an ArrayList when the AutoCompleteTextView also takes a String array?
When you know only going to work with a fixed number of elements, you should Array. If not, use Lists.
My personal opinion is use list. Lists makes code very inflexible and easy to use.
You can initialize Java arrays at compile time, like:
String data[] = { "a", "b", "c" };
In old versions of Java there was also the case for type safety. ArrayList elements had to be casted to the original type whereas Java arrays where type safe.
Java arrays are part of the language and you will not be able to change them. ArrayList is part of the Java API. If you need (I do not recommend it though) you could substitute your own library to implement the ArrayList job
Check This Question For More Information
See This question
If you have an array, it has to have a fixed size. Dynamically adding and removing the elements are difficult to manage and you have to have new array created every time you add a new item. Similarly for removing item.
With ArrayList it is easy to manage as it doesn't get created with a static size. Thus at runtime you can easily add and remove elements.
ArrayList is the ideal datastructure to use here.
I need help with csv, I only started learning how to use it yesterday, and I can't find a solution for that problem.
I have a csv file with some array: "name, address, id", using Opencsv.
Now I want to be able to add corresponded strings in the row below it.
For example, if the user press some button, the name "david" will be added the the csv file, and it will look like:
"name,address,id"
"david"
and when the user will press other button, the adress "3 street" will be added, so it will look like:
"name,address,id"
"david, 3 street"
and so on, so in the end there will the a list of names and their address and id. I just can't figured out how to do it and I cant anything similar. Maybe there is another way to do it?
Let me try to understand what you mean,
In scenario 1, you should have only name added,
In scenario 2, you should have name,address added,if that is what I understand?
This is simple and quite achievable.
Firstly I am assuming you have already created the row part in your csv and saved to your sd-card
In the next part it should be using an arraylist to write to your csv, check out the code below
String csv = "C:\\work\\output.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
List<string[]> data = new ArrayList<string[]>();
data.add(new String[] {"India", "New Delhi"});
data.add(new String[] {"United States", "Washington D.C"});
data.add(new String[] {"Germany", "Berlin"});
writer.writeAll(data);
writer.close();
Take this arraylist when its your scenario 2.
Also create a separate arraylist which will contain single column data and populate in the same way for scenario 1.
You need to do proper null-checks in scenario 1, else it will throw NullPointer Exception.
Most final approach create two separate methods
Method1- for writing only single column data to your csv.(where you should properly handle the nullchecks)
Method2-the sample code provided
For more reference
http://www.codeproject.com/Questions/491823/Read-fWriteplusCSVplusinplusplusAndroid
Hope this works.
I have a question. In my app I have saved in my database some lists. Each list has asociated a date in this format 6-June-2011. How can I order these lists by date? I wrote I function like that :
public Cursor getAll(){
return (mDb.rawQuery("SELECT _id, Title, Shop , Data , Budget_allocated ," +
" Budget_spent FROM Lists ORDER BY Data",null));
}
but it doesn't work fine. I think it compare only the day. For example, if I have 31-May-2011 and 6-June-2011, it will say that the first date is after the second date.
It is possible what I am trying to do? Should I modify the date in format like this :6-06-2011?
Thanks..
I don't know anything about android development, but it sounds like your date field is stored as a string rather than a date, is that correct?
If so, you can either:
Change your table so that field is a date (then it should compare correctly)
Or store it in a standard format such that the default string comparison sorts dates correctly. Since string comparison sorts first on first character, second on second character, etc, this would be putting the biggest time difference first, ie. "2011-05-31" (include the zeroes).
(You should be able to convert the field by making a new field, copying the data from the old field into the new field in the correct format, and then deleting the old field and renaming the new one, or more simply if you simply want to change the format of the text. You should be able to do this either from code, or with an "update" query, AFAIK.)
Use a date format as follows...yyyy-MM-dd HH:mm:ss. This is guaranteed to be sortable in ascending or descending order.
If your Data column is not of type datetime there may be an issue. Take a look at this related SO question and answers:
SQL ORDER BY date problem
I have received several requests to adjust the way list items are displayed on my media player application.
Currently any entry beginning with "The" is sorted with the T's as you would expect. Many users would like to sort the item using the second word in the title.
Can someone shed some light on where this would be done? Would it be adjusted while getting the cursor or when applying to listview?
Any help would be greatly appreciated.
Thank You,
Josh
UPDATE:
Thank you all for the answers, but I am still struggling to find apply the solutions suggested in my instance.
I am using a simple cursor to acquire the dataset. Snippet of the code it below:
audioCursor = getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, cols,
null, null,AudioColumns.ARTIST + " COLLATE LOCALIZED ASC");
startManagingCursor(audioCursor);
setListAdapter(new MyABCAdapter(this, R.layout.list_item,
audioCursor, new String[]{AudioColumns.ARTIST,MediaStore.Audio.Artists.NUMBER_OF_TRACKS},
new int[]{android.R.id.text1, android.R.id.text2}));
I also have a utility that successfully adjusts the entry text, changing "The Artist" to "Artist, The", but it is not applied until bindView and the list has already been sorted:
private String fixFileName(String fileName) {
...
if (fileName.startsWith("The")){
fileName = fileName.replace("The ", "");
fileName = fileName.concat(",The");
}
return fileName;
}
My questions are:
1) Is there any way to apply fixFileName to the Cursor before the list is created?
2) If that is not possible, is there a way to resort the listview after bindview?
Thanks!
Have your list items extend Comparable. In the compareTo(..) method, write the custom compare code, likely using a "the".equalsIgnoreCase(fileName.subString(0, 3)), to make "The..." a special case.
Are you using an ArrayList<String> for the titles? One way I can think of is to implement your own Comparable interface. That would include, inside the method compareTo(...), remove any word like "The, "A", etc. and return the comparison of the rest of the String.
When you add items into the list do a Collections.sort() with a custom Comparator.
class CustomComp implements Comparator
{
public int compare(Object obj1, Object obj2)
{
...
if(obj1.toString().toLowerCase().startsWith("the"))
sort by second word instead
...
}
}
I have a problem about onItemSelected method of Spinner. There is no problem if I only have one Spinner. I can set a listener on that. I have a DB stored in sqlite. There is a table in which a column field contains date with year-month-date format. Then I created two Spinner views. One for month, and other for year. My program wants to show the database queries based on selection from month and year.
The problem now, if I set listener only on month Spinner, it shows queries based on month. If I set listener on year Spinner, it shows queries based on year. Actually I already prepared sql queries matching both year and month queries. But it seems that the OnItemSelected listener only can accept "ONE" spinner instance at a time. I try to use monthview.getItemAtPosition(position) && yearview.getItemAtPosition(position) to match both requirements for month and year. But it failed.
I use public class xxx extends xxx implements OnItemSelected listener and add two methods.
spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id)
{
// Do some stuff based onItemSelected
}
}
Does anyone know how to achieve this goal ?
In simple words, I have two spinners, one for month, one for year, values are populated via arrayadapter. Then I use SimpleCusrsorAdapter to get sql result from sqlite DB. Then I put cursor result into listadapter and associated with listview. It works without problem if I operate it individually either by month or year but not both. But it seems that listener only listen on one spinner instance not two or more at the same time. May be it is common problem. May be some of you already encountered this problem before.
Or can I use anonymous inner class ? But I think that it is different approach with same result. If not may be I need to use another technique if only one listener is available ?
I want to show, for example:
-I select April and All years, it displays all entries in April (April in all years)
-I select 2010 and All Months, it displays all entries in 2010 (Jan to Dec 2010)
-I select April and 2010, it only displays all entries in April 2010
Thanks for explaination and suggestions !!
Tom
Best Regards,
Finally I solved this problem by using getSelectedItemPosition() to get the value and do some decision checking. Then program runs without problem.
But I also want to know whether I can use more than two setOnItemSelectedListener for Spinner or other UI component ?
Tom
I am not 100% sure I get your problem.
Look at the method name.
setOnItemSelectedListener
The key here is the set part. Each time you call this method, you override any previously stored values for that object.
But in your cases it seems that what you should do is to call the method once for each of the two spinners either with an anonymous class (as you do there) or with your activity (which will save a bit of memory since you don't have to create the two classes).
As an example:
spinner1.setOnItemSelectedListener(classToReceiveTheSelection)
spinner2.setOnItemSelectedListener(classToReceiveTheSelection)
If you absolutely must have two different classes that respond to the same OnItemSelected, that is possible but somewhat ugly.