How to add newly added listitems from Top. sql server - java

I want add newly added listitems from the index 0. like if one items is present already then if i insert another item so i want it display at top.
ListView lst1 = (ListView) findViewById(R.id.list2);
List<Map<String, String>> MyDataList = null;
reuestitems myData = new reuestitems();
MyDataList = myData.getlist10();
String[] from = {"bloodgrp", "date", "time", "name", "Username"};
int[] to = {R.id.listt, R.id.date, R.id.time1, R.id.name3, R.id.user};
ad = new SimpleAdapter(request.this, MyDataList, R.layout.listrequest, from, to);
lst1.setAdapter(ad);
lst1.setBackgroundColor(getColor(R.color.colorPrimary));
if(ad.getCount()==0){
Toast.makeText(getApplicationContext(), "No requests are currently visible", Toast.LENGTH_SHORT).show();
}

i strongly suggest to use RecyclerView instead of ListView.
the function you are looking for is adapter.notifyItemInserted or if you want to remove an item adapter.notifyItemRemoved.

Related

Filter Records from SQLite to show in a List

I have some data in SQLite database, which I would like to show in a List based on small logic.
I have three fields in my table,
first field : id
second field : title
third field : type
where Type can be : Monthly or Yearly
Here is my code:
// Generate real data for each item
public List<ReminderItem> generateData(int count) {
ArrayList<ReminderItem> items = new ArrayList<>();
// Get all reminders from the database
List<Reminder> reminders = rb.getAllReminders();
// Initialize lists
List<String> Titles = new ArrayList<>();
List<String> Type = new ArrayList<>();
List<Integer> IDList= new ArrayList<>();
// Add details of all reminders in their respective lists
for (Reminder r : reminders) {
Titles.add(r.getTitle());
Type.add(r.getType());
IDList.add(r.getID());
}
return items;
}
This is the situation, where I need help from you guys, As you can see still, I am showing each and every record from database to list, no matter from which Type it belongs.
Now, I just want to show records in a List, which belongs to Type "Monthly" only
So exactly what I have to do ? How can I show records in a List for the Type of "Monthly" only
I have a String variable namely, strType = "Monthly";
You have two option to do this.
First is directly get only those record from database which reminder type is "Monthly" by execute below sql statement.
SELECT id,title,type FROM table_name WHERE type = "Monthly"
Second is check reminder type is equal to "Monthly" when you add data into List.
for (Reminder r : reminders) {
String reminderType = r.getType();
if(reminderType.equalsIgnoreCase(strType)) {
Titles.add(r.getTitle());
Type.add(reminderType);
IDList.add(r.getID());
}
}
Full Code
// Generate real data for each item
public List<ReminderItem> generateData(int count) {
String strType = "Monthly";
ArrayList<ReminderItem> items = new ArrayList<>();
// Get all reminders from the database
List<Reminder> reminders = rb.getAllReminders();
// Initialize lists
List<String> Titles = new ArrayList<>();
List<String> Type = new ArrayList<>();
List<Integer> IDList= new ArrayList<>();
// Add details of all reminders which type="Monthly" in their respective lists
for (Reminder r : reminders) {
String reminderType = r.getType();
if(reminderType.equalsIgnoreCase(strType)) {
Titles.add(r.getTitle());
Type.add(reminderType);
IDList.add(r.getID());
}
}
return items;
}
When you select from your sqlite db you can add filter there
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_A + " WHERE " +
COLUMN_TYPE + "=?", new String[]{ arg0 }); // arg0 = "Monthly"
This will increase your performance instead of filtering List after load

Wicket: Palette set default selected

I'm trying to implement a palette. I try to set a default selected list but it's empty.
myLists:
// here I get a Set of the categorys which are already in that group
Set<Category> selectedCategorysSet = new HashSet<Category>();
selectedCategorysSet = group.getCategorys();
// here I get all categorys exists
List<Category> listCategory = new ArrayList<Category>();
listCategory = catDao.getAll(Category.class);
List<Category> selectedCats = new ArrayList<Category>();
List<Category> tmpList = new ArrayList<Category>();
// the palette doesnt accept an Set so I added the set to a List
selectedCats.addAll(selectedCategorysSet);
// here I delete every Category from the whole List which is already selected (stored in a temporary list)
for(Category catList:listCategory){
for(Category cat:selectedCategorysSet){
if(cat.getCategoryId() == catList.getCategoryId()){
tmpList.add(catList);
}
}
}
listCategory.removeAll(tmpList);
/*
two multiple select boxes which switches items between each other
*/
IChoiceRenderer<Category> renderer = new ChoiceRenderer<Category>("title","categoryId");
final Palette<Category> palette = new Palette<Category>("palette",
new ListModel<Category>(selectedCats),
new CollectionModel<Category>(listCategory),
renderer, 10, false);
I already debugged that code, it works but my selected values are empty.
Here is a picture of my debugged variables:
but the selected field is still empty!
what am I doing wrong?
You should not delete every Category from the whole List which is already selected.
Palette component must store whole list of values in it's choicesModel which is listCategory in your code.
So, just remove following code from your implementation:
for(Category catList:listCategory){
for(Category cat:selectedCategorysSet){
if(cat.getCategoryId() == catList.getCategoryId()){
tmpList.add(catList);
}
}
}
listCategory.removeAll(tmpList);

Custom Autocomplete Adapter Android

I wish to have a auto-complete text-box which comes up with the users contact names. My code is as follows.
private void getContactNames()
{
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
_contactAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line);
while (cursor.moveToNext())
{
int nameIdx = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
String tmp = cursor.getString(nameIdx);
_contactAdapter.add(tmp);
}
}
Setting the adapter:
AutoCompleteTextView contactName = (AutoCompleteTextView) findViewById(R.id.contactName);
contactName.setAdapter(_contactAdapter);
When I do this, the adapter has all the contact names in there (238 contacts). However, when I start typing into the text box, the auto complete does not show.
Funny, as when I test it out doing this:
String[] ab = new String[] {"aaaaa", "bbbbb"};
_contactAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,ab);
it will show "aaaaa" and "bbbbb" when typing in to the text box.
Any ideas?
Thanks,
Tom
*EDIT
Just thought I would follow up. It does seem to be the sheer amount of contacts that is preventing it from appearing. Any way to get around this?
while (cursor.moveToNext())
{
int nameIdx = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
String tmp = cursor.getString(nameIdx);
//_contactAdapter.add(tmp);
// get all names in a new arraylist and then assign it to
arrayList.add(tmp);
}
and then assign it to your adapter as
_contactAdapter = new ArrayAdapter<String> this,android.R.layout.simple_dropdown_item_1line, arrayList);

Showing text in Android ListAdapter on this specific case

I am trying to build a simple TV-Guide for Android. To make that, I am using RSS from one site. I parse XML and now, I'd like to show it. The idea is a List that displays Station, Whats currently on the show and date, and when I press on some item in the list it will give me a new Activity that shows the full schedule of some TV station. I've managed to separate parts of Whole TV program in just separate Strings (like: 06:00 News; 07:15 Movie). And I even managed to separate it so it fills String[][] (like: |06|,|00|,|News| ; |07|,|15|,|Movie|). And my Idea was to check which one is closest to real time and to display it.
Well, currently my App displays TV Station, WHOLE program (schedule), and Date. And I want it to display just whats currently showed. Can anybody help me with this one?
Here is class in which I want to do it: (I also have Parser class and Main class with just buttons and URLs of XMLs)
public class Pomocna extends ListActivity {
// All static variables
static String url =null;
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "encoded";
Calendar calendar = new GregorianCalendar();
int DSQ=calendar.get(Calendar.HOUR_OF_DAY);
int DMQ=calendar.get(Calendar.MINUTE);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent in = getIntent();
// Get XML values from previous intent
url = in.getStringExtra("A");
ArrayList<HashMap<String,String>> menuItems = new ArrayList<HashMap<String,String>>();
//ArrayList<String[][]> nekaj = new ArrayList<String[][]>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); //get XML
Document doc = parser.getDomElement(xml); // get DOM elem.
//doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//loop
for (int i=0; i< nl.getLength(); i++){
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
//add to map
map.put(KEY_TITLE, Vracanje1(parser.getValue(e, KEY_TITLE)));
map.put(KEY_DATE, Vracanje2(parser.getValue(e, KEY_DATE)));
map.put(KEY_DESC, parser.getValue3(e,KEY_DESC));
//NEKO FRCERANJE -=- POCETAK
String pvp = parser.getValue3(e,KEY_DESC);
char[] rast = pvp.toCharArray();
int brojac = 0;
for(int q=0; q<pvp.length(); q++){
if(rast[q]=='*') brojac++;
}
String[][] niz= new String[brojac][3];
int bf1=0;
int bf3=0;
int oo=0;
for(int q=0; q<pvp.length(); q++){
if(rast[q]=='*'){
bf3=bf1;
bf1=q;
String lol = pvp.substring(bf3, bf1);
// SEPARATE STRING: LOL
// IT MUST HAVE 3 PARTS: HOUR, MINUTE, AND DESCRIPTION
if(oo==0){
String ps=lol.substring(0,2);
String ds=lol.substring(3,5);
String ts=lol.substring(6,lol.length());
niz[oo][0]=ps;
niz[oo][1]=ds;
niz[oo][2]=ts;
}
if(oo>0){
String ps=lol.substring(1,3);
String ds=lol.substring(4,6);
String ts=lol.substring(7,lol.length());
niz[oo][0]=ps;
niz[oo][1]=ds;
niz[oo][2]=ts;
}
oo++;
}
}
//NEKO FRCERANJE -=- KRAJ
menuItems.add(map);
//nekaj.add(niz);
}
//DISPLAY WHAT's CURRENTLY ON PROGRAM
//USE TIME TO COMPARE AND SHOW
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item,
new String[]{KEY_TITLE, KEY_DESC, KEY_DATE}, new int[]{
R.id.title, R.id.description, R.id.date
});
setListAdapter(adapter);
//singleView
ListView lv = getListView();
}
public String Vracanje1(String bq){
int p1=bq.length();
int p2=p1-10;
StringBuilder sbp= new StringBuilder(bq);
sbp.delete(p2, p1);
String ses=sbp.toString();
return ses;
}
public String Vracanje2(String bq){
int p1=bq.length();
int p2=p1-14;
StringBuilder sbp=new StringBuilder(bq);
sbp.delete(p2, p1);
String ses = sbp.toString();
return ses;
}
}
Per my understanding the way You're doing won't be acceptable to any TV-program application, because usually program has many channels with many programs and parsing and analysing the data in UI thread will (sooner or later) cause ANRs. I would suggest You to consider use of separate service and content provider to let UI thread do only UI-related stuff and leave data processing to corresponding components. It would be faster and easier to find/process data via sqlite in provider.
Regarding a question about finding closest data - You could sort arrays and when find closest one (e.g. just iterating from the beginning).
I agree with #sandstar, but I'm not sure if what you're asking is how to filter the data or how to show the data? In this case it is the matter of updating the ListAdapter. This means, when you want to show only the most recent program, you need to provide the adapter a list of maps containing only the map with the data for the latest show. This means you should filter the data before applying the adapter to the ListView. If you want to have more control over the adapter you might consider extending the ArrayAdapter which also allows you to add/clear the data of the existing adapter.

Displaying multiple Items in simple_list_item_1

I followed this guide http://www.vogella.de/articles/AndroidSQLite/article.html and altered the table and code to handle additional fields. But when the list is displayed it only displays the Item field and not the price. I can't find where in the code it does this.
Here is the code for the loading of items into the adapter, the getAllItems returns and array of items. Item has id, item and price.
List<Item> values = datasource.getAllItems();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
Here is the code behind that :
public List<Item> getAllItems() {
List<Item> items = new ArrayList<Item>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
null, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Item item = cursorToItem(cursor);
items.add(item);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return items;
}
private Item cursorToItem(Cursor cursor) {
Item item = new Item();
item.setId(cursor.getLong(0));
item.setItem(cursor.getString(1));
item.setPrice(cursor.getString(2));
return item;
}
It appears 'values' is only Item.items and not price and ID but I don't see why?
Without the whole private Item cursorToItem stuff, how about adding
while (!cursor.isAfterLast()) {
items.add(cursor.getLong(0) + " " + cursor.getString(1) + " " + cursor.getString(1));
cursor.moveToNext();
}
If you want to have more objects in a row, your task is much bigger. I suggest you check this link and implement Pankaj's code. I have been using it for a while and it works like a charm. However, it took me a while to understand.

Categories

Resources