Get String[] from SQLite for Multispinner - android

I would like to get a String Array from my database of all contacts (TABLE_CONTACTS) to display them in a MultiSelectionSpinner.
Is there a way to change this code easy for my purpose?
String[] array = { "one", "two", "three" };
spinner = (MultiSelectionSpinner) findViewById(R.id.mySpinner1);
spinner.setItems(array);
The MultiSelectionSpinner is working with the three numbers, but I fall into despair while trying to get the contacts from my database.

First of all, you must make sure that TABLE_CONTACTS has an id column named "_id".
If you have this, then its very simple:
Cursor cur= db.rawQuery("select _id, column_to_get_data_from FROM TABLE_CONTACTS", null);
String[] from = new String[]{"column_to_get_data_from"};
int[] to = new int[]{android.R.id.textview_to_put_data_into};
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cur, from, to);
If you need to bind more fields, you must create your own item.xml spinner item layout xml file to use instead of android.R.layout.simple_spinner_item and put the corresponding values on the from and to arrays.
Then you just add the adapter to the spinner:
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mAdapter);

Related

Using SimpleCursorAdapter with Spinner?

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);

How to add an item to SimpleCursorAdapter?

I have a simple database table with 2 columns "_id" and "title".
and I'm displaying the data in a spinner, and it works well.
but I need to add one more item at the top of the spinner list that is not from the database with id = 0 and title = "not specified";
Spinner list = (Spinner) findViewById(R.id.spinner);
Cursor cursor = database.getAll(); // returns cursor with objects
String[] columns = new String[] {"title"};
int[] to = new int[] {R.id.title};
list.setAdapter(new SimpleCursorAdapter(this, R.layout.object_item_simple, cursor, columns, to));
I need to know the selected item id from the database, i can do this with list.getSelectedItemId();
so I can't use ArrayAdapter instead of SimpleCursorAdapter, because i don't think that there is a method for setting the id for each item on the adapter.
is there a way to do this?
Thanks.
You could create an object out of your id and title and build a list of these objects with the cursor. Then insert your artificial entry at the top top of that list.
Then when you construct your Adapter pass in this list.
Alternatively you could put a dummy value into your database, although that would be weird and maybe not possible depending on your query and data. The ArrayAdapter is much more sensible
How to Do This With SimpleCursorAdapter
This method:
Is Efficient
Works with standard CursorLoader and SimpleCursorAdapter idioms
Great with ContentProvider data
I create the item i want to insert into the cursor as a static MatrixCursor
private static final MatrixCursor PLATFORM_HEADER_CURSOR = new MatrixCursor(
//These are the names of the columns in my other cursor
new String[]{
DataContract.ReflashPackage._ID,
DataContract.ReflashPackage.COLUMN_PLATFORM
});
static {
PLATFORM_HEADER_CURSOR.addRow(new String[]{
"0",
"Select a Platform")
});
}
Here is my implementation of onLoadFinished which merges the cursor and passes it to the adapter.
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case PLATFORM_CURSOR_LOADER_ID:
Cursor mergedCursor = addPlatformHeaderToCursor(data);
mPlatformAdapter.swapCursor(mergedCursor);
break;
}
}
#NonNull
private static Cursor addPlatformHeaderToCursor(Cursor platforms) {
Cursor[] cursorToMerge = new Cursor[2];
cursorToMerge[0] = PLATFORM_HEADER_CURSOR;
cursorToMerge[1] = platforms;
return new MergeCursor(cursorToMerge);
}
One technique that I use often is I will define an object (such as EntryObject) that has the variables I am going to need from the cursor to display. Once I have this I can iterate through the cursor and place the information into those EntryObjects and place them in an ArrayList or an array.
Then you can build a customer ArrayAdapter that will work with your new object to pull as much data as you need and display it how you want to.

Android Binding SQLite to GridView in Eclipse

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);
}

Custom IDs in ListView

I'm trying to populate a listview with products. I can do it, but I need them to have custom id's (the ones from the SQLite database). How can I do this? This is my code without the id implementation so far:
ArrayList<String> productNameList = new ArrayList<String>();
ArrayList<String> productIdList = new ArrayList<String>();
Cursor results = myDbHelper.getProducts();
ListView lv = (ListView) findViewById(R.id.productlist);
while (results.moveToNext()){
productNameList.add(results.getString(results.getColumnIndex("name")));
productIdList.add(results.getString(results.getColumnIndex("id")));
}
lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , productNameList));
You should use a SimpleCursorAdapter:
String[] columns = new String[] { "_id", "name" };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursor, columns, to);
lv.setAdapter(mAdapter));
"to" and "columns" define a mapping:
"colums" is a list of the database column names you want the SimpleCursorAdapter to read. And "to" is a list of android ids specifying on which widget the values from the cursor are set.
In the latter code this means that the value of "_id" will be displayed in the textfield with the android id "android.R.id.text1" and the value of the column "name" will go into textfield "android.R.id.text2".

ArrayAdapter/ListView is not working

I'm new programming with android, and doing my first aplication i got something wrong with the lists.
Here the code:
Cursor c = db.rawQuery("SELECT nombre FROM contactos", null);
ArrayList<String> listaArray = new ArrayList<String>();
ListView listadoContactos = (ListView)findViewById(R.id.listViewListaContactos);
if (c.moveToFirst())
{
do {
listaArray.add(c.getString(0));
} while(c.moveToNext());
}
//Creamos un adaptador y lo asignamos al ListView.
ArrayAdapter<String> adaptadorLista = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listaArray);
listadoContactos.setAdapter(adaptadorLista);
When i see the result, my list its showing only the first item in the db that i'm querying. Can you help me, please?
Thanks in advice! George.
PS: "nombre" is the column 0. That is why i'm writting "getString(0)", because i just want to show 1 column of each row.
Try to use SimpleCursorAdapter
// NOTE your query result should have id-field, named "_id"
Cursor c = db.rawQuery("SELECT nombre, nombre_id as _id FROM contactos", null);
SimpleCursorAdapter adaptorLista = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, new String[]{"nombre"}, new int[]{android.R.id.text1} );
listadoContactos.setAdapter(adaptadorLista);
Here android.R.layout.simple_list_item_1 is a layout of each row in ListView,
new String[]{"nombre"} names of fields in cursor which values are set to TextViews in ListView row. TextView ids specified in the last argument new int[]{android.R.id.text1}
Use a CursorAdapter instead of an ArrayListAdapter. You are making extra work for yourself by copying the cursor into an Array just to feed it to the ListView.
Here is a tutorial on CursorAdapters
You could use a SimpleCursorAdapter and pass it the cursor directly:
Adapter adapter = new SimpleCursorAdapter(
this,
c,
android.R.layout.simple_list_item_1,
new String[] { "nombre" },
new int[] { android.R.id.text1 },
0);
listadoContactos.setAdapter(adapter);
and then you don't have to step through and build the list yourself.

Categories

Resources