I want to iterate through a cursor data from a database, i won't be returning all of the data from the cursor. I would only need 5 randomized row of data I have the logic to return all data below but I only want five rows to be returned.
private ArrayList<Insect> insectList(){
ArrayList<Insect> insects = new ArrayList<>();
Collections.shuffle(insects);
if (cursor.moveToFirst()) {
do {
Insect insect = new Insect();
insect.setName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME)));
insect.setScientificName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
insect.setClassification(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
insect.setImageAsset(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_IMAGEASSET)));
insect.setDangerLevel(Integer.parseInt(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_DANGERLEVEL))));
insects.add(insect);
} while (cursor.moveToNext());
}
return insects;
}
Which perfect loop can i use to achieve only five rows from this cursor while iterating
if (cursor.getCount() > 0) {
int count = 0;
while (cursor.moveToNext()){
if(count < 5){
count++;
Insect insect = new Insect();
insect.setName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME)));
insect.setScientificName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
insect.setClassification(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
insect.setImageAsset(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_IMAGEASSET)));
insect.setDangerLevel(Integer.parseInt(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_DANGERLEVEL))));
insects.add(insect);
}
}
cursor.close();
}
I have a Listadapter wherein there are 4 different strings, and storing them to my listview. Now I want to get all the items from one of those strings and parse it to "date", so how can I able to populate my calendar dates from my listadapter?
Following the codes:
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> eventsList = controller.getAllevents();
// If users exists in SQLite DB
if (eventsList.size() != 0) {
// Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, eventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
String eventstart = adapter.toString(); //I got null exception here..
Date edate = ParseDate(eventstart);
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.Green, edate);
caldroidFragment.refreshView();
}
}
If you want to fetch an item from your adapter you can use
adapter.getItem(position);
which will return the item at the specified position. In your case, that method will return the HashMap<String, String> at the specified position:
Example:
/* adapter.getCount() returns the count of how many items
(HashMaps, in your case) that is represented in this adapter. */
for(int i = 0; i < adapter.getCount(); i++){
HashMap<String, String> myHashMap = adapter.getItem(i);
//"myKey" is the key that you provided, when mapping your key-values
String myVal = myHashMap.get("myKey");
Date edate = ParseDate(myVal);
/* Handle your Date object here. I'm just printing it to the console
in this example. */
System.out.println("Item at position " + i + " " + edate.toString());
}
Problem solved! Just simply put inside the loop and change the 'position' variable into the variable that handles the loop e.g for (int i = 0; i < eventsList.size(); i++) change adapter.getItem(position) to adapter.getItem(i)
As i am newbie in android i want to show my saved spinner value at the time of view of saved form
how can i show database saved value at the time of view for spinner
here is my code
Java activity file
Spinner spnAECust;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ae_view_edit_sales);
spnAECust = (Spinner) findViewById(R.id.spnAECust);
/* Get Customer List and Add Select Default */
cust = con.getAllCustomers();// from database getting list
List<Customer> custList = new ArrayList<Customer>();
Customer c = new Customer();
c.setId(Constants.Common.ZERO);
c.setNm("Select Customer");
custList.add(c);
custList.addAll(cust);
// Create and fill an ArrayAdapter with a bunch of "Customer" objects
ArrayAdapter<Customer> custArrayAdapter = new ArrayAdapter<Customer>(this, android.R.layout.simple_spinner_item,
custList.toArray(new Customer[custList.size()]));
// Tell the spinner about our adapter
spnAECust.setAdapter(custArrayAdapter);
sa = con.getAirSalesActivityDetails(Integer.parseInt(saId));// get details from Sqlite
Customer cust = new Customer();
cust.setId(sa.getCustomerId());
spnAECust.setSelection(custArrayAdapter.getPosition(cust));// to set value saved in db
}
at tried setSelection but it maches index value rather than id value so i get abstract value to b selected please show me correct way to implement ...Thnks in advance
Here i got answer by my own
/* Get Customer List and Add Select Default */
cust = con.getAllCustomers();
List<Customer> custList = new ArrayList<Customer>();
Customer cst = new Customer();
cst.setId(Constants.Common.ZERO);
cst.setNm(Constants.Common.CUSTOMER_HINT);
custList.add(cst);
custList.addAll(cust);
/* Get Commodity List and Add Select Default */
comm = con.getAllCommodities();
List<Commodity> commList = new ArrayList<Commodity>();
Commodity cm = new Commodity();
cm.setId(Constants.Common.ZERO);
cm.setNm(Constants.Common.COMMODITY_HINT);
commList.add(cm);
commList.addAll(comm);
// Create and fill an ArrayAdapter with a bunch of "Customer" objects
ArrayAdapter<Customer> custArrayAdapter = new ArrayAdapter<Customer>(this, android.R.layout.simple_spinner_item,
custList.toArray(new Customer[custList.size()]));
int custIndex = 0;
// to set selected item
for (int r = 0; r < custArrayAdapter.getCount(); r++) {
if (sa.getCustomerId() == custArrayAdapter.getItem(r).getId()) {
custIndex = r;
break;
}
}
// Tell the spinner about our adapter
spnAECust.setAdapter(custArrayAdapter);
spnAECust.setSelection(custIndex);
// Create and fill an ArrayAdapter with a bunch of "Commodities" objects
ArrayAdapter<Commodity> commArrayAdapter = new ArrayAdapter<Commodity>(this, android.R.layout.simple_spinner_item,
commList.toArray(new Commodity[commList.size()]));
int commIndex = 0;
// to set selected item
for (int r = 0; r < commArrayAdapter.getCount(); r++) {
if (sa.getCommodityId() == commArrayAdapter.getItem(r).getId()) {
commIndex = r;
break;
}
}
// Tell the spinner about our adapter
spnAEComodity.setAdapter(commArrayAdapter);
spnAEComodity.setSelection(commIndex);
used for loop to get index for saved value
int commIndex = 0;
// to set selected item
for (int r = 0; r < commArrayAdapter.getCount(); r++) {
if (sa.getCommodityId() == commArrayAdapter.getItem(r).getId()) {
commIndex = r;
break;
}
}
and add index to
spnAEComodity.setSelection(commIndex);
I am using an array adapter and to this am adding an array list of string s , the list is multi select , How can i get the values of list items clicked ?
my_contacts_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,conts_list);
my_contacts_list.setAdapter(adapter);
I was trying to do this ,
SparseBooleanArray positions = my_contacts_list.getCheckedItemPositions();
int size=positions.size();
int i=0;
while(i <= size){
conts_list.get(positions.get(i));
i++;
}
But position.get(i) is an array list , how to retrieve the selected items then ?
SparseBooleanArray.get returns a boolean, but I believe you need to check it for each position in your list, e.g.
int len = listView.getCount();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = cont_list.get(i);
/* do whatever you want with the checked item */
}
This API is a mess. Here is what works for me.
SparseBooleanArray checked = tags.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i)) {
Tag tag = (Tag) tags.getItemAtPosition(checked.keyAt(i));
Log.i("xxxx", i + " " + tag);
}
}
I believe the fastest way to get the info out of this SparseArray is to iterate over the keys (actually I'm fairly sure that the solutions above won't work in all cases). The ListView will enter a pair (index, true) into the SparseBooleanArray for every selected index.
So the code might look like this:
SparseBooleanArray checked = lv.getCheckedItemPositions();
int size = checked.size(); // number of name-value pairs in the array
for (int i = 0; i < size; i++) {
int key = checked.keyAt(i);
boolean value = checked.get(key);
if (value)
doSomethingWithSelectedIndex(key);
}
I think the Answer from Daren Robbins is Wrong, here is my answer:
ArrayList<String> ids = extras.getStringArrayList("commonids");
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if(checked.get(i))
Log.i("CheckedItem", ids.get(checked.indexOfKey(i)));
}
Assume ids is an arraylist with the same size of the listview containing the ids of the items in the list view
The thing is you must iterate all the list view items but not checkedPositions.
Define the variables:
listView (The instance of you ListView)
names (the ArrayList you are )
saveCheckedName (save all checked name to this Arraylist)
SparseBooleanArray checkedPositions = listView.getCheckedItemPositions();
for (int i = 0; i < subjectListView.getCount(); i++) {
if (checkedPositions.get(i) == true) {
saveCheckedName.add(names.get(i));
}
}
Like so many other things, multi-select ListViews are a real problem in Android.
Instead of simply requesting the selected items as a List of Objects (dear Google, this is what we expect):
List selected_items = my_list_view.getSelectedItems();
we are forced to use this stupendously ridiculous API:
SparseBooleanArray checked = my_list_view.getCheckedItemPositions();
int num_selected = 0;
for(int i = 0; i < checked.size(); i++) {
if(checked.valueAt(i)) {
num_selected++;
int key = checked.keyAt(i);
boolean value = checked.get(key);
if (value) {
//
}
}
}
The horribly named SparseBooleanArray is populated by calling the even more horribly named getCheckedItemPositions() on the ListView. But instead of returning the positions of each selected/checked item in the list, it returns the position of every item in the list that WAS EVER touched, whether it is currently actually selected or not! Unbelievable, but true.
To calculate whether the item is ACTUALLY CURRENTLY checked, we are forced to test valueAt(i) for truthiness while looping through the 'was ever touched' array of items.
In addition to this madness, if we want to calculate the number of selected items, we appear to be forced to increment our own counter (e.g. num_selected).
With APIs like this one, it's little wonder developers are an angry lot!
I think another option is to just keep track of all of this yourself.
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View selectedItem,
int position, long itemId) {
//Keep a reference here, and toggle a global variable.
HOW I SOLVED THE ISSUE with a second ArrayList :
Created a second ArrayList instance
Updated that ArrayList instance with the UNCHECKED items
added it to the my listadapter
public void removeSelectedItems(){
updatedList = new ArrayList<String>(); //initialize the second ArrayList
int count = lv.getCount(); //number of my ListView items
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
for (int i=0;i < count;i++){
if(!checkedItemPositions.get(i))
updatedList.add(liveNames.get(i)); //liveNames is the current ArrayList
Log.e("TEST", liveNames.get(i));
}
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, updatedList);
setListAdapter(adapter);}
Hope it will be helpfull :)
Foo objectAtCheckedRow = null;
for (int i = 0; i < positions.size(); i++) { //positions.size() == 2
objectAtCheckedRow = adapter.getItem(positions.keyAt(i));
//Do something significant with object here
}
A couple things to understand
It's a key-value pair list.
The key is the index of a row, get it with positions.keyAt(i)
The value is whether the row at that index is checked or not(true or false), get it with positions.valueAt(i)
positions.get(i) returns the same boolean as .valueAt(i)
Careful not to get indexes mixed up. You do not need to(and should not) iterate over your whole list. Use int i to iterate over positions, but don't use i to get objects from your list
But in this specific case(listView.getCheckedPositions()) it only fills in true(checked rows), so you don't actually need to verify using .get(i) nor .valueAt(i)
Example:
Let's say you've checked the 5th and 8th items in the list(index 4 and 7), then positions.size() == 2 and i will be 0 and then 1
So when:
i == 0 then keyAt(i) == 4
i == 1 then keyAt(i) == 7
i == 0 OR i == 1 then valueAt(i) == true AND get(i) == true
FYI, Here is how Google did it:
Excerpted from http://mytracks.googlecode.com/hg/MyTracks/src/com/google/android/apps/mytracks/util/Api11Adapter.java
/**
* Gets the checked positions in a list view.
*
* #param list the list view
*/
private int[] getCheckedPositions(ListView list) {
SparseBooleanArray positions = list.getCheckedItemPositions();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
for (int i = 0; i < positions.size(); i++) {
int key = positions.keyAt(i);
if (positions.valueAt(i)) {
arrayList.add(key);
}
}
int[] result = new int[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
result[i] = arrayList.get(i);
}
return result;
}
and here is my adapted version:
public static List<Integer> getAbsListViewCheckedItemPositions(AbsListView absListView) {
SparseBooleanArray checked = absListView.getCheckedItemPositions();
List<Integer> positions = new ArrayList<>();
int checkedSize = checked.size();
for (int i = 0; i < checkedSize; i++) {
if (checked.valueAt(i)) {
positions.add(checked.keyAt(i));
}
}
return positions;
}
We use this in our Android utility class. The generics help prevent compiler warnings, but you can remove them if your adapter returns multiple types.
public static <T> Collection<T> getCheckedItems(ListView listView) {
Collection<T> ret = new ArrayList();
SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
for (int i = 0; i < checkedItemPositions.size(); i++) {
if (checkedItemPositions.valueAt(i)) {
T item = (T) listView.getAdapter().getItem(checkedItemPositions.keyAt(i));
ret.add(item);
}
}
return ret;
}
Very simple, use below code
listViewRequests.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
AppCompatCheckedTextView checkBox = (AppCompatCheckedTextView) view;
if (checkBox.isChecked() == true){
Log.i("CHECK",checkBox.isChecked()+""+checkBox.getText().toString());
}
}
});
for(int i =0; i< listView.getAdapter().getCount(); i++){
if(listView.isItemChecked(i)){
listView.getAdapter().getItem(i); // item
}
}
should be used after setAdapter() method
I have created a simple Spinner binding it to a SimpleCursorAdapter. I'm populating the SimpleCursorAdapter with a list of towns from a content provider.
When I go to save the users selection I'm planning on saving the row id that is being populated into my SimpleCursorAdapter.
I'm using the following code to get the ID.
townSpinner.getSelectedItemId();
What I can not figure out is how best to set the selection when I pull back up the saved item.
The following code works but it only sets selection by position number.
townSpinner.setSelection(2);
Should I just create a loop to determine the correct position value based on Id?
long cityId = Long.parseLong(cursor.getString(CityQuery.CITY_ID));
for (int i = 0; i < citySpinner.getCount(); i++) {
long itemIdAtPosition2 = citySpinner.getItemIdAtPosition(i);
if (itemIdAtPosition2 == cityId) {
citySpinner.setSelection(i);
break;
}
}
I think you've answered your own question there!
Just write your own setSelectionByItemId method using the code you posted
Example:
DB:
public Cursor getData() {
SQLiteDatabase db = getReadableDatabase();
String sql = "select ID _id, Name from MyTable order by Name ";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
Activity:
Cursor myCursor = db.getData();
SimpleCursorAdapter adapter1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
myCursor,
new String[] { "Name" }, new int[] { android.R.id.text1 }, 0);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter1);
for(int i = 0; i < adapter1.getCount(); i++)
{
if (adapter1.getItemId(i) == myID )
{
mySpinner.setSelection(i, false); //(false is optional)
break;
}
}
Android Spinner set Selected Item by Value
The spinner provides a way to set the selected valued based on the position using the setSelection(int position) method. Now to get the position based on a value you have to loop thru the spinner and get the position. Here is an example
mySpinner.setSelection(getIndex(mySpinner, myValue));
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).equals(myString)){
index = i;
}
}
return index;
}
If you are using an ArrayList for your Spinner Adapter then you can use that to loop thru and get the index. Another way is is to loop thru the adapter entries
Spinner s = (Spinner) findViewById(R.id.spinner_id);
for(i=0; i < adapter.getCount(); i++) {
if(myString.trim().equals(adapter.getItem(i).toString())){
s.setSelection(i);
break;
}
}