How to add distinct items into spinner from DB in android - android

i need to upload unique data from DB into spinner list in android.Ex.In my DB i have 4 records as "Jan","Feb","Mar","Jan".i need to upload those data in to spinner by distinct.i.e.only jan,feb,mar.
How could i do this?
My code...
//...
Spinner spin = (Spinner) findViewById(R.id.spin);
AdapterCountries = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item);
AdapterCountries.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(AdapterCountries);
spin.setOnItemSelectedListener(new OnItemSelectedListener());
db1.open();
// long id;
Cursor cursor = db1.getAllTitles1();
while (cursor.moveToNext()){
results=cursor.getString(2);
AdapterCountries.add(results);
}
db1.close();
In My DBAdapter class..
public Cursor getAllTitles1(){
return db.query(DATABASE_TABLE1, new String[] {
KEY_ROWID,DISHNAME,CATEGORY,DESCRIPTION},null,null,null,null,null);
}

You should use the DISTINCT clause in the the sql query, and it will return unique data already.
Use raw queries in execute method, instead of using the current approach.

Check this method for getting distinct values.

Related

Retrieving Particular column from db into Spinner

My SqliteDB
In the above link am having my db screenshot
How to load that fiGoods column values into Spinner. Since am new to android kindly help me with full code
Write Query to get fiGoods
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select fiGoods from fiGoodsDetail", null);
String[] figoodslist;
res.moveToFirst();
int i=0;
while(!res.isAfterLast())
{
figoodslist[i] = res.getString(res.getColumnIndex("fiGoods"));
i++;
}
Get fiGoods value in String array.Then you have to bind array to spinner like this...
ArrayAdapter<String> adaper = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, YOUR_STRING_ARRAY);
spinner.setAdapter(adaper);
To link sqlite values to an adapter, use the handy CursorAdapter class.

How to implement a MatrixCursor for a Spinner?

I have a SQLite query that returns a Cursor. I want to add some extra rows to the Cursor by implementing a MatrixCursor(to try to keep the first item of real data from automatically selected when clicked). Then I want to map them to a SimpleCursorAdapter. I kept reading the posts(and codes) but still remain fuzzy to me how to code it to my existing code listed below.
Cursor cursor = myDB.query(DATABASE_TABLE_NAME, resultColumns, whereClause,
whereArgs, null, null, null, null);
// Create Spinner View object from layout resource
Spinner spinner = (Spinner) findViewById(R.id.spinner);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, // Use a template
// that displays a
// text view
cursor, // Give the cursor to the adapter
new String[] {"ename"}, // Map the NAME column in the
// people database to...
new int[] {android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
If you want to build a MatrixCursor from a simple Cursor you'll have to parse the entire initial Cursor and append the rows you want:
//...
MatrixCursor mc = new MatrixCursor(resultColumns);
// add extra rows, this will probably not work if you want to insert them
// between the initial cursor rows because of the _id column that need autoincrement values
mc.addRow(new Object[] { new Long(-2), "Extra name1" });
mc.addRow(new Object[] { new Long(-1), "Extra name2" });
// I don't know what your cursor holds, I assumed you have the _id column(long value)
// and a name(String value)
int size = cursor.getCount();
for (int i = 0; i < size; i++) {
cursor.moveToPosition(i);
mc.addRow(new Object[] {
cursor.getLong(cursor.getColumnIndex(/*the _id column*/)),
cursor.getString(cursor.getColumnIndex(/* the name column(ename?!?)*/)) });
}
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, mc, new String[] {"ename"}, new int[] {android.R.id.text1});
//...
If you're doing this just to avoid the OnItemSelectedListener from firing when the Spinner is shown, maybe you could have another approach. For example in your listener:
//boolean status = true; flag in MyOnItemSelectedListener
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
if (status) {
status = false;// this is the first listener trigger so you probably want to ignore it
return;
}
// do stuff here
}
Note: I don't know how good is the above solution. If you look there are probably much better solution to this Spinner related issue.

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.

Spinner empty, trying to populate with SimpleCursorAdaptor in subroutine

I am trying to populate a spinner with data from a database. The code is in a subroutine. Everything executes but the spinner is empty. If I copy the code to the "onCreate(Bundle saveInstanceState) it works fine. I am thinking I have context issue but can not figure it out.
Here is the subroutine:
public void showMatchNames (){
Cursor c;
String sMatchName = "MatchTable";
c = db.query(sMatchName, new String[]{KEY_ROWID, KEY_TITLE}, null, null, null, null, null);
if(c.moveToFirst()){
SimpleCursorAdapter MatchAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, c, new String[]{KEY_TITLE}, new int[]{android.R.id.text1});
MatchAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spin2 = (Spinner)this.findViewById(R.id.spinner2);
spin2.setAdapter(MatchAdapter);
}
scrMatchView.setOnItemSelectedListener(new mySpinnerListener());
c.close(); // Done with Cursor so close it
}
There is data in the database, confirmed by exporting to SQliteMan and doing a query.
I can also pull the names from the database and populate the spinner with a simple ArrayAdapter from the "showMatchNames" subroutine.
I am pretty sure it is something simple but I have been staring at this for hours now and can't get it to work.
Any help would be very welcome.

Autocompeletextview & customtable

HI i have a autocompletextview ,when am typing in autocomplete textview i need to directely query the custom table ,insted put it in array, My custom table contain list of names, how can i do this?
You should use SimpleCursorAdapter
SQLiteDatabase db // reference to database
// note that your query result should have an id field with name "_id"
Cursor cursor = db.rawQuery("select name_id as _id, name from table_names", new String[]{});
// create adapter over cursor, returned from database
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_dropdown_item_1line, cursor, new String[]{"name"}, new int[]{android.R.id.text1});
AutoCompleteTextView autocomplete = (AutoCompleteTextView)findViewById(R.id.autocomplete_id);
autocomplete.setAdapter(adapter);
Also you should look at SimpleCursorAdapter.CursorToStringConverter to convert data from cursor to String, which will be displayed. Maybe this link helps you with SimpleCursorAdapter.CursorToStringConverter

Categories

Resources