Android: Get Position from SimpleCursorAdapter - android

I would like to set the position of a spinner item, but the spinner is being populated with a simplecursoradapter with data from a database. I would like to get the current string from the database, then set the spinner to that value. I know that by using an arrayadapter I can get the position from the adapter this way:
String myString = queryData.getString(queryData.getColumnIndex("myString"));
//cast to an ArrayAdapter
mySpinnerAdapter adapter = (mySpinnerAdapter) mySpinner.getAdapter();
int spinnerPosition = ?
//set the default according to value
mySpinner.setSelection(spinnerPosition);
But is there a way to get the position of an item from a SimpleCursorAdapter? In the past I have always build an array of my spinner data along side the cursoradapter, but this seems like a dirty way of doing it. If its the only way though...

You can get the position of the item by doing this:
ArrayList<View> views = new ArrayList<View>();
listView1.reclaimViews(views);
for (int i = 0; i < views.size(); i++)
{
View v = views.get(i);
// Get the view's text value and compare it with your string here
// If the two strings match, store the position, which is 'i' in this case
// If your view is a textview, you would do this:
TextView tv = (TextView)v.findViewById(R.id.textView1);
if (tv.getText().toString().toLowerCase().compareTo(textToCompare.toLowerCase()) == 0)
{
// Store position here
}
}

Even i face the same problem. After breaking my head for some hours, i found this solution.
I hope it will help you.
/// value is column name in DB. take value from
final String[] from = new String[] {"value"};
/// field in spinner. Put value into (keep "R.id.text1" as it is..)
final int[] to = new int[]{R.id.text1};
// Get Database Access Object to interact with DB
DataAccessObject dataAccessObject = new DataAccessObject(context);
final Cursor valueCursor = dataAccessObject.querySpinnerValues();
final SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(
context, R.layout.spinner_row_layout, valueCursor,
from , to );
// when ever a field is selected in the spinner's "spinner.setOnItemSelectedListener" method will be called
// and the primary key
// associted with that particular value will be saved into "someFieldPkMap" map or you can choose other collection..or some
// instance variable..
//
// Note : Here i am fetching two columns fron DB.
// 1. "_id" Primary key should always be "_id" otherwise it will not work
// 2. "value" which will be displayed in the spinner. this column can be anything. but you need to map it. The way i did eg..
// final String[] from = new String[] {"value"}; /// value is column name in DB. take value from
// final int[] to = new int[]{R.id.text1}; /// field in spinner. Put value into (keep "R.id.text1" as it is..)
//
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
valueCursor.moveToPosition(position);
// Get the primary Key associated with the value...
// Use "someFieldPkMap" map to get the primary key
someFieldPkMap.put(fieldName, Integer.parseInt(valueCursor.getString(0)));
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
spinner.setAdapter(simpleCursorAdapter);

Related

get row from a cursor based on the id that is a column

currently in my cursor that I recieve on method setupChangeReasons(Cursor cursor), I have a list of records that I get from the database, I have a variable "mChangeReasonId", if this variable is 0 nothing happens, but if it has another value what I need is to get all the data of the row of this record, all the records that I receive have an id, description, number, employee, etc. I need to get all that row if the id is equal to "mChangeReasonId".
How can I get that specific row from the cursor, when my variable "mChangeReasonId" has a value other than 0? I need store this data in different variables.
private void setupChangeReasons(Cursor cursor) {
final DetailsSpinnerView spChangeReason = (DetailsSpinnerView) getView().findViewById(R.id.changeReason);
SimpleCursorAdapter changeReasonAdapter = new SimpleCursorAdapter(getActivity(), R.layout.spinner_item_empty, cursor, new String[]{eHubDatabaseManager.AbsenceReason.COL_DESCRIPTION}, new int[]{android.R.id.text1}, 0);
NothingSelectedSpinnerAdapter nothingSelectedSpinnerAdapter = new NothingSelectedSpinnerAdapter(changeReasonAdapter, R.layout.spinner_item_empty, getActivity());
changeReasonAdapter.setDropDownViewResource(R.layout.spinner_item);
spChangeReason.setAdapter(nothingSelectedSpinnerAdapter);
AcbItemWrapper acbItemWrapper = new AcbItemWrapper(cursor);
//variable mChangeReasonId
final int spinnerPosition = mChangeReasonId == 0 ? 0 : acbItemWrapper.getPositionOfInt(mChangeReasonId, eHubDatabaseManager.AbsenceReason.COL_ID) + 1; //+1 to account for NothingSelected
spChangeReason.setSelection(spinnerPosition);
spChangeReason.setOnItemSelectedListener(getChangeReasonListener(spinnerPosition, spChangeReason));
}

How to position (select) a spinner on specific item by id with simplecursoradapter?

I'm populating a spinner with a number of records from my SQlite database using the following code:
DBHelper db = new DBHelper(getBaseContext());
Cursor cursor_clients = db.select("clients", "_id, name", "ORDER BY name"); // table, fields, filter/order
String[] columns = new String[] { "name" };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor_clients, columns, to, 0);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
spnClients.setAdapter(mAdapter);
It works great, and I can use
spnAcademias.getSelectedItemId();
To get the _id of the selected record. My problem is: How to select an item on this spinner by the _id?
I have the _id of the row I want, I want it to show this row selected, and not the first row coming from the query.
Doing more research I ended up with the solution here: setSelection on Spinner based on rowId
I thought maybe there was a native solution without a loop, but there is not.
Solution:
public void setSpinnerItemById(Spinner spinner, int _id)
{
int spinnerCount = spinner.getCount();
for (int i = 0; i < spinnerCount; i++)
{
Cursor value = (Cursor) spinner.getItemAtPosition(i);
long id = value.getLong(value.getColumnIndex("_id"));
if (id == _id)
{
spinner.setSelection(i);
break;
}
}
}
If you're able to just as easily get the text value of the row you are looking for, then try the solution here, and more specifically the top comment on it: Set selected item of spinner programmatically
Use the following: spinnerObject.setSelection(INDEX_OF_CATEGORY2).
...
... I also found a way of getting the index without needing to loop through the adapter. I used the following mySpinner.setSelection(arrayAdapter.getPosition("Category 2"));

How to Retrive proper data on Spinner from SimpleCursorAdpter in Android

hay i used the SimpleCursorAdapter from implement the data on the spinner.its going well. also to get data i used following code:
Cursor cursor = (Cursor) (spncomapnayname.getSelectedItem());
if (cursor != null) {
companyselected = cc.getString(cc.getColumnIndex(db.COMPANY_NAME));
}
it is working well.but it is for the getting data from the spinner.but now i want to set particular data on spinner which was inserted by the user for update for normal ArrayAdapter spinner we used:
spinnername.setSelection(adapter1.getPosition(abc));
so i want to know how to set data from the database on spinner.
here is my code:
cursor = db.getProductName();
adapter1 = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { DB_Database.PRODUCT_NAME }, new int[] { android.R.id.text1 });
adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spnproduct.setAdapter(adapter1);
purchaseproduct = purchasebundle.getString("clickedpurchaseproductname");
if(!purchaseproduct.equals("null")|| !purchaseproduct.equals("")) {
System.out.println("purchaseproduct" + purchaseproduct);
String mypurchaseproduct=purchaseproduct;
ArrayAdapter myAdap = (ArrayAdapter) spnproduct.getAdapter();
int spinnerPosition = myAdap.getPosition(mypurchaseproduct); // set the default according to value
spnproduct.setSelection(spinnerPosition);
}
here i get data from bundle.i want to retrive data on Spinner.the data is populated from SimpleCursorAdapter
First Get Selected Value From Cursor and store into mString Variable and then use below code for display this selected value into Spinner.
if (!mString.equals("null") || !mString.equals("")) {
String myString = mString; // the value you want the position for
ArrayAdapter<String> myAdap = (ArrayAdapter<String>) mSpn1.getAdapter(); // cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(myString);
// set the default according to value
mSpn1.setSelection(spinnerPosition);
}
You can do something like this:
Cursor c = (Cursor)parent.getItemAtPosition(pos);
int id = c.getInt(c.getColumnIndexOrThrow("columm_name"));
or to get a String
String name=c.getString(c.getColumnIndexOrThrow("columm_name"));

Populating a spinner with specific entries from an array

I am working on an application for Android. For this I am making an Activity in which you select your country and then a spot in that country. I have one spinner that contains a list of all available countries. Now, what I want it to do is get the country that has been selected, then filter a list of spots that I have for the items that start with the country that has been selected. Then it should put the spots for the selected country into a different spinner. Just for clarity, the list of countries is just a list of countries, and the list of spots looks like:
Country1 - Spot1
Country1 - Spot2
Country2 - Spot1
Country2 - Spot2
And so on.
This is what I thought the code should work like:
Get selected country from spinner 1.
Make a new ArrayList containing the spots.
Make a second empty ArrayList.
For each entry of the ArrayList containing the spots, check if it starts with the selected country.
If so, add it to the second ArrayList.
Once this is all done, make an ArrayAdapter with the second ArrayList.
Set this ArrayAdapter for spinner 2.
I tried to achieve this with the following code:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
ArrayList<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(R.array.spots_array);
ArrayList<CharSequence> arraylist2 = new ArrayList<CharSequence>();
for (i=0; i<arraylist.size(); i++) {
String delimiter = " - ";
if ((arraylist(i).split(delimiter)).equals(selectedCountry)) {
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, arraylist2<CharSequence>, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
But it gives several errors:
At addAll() it says: "The method addAll(int, Collection) in the type ArrayList is not applicable for the arguments (int)"
At arraylist it says: "The method arraylist(int) is undefined for the type Configuration"
At string (inside substring) it says: "string cannot be resolved"
I am still relatively new to Android, and am having a lot of trouble getting this working. Can anybody please help me out?
There is a lot of little mistakes in your code :
To access an element in an arraylist use the get(position) method
When you add your "spot_array", you actually add the id of the resource, not the array itself (see here)
Here is your code updated, it should works or may need some tweaks
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selectedCountry = parent.getItemAtPosition(pos).toString();
List<CharSequence> arraylist = new ArrayList<CharSequence>();
arraylist.addAll(Arrays.asList(getResources().getTextArray(R.array.spots_array)));
List<CharSequence> arraylist2 = new ArrayList<CharSequence>();
String delimiter = " - ";
for (int i=0; i<arraylist.size(); i++) {
String country = arraylist.get(i).toString();
if (country.contains(selectedCountry)) {
arraylist2.add(country.substring(country.lastIndexOf('-') + 2));
}
}
ArrayAdapter<CharSequence> arrayAdapter2 = ArrayAdapter.createFromResource(this, android.R.id.text1, android.R.layout.simple_spinner_item);
arrayAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(arrayAdapter2);
spinner2.setOnItemSelectedListener(this);
}
You have several errors in your code.
Firstly, the method addAll of the ArrayList must take as an argument a Collection. You are passing an Android array id R.array.spots_array; bear in mind that the Android ids are integers.
The usually method to fetch a string array from Android resources is (inside an activity):
String[] myArray = getResources().getStringArray(R.array.spots_array);
Second error: you should access the ArrayList elements by calling the method get(position) , not directly (arraylist(position)). Something like arraylist.get(position).
Third error:
arraylist2.add(arraylist(i).string.substring(string.lastIndexOf('-') + 1));
should simply be arraylist2.add(arraylist.get(i)); for adding one list element to another.
More on ArrayLists can be found here.

Set text color of a textview in a listview item? (Android)

Been scouring this site for any answers, no real easy solution I've found for this. I am creating an Android application that uses an sqlite database to look up a hex value by the color name typed in. I am dynamically creating a TextView, setting its text and text color, then adding it to the ArrayList, then the ArrayList is being added to the ListView. The text shows up in the ListView, but its color property is not being set. I'd really like to find a way to get the text color set for each listview item. Here is my code thus far:
Class Variables:
private ListView lsvHexList;
private ArrayList<String> hexList;
private ArrayAdapter adp;
In onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.color2hex);
lsvHexList = (ListView) findViewById(R.id.lsvHexList);
hexList = new ArrayList<String>();
In my Button Handler:
public void btnGetHexValueHandler(View view) {
// Open a connection to the database
db.openDatabase();
// Setup a string for the color name
String colorNameText = editTextColorName.getText().toString();
// Get all records
Cursor c = db.getAllColors();
c.moveToFirst(); // move to the first position of the results
// Cursor 'c' now contains all the hex values
while(c.isAfterLast() == false) {
// Check database if color name matches any records
if(c.getString(1).contains(colorNameText)) {
// Convert hex value to string
String hexValue = c.getString(0);
String colorName = c.getString(1);
// Create a new textview for the hex value
TextView tv = new TextView(this);
tv.setId((int) System.currentTimeMillis());
tv.setText(hexValue + " - " + colorName);
tv.setTextColor(Color.parseColor(hexValue));
hexList.add((String) tv.getText());
} // end if
// Move to the next result
c.moveToNext();
} // End while
adp = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hexList);
lsvHexList.setAdapter(adp);
db.close(); // close the connection
}
You are not adding the created TextView to the list at all, you just add the String to the list, thus it doesn't matter what method you called on the TextView:
if(c.getString(1).contains(colorNameText)) {
// ...
TextView tv = new TextView(this);
tv.setId((int) System.currentTimeMillis());
tv.setText(hexValue + " - " + colorName);
tv.setTextColor(Color.parseColor(hexValue));
hexList.add((String) tv.getText()); // apend only the text to the list
// !!!!!!!!!!!!!! lost the TextView !!!!!!!!!!!!!!!!
}
What you need to do is to store the colors in another array, and when creating the actual list view, set the color of each TextView according to the appropriate value in the list.
To do that, you will need to extend ArrayAdapter and add the logic of the TextView color inside.

Categories

Resources