I have spinner which I populate from SQLite database. But I want to populate it from string-array:
<string-array name="category">
<item name="accommodation">Accommodation</item>
<item name="automobile">Automobile</item>
<item name="credit cards">Credit Cards</item>
<item name="donations">Donations</item>
<item name="entertainment">Entertainment</item>
<item name="food">Food</item>
</string-array>
where name I take from SQLite table.
I have method which retrieve name from database:
public Cursor getAllCategory() {
mDB = dbHelper.getReadableDatabase();
return mDB.query(CATEGORY_TABLE_NAME, null, null, null, null, null,null);
}
And in my program I use these names:
// spinner
catSpinner = (Spinner) view.findViewById(R.id.category_spinner);
cursor = adapter.getAllCategory();
String[] from = new String[] { DataAdapter.CATEGORY_COL_NAME };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter catAdapter = new SimpleCursorAdapter(
getActivity(),
android.R.layout.simple_spinner_dropdown_item, cursor,
from, to, 0);
catAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
catSpinner.setAdapter(catAdapter);
But I want use names from database, but value that responding to these names(string.xml) use from string-array
How I can do this? I want to do this to avoid changing database when I change localization.
Try this.For getting data into the spinner you have to use SimpleCursorAdapter which is given below.
// This is your method of database class which returns cursor
Public Cursor getAllNames(){
return mDb.query(table_name, new String[]{KEY_ROWID, KEY_TITLE}, null, null, null, null, null );
}
And use this method in spinner to get items(i.e. Name).
Cursor c = mDbHelper.getAllNames();
startManagingCursor(c);
String[] from = new String[]{your_name};
// create an array of the name which you want to bind our data to
int[] to = new int[]{android.R.id.text1};
// This is your simple cursor adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
Spinner s = (Spinner) findViewById( R.id.unique_id ); // This is your spinner
s.setAdapter(adapter); // Set it to the adapter
Hope this helps. :)
Related
I am new with android..I am learning work with database files..I have a simplecurseadapter like this
Cursor c = db.query(TABLE_NAME,columns,null, null, null, null, COLUMN_ID);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, c,
new String[] {COLUMN_ID,COLUMN_NAME,COLUMN_order}, new int[] {R.id.list_item_text_id,R.id.list_item_text_main,R.id.list_item_text_sub}, 0);
ListView list = (ListView) findViewById(R.id.list_poet_name);
list.setAdapter(adapter);
I want to know Is there any way to make a custom listview?my column_order has just to value 0,1 and I want rows with 0 value shows in R.id.list_item_text_main and if its value is 1 it shows in R.id.list_item_text_sub Can I define an if statement in SimpleCursorAdapter?I yes How?If no..Whats the best way to do it?
Make your query like this
Cursor c = db.query(TABLE_NAME,columns,COLUMN_order + "=? OR " + COLUMN_order + "=?", new String[]{"0", "1"}, null, null, COLUMN_ID);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, c,
new String[] {COLUMN_ID,COLUMN_NAME,COLUMN_order}, new int[] {R.id.list_item_text_id,R.id.list_item_text_main,R.id.list_item_text_sub}, 0);
ListView list = (ListView) findViewById(R.id.list_poet_name);
list.setAdapter(adapter);
I think I find my answer...
http://enjoyandroid.wordpress.com/2012/03/12/customizing-simple-cursor-adapter/
I am working on it..Maybe I am wrong
I've populated my spinner as this:
DatabaseConnector dbConnector = new DatabaseConnector(this);
dbConnector.open();
Cursor c = dbConnector.raw("SELECT _id, nombrecasa FROM casa");
startManagingCursor(c);
String[] from = new String[]{"nombrecasa"};
int[] to = new int[]{android.R.id.text1};
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
casaSpinner = (Spinner) findViewById( R.id.casaspinner);
casaSpinner.setAdapter(adapter);
dbConnector.close();
}
And when I try to get the value as:
String idcasa = casaSpinner.getSelectedItem().toString();
it only returns this:
android.database.sqlite.SQLiteCursor#40539880
Your spinner has taken a SimpleCursorAdapter as an adapter, of which its dataset is a Cursor. When you select an item on the spinner, you've only moved the cursor to a specific row and when you call getSelectedItem() you're still requesting for the dataset object - which is still a cursor object. to do what you're trying you can simply call:
c.getString(1);
once your selection has been made. For something a little more fundamentary illustrative of what i said.
((Cursor) casaSpinner.getSelectedItem()).getString(1);
I have a db with table "mytable" having 2 colums "id","sampletext"
I want to query distinct values of sampletext and feed to a Spinner using SimpleCursorAdapter.
here is what is tried
String[] cols=new String[]{"sampletext"};
int[] lbls=new lbls[]{android.R.id.text1};
mycursor=sdb.query(true,"mytable", cols,null,null,null,null,null,null);
sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, cols,lbls,0);
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(sca);
When i run this i get error at line 4 : id does not exist.
when i changed first line to "id" the spinner got populated with id values.
But i need "sampletext", what am i doing wrong?
Appreciate any suggestions
what am i doing wrong
you didnt read documentation ...
there are two arrays of string with columns: first in used in query, second one in Adapter constructor(you used only one array for both)
first one tells sqlite which columns should be taken to Cursor, second tells Adapter which ones should be showed/mapped to Views in single row...
Next CursorAdapter needs Cursor with column named _id
So now it's pretty obvious that we should do smthin like this:
String[] queryCols=new String[]{"_id", "sampletext"};
String[] adapterCols=new String[]{"sampletext"};
int[] adapterRowViews=new int[]{android.R.id.text1};
mycursor=sdb.query(true,"mytable", queryCols,null,null,null,null,null,null);
sca=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, mycursor, adapterCols, adapterRowViews,0);
sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spn.setAdapter(sca);
Here's an example with raw query. Please note the first ID column returned by the query should be labeled as _id .
MyDatabase.java:
public class MyDatabase extends SQLiteAssetHelper {
...
public Cursor getListNamesForDropDown() {
SQLiteDatabase db = getReadableDatabase();
String sql = "select ID _id, Name from MyTable order by Name ";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
MyActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
....
Cursor cursorTest = db.getListNamesForDropDown();
android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
cursorTest,
new String[] {"Name"},
new int[] {android.R.id.text1}, 0);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerTest.setAdapter(adapter);
android.widget.SimpleCursorAdapter adapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
cursor,
new String[] { DBOpenHelper.ACCOUNT_BANK },
new int[] { android.R.id.text1 }, 0);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
I have made the following code to retrive data from SQLite database.
public Cursor fetchAllScores() {
return database.query(DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_PLAYDATE, KEY_NUMVALA, KEY_NUMVALB }, null, null, null,
null, null);
}
Then I call this function in my main.java file using the following
cursor = dbHelper.fetchAllScores();
startManagingCursor(cursor);
After having cursor I manage to populate myGridView with some data using following code
GridView myGV = (GridView)findViewById(R.id.gridView1);
String[] cols = new String[] { scoreDbAdapter.KEY_PLAYDATE, scoreDbAdapter.KEY_NUMVALA, scoreDbAdapter.KEY_NUMVALB};
int[] views = new int[] { android.R.id.text1, android.R.id.text2, android.R.id.text2 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor, cols, views);
Log.w("NumRows",adapter.getCount() + "");
myGV.setAdapter(adapter);
Now the problem is only first row is populated and first two columns, I want data like in forst row (2011-10-27 , 5 , 6 ) and second row like (2011-10-26 , 3 , 2 ) but i m getting is only forst row like (2011-10-27, 2011-10-26 ).
Can this be fixed in GridView?
For your question, take a look here, Binding to Data with AdapterView.
Note: Below decription is just example for how to bind cursor to an adapter.
Filling the Layout with Data
Inserting data into the layout is typically done by binding the AdapterView class to an Adapter, which retrieves data from an external source (perhaps a list that the code supplies or query results from the device's database).
The following code sample does the following:
1.Creates a Spinner with an existing View and binds it to a new ArrayAdapter that reads an array of colors from the local resources.
2.Creates another Spinner object from a View and binds it to a new SimpleCursorAdapter that will read people's names from the device contacts (see Contacts.People).
// Get a Spinner and bind it to an ArrayAdapter that
// references a String array.
Spinner s1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.colors,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adapter);
// Load a Spinner and bind it to a data query.
private static String[] PROJECTION = new String[] { People._ID, People.NAME};
Spinner s2 = (Spinner) findViewById(R.id.spinner2);
Cursor cur = managedQuery(People.CONTENT_URI, PROJECTION, null, null);
SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item,cur,new String[] {People.NAME}, new int[] {android.R.id.text1});
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s2.setAdapter(adapter2);
Note that it is necessary to have the People._ID column in projection used with CursorAdapter or else you will get an exception.
If, during the course of your application's life, you change the underlying data that is read by your Adapter, you should call notifyDataSetChanged(). This will notify the attached View that the data has been changed and it should refresh itself.
For more info look at this,
Custom CursorAdapters.
Thanks.
Make a new layout which contains textViews. Find the layout as shown in first line of the code below and attach your data to the listView. ListView loads the layout containing textView.
private void populateGrid()
{
ListView lv = (ListView)findViewById(R.id.listView1);
Cursor c = dbHelper.fetchAllScores();
startManagingCursor(cursor);
String[] cols = new String[] { TodoDbAdapter.KEY_PLAYDATE, TodoDbAdapter.KEY_NUMVALA, TodoDbAdapter.KEY_NUMVALB};
int[] views = new int[] { R.id.txt_date, R.id.txt_no, R.id.txt_yes};
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.listviewtemp, c, cols, views);
Log.w("NumRows",adapter.getCount() + "");
lv.setAdapter(adapter);
}
R.layout.listviewtemp is the listView template layout (separate xml), lv is the listview found in the mainlayout.xml.
public Cursor fetchAllScores() {
return database.query(DATABASE_TABLE, new String[] { KEY_ROWID,
KEY_PLAYDATE, KEY_NUMVALA, KEY_NUMVALB }, null, null, null,
null, null);
}
I wanna create an array of cities that are stored in the database
Cities Table
CREATE TABLE cities (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT);
Querying for City List
// City List
public Cursor cityList() throws SQLException {
return db.query(TABLE_CITIES, new String[] {ID, KEY_NAME}, null, null, null, null, null, null);
}
Trying to Get the content into the Array
Cursor cities = db.cityList();
startManagingCursor(cities);
String[] city_list = new String[] { DBAdapter.KEY_NAME };
Spinner cityList = (Spinner)this.findViewById(R.id.citySpiner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, city_list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cityList.setAdapter(adapter);
Am not able to populate the Spinner.. with the database content.
Try SimpleCursorAdapter
String[] from = new String[] { DBAdapter.KEY_NAME };
int[] to = new int[] {android.R.id.text1};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(context, android.R.layout.simple_spinner_dropdown_item , cursor, from, to);
cityList.setAdapter(cursorAdapter);
Edit:
from means the column(s) from the Cursor which will be used to display as text array in Spinner.
to means the id(s) of the view which will hold the value of that column.
It is very interesting that the view at index N will hold the text from column at N.