Populating Spinner from SQLite database using CursorAdapter - android

I've looked at similar questions but they don't explain how to use a CursorAdapter.
What I'm trying to do is populate a Spinner with a column of Strings read from a selected database.
This is my current code:
//open database depending on selected item
myDatabase = openOrCreateDatabase("Courses"+spSem.getSelectedItem().toString(),MODE_PRIVATE,null);
//read fields to be populated and store them in an arraylist, I need to use arraylist since not every database has the same size
Cursor resultSet = myDatabase.rawQuery("Select * from Subject",null);
resultSet.moveToFirst();
List<String> course = new ArrayList<String>();
for (int i = 1; i < course.size(); i++) {
course.add(resultSet.getString(i));
}
This next part is where I'm stuck, I'm thinking I need to use CursorAdapter() to populate the spinner, but I have no idea how? Previously I had this:
String[] cArr = new String[course.size()];
course.toArray(cArr);
CursorAdapter a = new CursorAdapter(this,cArr,android.R.layout.simple_spinner_item);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCourse.setAdapter(a);
With this code I get the error "CursorAdapter is abstract and cannot be instantiated", and "cannot resolve method'setDropDownView'".

Related

accessing sqlite database with each item in listview

I have a listview that show some items, each item contains attribute called category Id, this is attribute is related to one of my database taples
I need for each item to open database, make a query to get category object where id = item category id and then show data in the listview
it is very heavy to open database to read record by record
can anyone advice how to solve this problem without opening database many times?
Thanks
you can red the data base once. Get all data at the same time. then read the desired data from the returned array.
//returns data from DB
String[] array = getInfoDataBase();
//array example
array = ["id1", "name1", "data2","id2", "name2", "data2", ....]
for (int i = 0; i < array.length; i = i+3) {
if (array[i] == //desired id) {
//get your data from the array like name1, data1
break; // to stop the fro loop
}
}
You can use JOINS for this purpose.
SELECT * FROM item INNER JOIN category ON item.categoryId = category.id WHERE item.id in (id1, id2, id3)
You will have to replace (id1, id2, id3) with the item Ids in your table.

Android : Deleting an item from listview as well as database

I have a listview in which i am adding the items whose values are retrieved from the table in my database. Now, in the current scenario, if i am deleting an item, i am passing the complete string and breaking it in parts to provide information to my delete query.
Instead of all these dumb work, i can simply pass the id of that particular item, but the id is not in the string array which is binded to the listview. How can i delete items from the database by simply using the item's id...?
Note: id is the column in table, so i have each item's id from database. But i am not displaying it in the listview.
String[] records = new String[report.size()];
for(int i = 0; i<report.size(); i++)
{
if(report.get(i).getDate()!="")
{
String eachRecord = (i+1) +". "+report.get(i).getDate() + " -- " + report.get(i).getType();
records[i] = eachRecord;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.singlerow, records);
listView.setAdapter(adapter);
You should map the data you are getting from the Database to a java object.
Read the data from the db store in list or array whatever you like.
Create your custom adapter by extending the BaseAdaper REF and pass your list of object to it.
In Adapter's getView build your view.
Now when you delete your list item you can easily find that object and ask for the id of it. You can use this id to delete the item from db. Now you can refresh the list with the remaining data.

Adding two .sqlite DB into a list and showing by adapter

I have two databases .sqlite in Android.
productosdb.sqlite and entradas.sqlite with one table each.
In productosdb I have the table "entradas"={id,cod1,cod2,descrip,present,pale} and in the other "entradas"={id,idref(that is cod1 already saved from the other table),cant,vto}
I want to show all items of table "entradas" but giving to the adapter a list that has all fields of both tables. When I get a row from table "entradas" I get the message idrefto search the other the missing fields. Something is not working. Here's some of the code:
private List<ProductoSUMADO> listasumada = new LinkedList<ProductoSUMADO>();
Producto temporalProducto = new Producto();
List<ProductoConVencimiento> temporalEntrada = new LinkedList<ProductoConVencimiento>();
String asd = bundle.getString("codigo");
temporalProducto = managerdb.getProductoPorCodigoBarras(asd);
String sss = temporalProducto.getCodprod();
temporalEntrada = db.getProductosPorIDRef(sss);
for (int pos = 0; pos < temporalEntrada.size(); pos++)
{
ProductoSUMADO p = new ProductoSUMADO(temporalProducto.getCodbar()),
temporalProducto.getCodprod(),
temporalProducto.getDescrip(),
temporalProducto.getPresent(),
temporalProducto.getPale(),
temporalEntrada.get(pos).getCant(),
temporalEntrada.get(pos).getVto(),
temporalEntrada.get(pos).getNotas());
listasumada.add(p);
}
CustomAdapter2 adapter = new CustomAdapter2(this, listasumada);
listview.setAdapter(adapter);
Maybe you understand what I want to do and show another way to do this.
You are doing it wrong. Just create one database and two tables "productos" and "entradas"
then you will be able to JOIN data using rawQuery.
Learn more about SQLite here: vogella
it has examples so you can test it!
Join example:
String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";
db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});

update My Spinner from SQlite Database

I FOUND A SOLUTION FOR RESTORING MY VALUES, SEE MY NEW VERSION of populateFields()
Okay so I have been reading through all the Spinner and SQlite posts on here and cannot seem to find a good answer for what I am looking for so I am posting this scenario.
My app has two screens and uses the sqlite database on my device saving a name and weight fields from editTexts as strings like so
String eName = name.getText().toString();
String eWeight = weight.getText().toString();// where name and weight are EditTexts
and I have two spinners as follows
String eReps = spinReps.getSelectedItem().toString();
String eSets = spinSets.getSelectedItem().toString();
Then I call this to add to the database
long id = mDbHelper.createExercise(eName, eWeight, eReps, eSets);
Here is where my issue is, upon someone selecting to create a new exercise my app crashes because it is trying to populate a spinner incorrectly. Here is what I have currently.
private void populateFields(){
if(mRowId != null){ // where mRowId is the selected row from the list
Cursor exercise = mDbHelper.fetchExercise();
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
// this is the part that i need help with, I do not know how to restore
// the current items spinner value for reps and sets from the database.
spinReps.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinSets.setSelection(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS)));
}
I assume I need to use some sort of adapter to restore my list items along with the current value from the database, I am just not sure how.
Can someone please help me with this???
** BELOW IS MY SOLUTION**
I had to move my ArrayAdapters repsAdapter, spinAdapter out of my onCreate()
and then implement this new populateFields()
private void populateFields(){
if(mRowId != null){
Cursor exercise = mDbHelper.fetchExercise(mRowId);
// same as before
name.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_NAME)));
// get the string for sReps and sSets from the database
String sReps = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
String sSets = exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_SETS));
// use the strings to get their position in my adapters
int r = repsAdapter.getPosition(sReps);
int s = setsAdapter.getPosition(sSets);
// set their returned values to the selected spinner Items
spinReps.setSelection(r);
spinSets.setSelection(s);
// same as before
weight.setText(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_WEIGHT)));
}
}
The way to set a Spinner to a value, not a position, depends on what adapter you are using.
ArrayAdapter, this one is easy:
int position = adapter.getPosition(exercise.getString(exercise.
getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS)));
spinReps.setSelection(position);
SimpleCursorAdapter, this one is a little harder:
String match = exercise.getString(exercise.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS));
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(-1);
int columnIndex = cursor.getColumnIndexOrThrow(ExerciseDbAdapter.KEY_REPS);
while(cursor.moveToNext()) {
if(cursor.getString(columnIndex).equals(match))
break;
}
spinReps.setSelection(cursor.getPosition());
If you are using a different type of adapter and can't modify the code above to fit it, let me know. Hope that helps!

List View Problem

i have a problem in a list view.. i want to put different fields in the same listview is this possible?
like this?
DBAdapter db = new DBAdapter(.this);
db.open();
List<String> ct = new ArrayList<String>();
ct = db.getAllAccounts();
List<String> sd = new ArrayList<String>();
sd = db.getAllAmount();
Account = (ListView) findViewById(R.id.ListView_addAccount);
Account.setAdapter(new ArrayAdapter<String>(this,R.layout.list_contas_layout,R.id.text1,R.id.text2, ct,sd));
theres something like this to use?
sorry about my english;)
Absolutely. Take a look at SimpleCursorAdapter. I'm not sure what database you're using, but using the Cursor class is pretty normal for this sort of thing. Otherwise you're going to have to create your own custom adapter.

Categories

Resources