How can I get my spinner to fill with database data? - android

I'm having a lot of problems trying to get my spinner to fill with data after my application loads. I'm just messing around and made a database for vehicles. So I'm trying to get a spinner to load the database data into it. This is the code I use in a method to attempt to do so, but my spinner is never loaded with my database data.
SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT vehicle_make, vehicle_model, vehicle_year FROM vehicles;", null);
vehicleProfileSpinner = (Spinner) findViewById(R.id.vehicleProfileSpinner);
startManagingCursor(cursor);
String[] columns = {"vehicle_year", "vehicle_make", "vehicle_model"};
int[] theView = {R.id.vehicleProfileSpinner};
SimpleCursorAdapter vpsAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_dropdown_item, cursor, columns, theView);
vpsAdapter.setDropDownViewResource(R.layout.main);
vehicleProfileSpinner.setAdapter(vpsAdapter);

In my case instead of using Simplecursoradapter, I have created array from cursor entries and created ArrayAdapter and set it to list. It worked perfect. Somehow Simplecursor adapter looks for ID field and causing issue,so I ignored it and used Arrayadapter. I will try to update this post with example I posted for other question.

One thing is all you need SimpleCusorAdapter.

Related

Retrieve CursorAdapter with activeAndroid and SearchView

I try to implement a "android.support.v7.widget.SearchView" into my toolBar who should provide some suggestions to the user.
I wished activeAndroid could provide me a way to retrieve a CursorAdapter directly from my query (basically a getAll()).
The following link seems to be deprecated since .toSql() require private access and "Cache" is unresolved.
Any idea?
You can create a Cursor via ActiveAndroid using:
Cursor cursor = ActiveAndroid.getDatabase().rawQuery("SELECT * FROM TABLE", null);
The CursorAdapter you will need to build yourself but is quite easy and the "Defining the Adapter" section of the link you provided should give you what you need to get started.
Please note that ActiveAndroid 3.1.0 does show the .toSql() as public.
One thing you will need to do is make sure your ActiveAndroid db model includes the expected _id column which is not there by default with ActiveAndroid. You'll want to uninstall the app or perform a database migration to see the changes to the underlying db model. Otherwise you may get this error
java.lang.IllegalArgumentException: column '_id' does not exist
Include the expected '_id' column which is not there by default with ActiveAndroid:
#Table(name = "Items", id = BaseColumns._ID)
Request the cursor like this:
public Cursor getCursor() {
String sql = new Select()
.from(Item.class)
.toSql();
String[] params = null;
Cursor cursor = Cache.openDatabase().rawQuery(sql, params);
return cursor;
}
You could then create an adapter like this:
ListAdapter adapter = new SimpleCursorAdapter(context,
android.R.layout.simple_list_item_1,
c, new String[] {"Name"}, new int[] { android.R.id.text1}
);

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.

Retrieving and displaying a contact name from a contact id while using a SimpleCursorAdapter

I am storing information on the phone's contacts using a sqlite database.
The fields I am storing are: _id, contact_id, body where _id is the row's id, contact_id is the phone contact's id and body is just a simple text which is the actual information I am storing.
I'm using a SimpleCursorAdapter to map the data to the view, like so:
Cursor cursor = database.fetchInformation(); // fetch info from DB
String[] from = new String[] { CONTACT_ID, BODY };
int[] to = new int[] { R.id.contact, R.id.body };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
getListView().setAdapter(adapter);
What I would actually want is to get the contact name that is associated with this CONTACT_ID, and have that be shown in the view.
I can't seem to find a simple solution. I've tried implementing my own SimpleCursorAdapter and rewriting setViewText(TextView, String) but it didn't work. Also, it just seems overly complicated for such a simple task.
Any help? Thanks.
You really have two options here:
1) You could create a MatrixCursor that contains all the information you wish to bind to your ListView. While its not very difficult to do this, its probably not the most efficient use of memory because you would need to get the name of every contact in your cursor.
2) You could subclass from CursorAdapter. Its pretty simple to implement the appropriate newView and bindView methods. Inside of bindView you would simply query the phone's contact content provider to get the name of the contact currently being bound.
try this
String where=PEOPLE.CONTACT_ID+"="+requiredId;
String[] projection={People.Name};//u only need name right?
int[] to = new int[] {R.id.body };//if body is ur text view
Cursor cursor = getContentResolver().query(People.CONTENT_URI,projection,where,null, null);
ListAdapter adapter=new SimpleCursorAdapter(this,R.layout.row,result,projection,to);
setListAdapter(adapter);

Android query sqlite database

What am I doing wrong!?!??
I am trying to get a set of data to a listview.
First I Open the database and then I trying to get the set,
I get a response but only 1 row from the database and I am getting at least 10 when I trying it in sqlite browser.....
Anyway I don't know if this make any sense, here is the code: (i am new at this, please don't laugh to much)
And btw I use the same methods/functions in another listview but then I don't have any WHERE in my query and that works fine....
So I want to get all the rows from the database and i only get the first one :)
Thanks mates!
db.openDataBase();
Cursor c = db.getCoursesFromCountyID(countyID);
BindsimpleCursorAdapter(c);
db.close();
the getCoursesFromCountyID =
int id = Integer.parseInt(county);
return db.query("Courses", new String[]{KEY_course_ID, KEY_course}, KEY_county_ID + " = " + id, null, null, null, null);
And the BindsimpleCursorAdapter looks like this =
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.simpleadapter_courses, c, new String[]{DataBaseHelper.KEY_course_ID, DataBaseHelper.KEY_course}, new int[]{R.id.courseID, R.id.course});
ListView lv = new ListView(this);
lv = (ListView)findViewById(R.id.listViewCourses);
lv.setAdapter(adapter);
I don't see any problems on your code, try adding 'KEY_county_ID' to you projection argument and removing the selection argument to check if all the rows are really there.

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.

Categories

Resources