ListView with SimpleCursorAdapter - android

in my app i am using a listview to display a menu of dishes with their Dish Names
This is the code where i bind the data from the query to the listview using the adapter:
private void getDishes() {
DBAdapter db = new DBAdapter(this);
db.open();
Cursor cursor = db.getAllDishes();
cursor.moveToFirst();
Log.w("ppp","kk - " + cursor.moveToFirst());
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.list_item, cursor, new String[] { DBAdapter.DishName },
new int[] {R.id.dishName });
setListAdapter(adapter);
db.close();
}
My Query code looks like this:
public Cursor getAllDishes()
{
return db.query(DATABASE_TABLE, new String[] {DishName},null,null,null,null,null);
}
Really appreciate any help/comments as i have been stuck on this for almost a week now.

Can you explain explicitely what's your problem?
My suggest change
public Cursor getAllDishes()
{
return db.query(DATABASE_TABLE, new String[] {DishName},null,null,null,null,null);
}
to
public Cursor getAllDishes()
{
Cursor dishes = db.query(DATABASE_TABLE, new String[] {DishName},null,null,null,null,null);
if(dishes != null)
dishes.moveToFirst();
return dishes;
}
Then
in getDishes() method write like this
private void getDishes() {
DBAdapter db = new DBAdapter(this);
db.open();
Cursor cursor = db.getAllDishes();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(YourActivity.this,
R.layout.list_item, cursor, new String[] { DBAdapter.DishName },
new int[] {R.id.dishName });
setListAdapter(adapter);
db.close();
}

Related

How do you Populate ListView With SQLite?

My program crashes every time I try to run this method:
private void populateListView() {
Cursor cursor = myDB.getAllRows();
startManagingCursor(cursor);
String[] from = new String[] {ProductContract.ProductEntry.INPUT, ProductContract.ProductEntry.DATE};
int[] to = new int[] {R.id.t_input, R.id.t_date};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.display_row, cursor, from, to, 0);
ListView myList = (ListView) findViewById(R.id.display_listview);
myList.setAdapter(myCursorAdapter);
}
Here's my getAllRows method:
public Cursor getAllRows() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.query(true, ProductContract.ProductEntry.TABLE_NAME, ProductContract.ProductEntry.ALL_KEYS,
null, null, null, null, null, null);
if(c != null) {
c.moveToFirst();
}
return c;
}

Append text to data returned from SQLite query before displaying in ListView

I am retrieving a set of results from an SQLite database and displaying it in a ListView.
What I want to do is to append some text before the result value before showing it in the actual ListView.
For example, if I am getting a value 5 from the database, I want to display it as Value = 5 in the ListView.
Here is the code that I am using for updating the ListView:
private void displayListView() {
Cursor cursor = dbHelper.fetchAllSubjects();
String[] columns = new String[]{
getSubjectsDbAdapter.KEY_SUBJECT,
getSubjectsDbAdapter.KEY_SEMESTER,
getSubjectsDbAdapter.KEY_ATTENDED,
getSubjectsDbAdapter.KEY_TOTAL,
getSubjectsDbAdapter.KEY_PERCENT
};
int[] to = new int[]{
R.id.sub_out,
R.id.semester_out,
R.id.attended_out,
R.id.total_out,
R.id.percent_out
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.list_layout, cursor, columns, to, 0);
subject_list.setAdapter(dataAdapter);
}
What I had tried was the following modification to the String[] array:
private void displayListView() {
Cursor cursor = dbHelper.fetchAllVals();
String[] columns = new String[]{
"Val1" + getSubjectsDbAdapter.KEY_1,
"Val2: " + getSubjectsDbAdapter.KEY_2,
"Val3: " + getSubjectsDbAdapter.KEY_3,
"Val4: " + getSubjectsDbAdapter.KEY_4,
"Val5: " + getSubjectsDbAdapter.KEY_5
};
int[] to = new int[]{
R.id.one,
R.id.two,
R.id.three,
R.id.four,
R.id.five
};
dataAdapter = new SimpleCursorAdapter(this, R.layout.list_layout, cursor, columns, to, 0);
subject_list.setAdapter(dataAdapter);
}
But that gave me the following error:
java.lang.IllegalArgumentException: column 'Val2: val2Val3: val3' does not exist
I got my answer here at SO.
Cursor allTaskcursor = databaseHelper.getAllTasks();
String[] from = {"name", "date"};
int[] to = new int[] {android.R.id.text1, android.R.id.text2};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_2, allTaskcursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
cursorAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getId() == android.R.id.text2) {
int getIndex = cursor.getColumnIndex("date");
int date = cursor.getInt(getIndex);
TextView dateTextView = (TextView) view;
dateTextView.setText(date + " days");
return true;
}
return false;
}
});
allTaskListView.setAdapter(cursorAdapter);

display data from sqlite according to value

i need your help, i did display data in a list view but the problem is that i
want the data to be according to a specific value, that means if the id = 1, only the rows
concerned will be displayed, if you have any suggestions i would be very thankful :
here the code of :
public class MainActivity extends ListActivity {
private static final int FLAG_REGISTER_CONTENT_OBSERVER = 2;
private Cursor cursor;
SimpleCursorAdapter adapter = null;
Cursor c;
DBAdapter db = new DBAdapter(this);
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db.open();
populateListViewFromDB();
} catch (Exception e) {
Log.e("ERROR", "Error occured: " + e.toString());
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
private void populateListViewFromDB() {
Cursor cursor = db.getAllRecords();
startManagingCursor(cursor);
String[] databaseColumnNames = new String[] { DBAdapter.col_region, };
int[] toViewIDs = new int[] { R.id.text };
SimpleCursorAdapter myCursordapter = new SimpleCursorAdapter(this,R.layout.activity_main, cursor, databaseColumnNames, toViewIDs,FLAG_REGISTER_CONTENT_OBSERVER);
ListView list = (ListView) findViewById(android.R.id.list);
And my DBAdapter is :
private static final String MENAGE = "table_MENAGE";
public static final String _id = "Num_du_Questionnaire";
public Cursor getAllRecords() {
return db.query(MENAGE, new String[] { _id, col_region,
}, null, null, null,
null, null);
}
list.setAdapter(myCursordapter);
} }
As you may check in query documentation, function accepts a selection and selectionArgs parameters, corresponding to SQL WHERE clause.
So, to make a query limited to a specific id, just use:
db.query(MENAGE, new String[] { _id, col_region}, "id = ?", new String[] {_id}, null, null, null);

What is the best way to list all rows in Sqlite Android ?

I'm currently using the following code to pass all items in some columns to Arrayadapter.
private void TestListAll(){
//Displays the whole list.
cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?",
new String[]{"%" + "" + "%"});
adapter = new SimpleCursorAdapter(
this,
R.layout.emp_list_item,
cursor,
new String[] {"firstName", "lastName", "title"},
new int[] {R.id.firstName, R.id.lastName, R.id.title});
setListAdapter(adapter);
}
Is there a better method to accomplish this?
in my app i use somethink like this:
public ArrayList<HashMap<String, ?>> selectLastPlayed() {
ArrayList<HashMap<String, ?>> list = new ArrayList<HashMap<String, ?>>();
Cursor cursor = this.db.query("employee Order BY ID DESC",
new String[] { "*" }, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, Object> temp = new HashMap<String, Object>();
temp.put("Icon", cursor.getString(1));
temp.put("Title", cursor.getString(2));
list.add(temp);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
and then, you can put arraylist into adapter ;)
like this:
SimpleAdapter adapter = new MySimpleAdapter(this, selectLastSearch(), R.layout.custom_row_view, new String[] { "Icon", "Icon" }, new int[] { R.id.textView1123, R.id.imageView12 });
this is my simple adapter:
public class MySimpleAdapter extends SimpleAdapter {
Context localcontext = null;
public MySimpleAdapter(Context context,List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
localcontext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
return view;
}
}
Yeah there is an easier way. Instead of writing out that sql select by hand let Android do it with a cursor in your database helper class. This selects everything in your table with no selection arguments.
public Cursor getAllItems() {
return this.sqliteDBInstance.query(EMPLOYEE_TABLE, null, null, null, null, null, null);
}
And then in your activity you only show firstname, lastname, and title even though _id was selected in the getAllItems Cursor method. I assume you do not want to show it in the listview.
Private Cursor cursor;
...
cursor = db.getAllItems();
startManagingCursor(cursor);
ListAdapter adapter = new SimpleCursorAdapter(MyActivity.this,
R.layout.emp_list_item, cursor, new String[] { "firstName", "lastName", "title" }, new int[] { R.id.firstName, R.id.lastName, R.id.title });
setAdapter(adapter);

Fill spinner from cursor in android

i have searched for a awnser for this for a while today. It all looks so easy but i never get it to work. I want to fill a spinner with my cursor. I have been trying to use SimpleCursorAdapter for this as a lot of sites say i shall but i never get it to work. Show me just how easy it is :)
Thanks for your time!
My cursor
Cursor cursor = db.query(DATABASE_TABLE_Clients, new String[] {"_id", "C_Name"}, null, null, null, null, "C_Name");
My spinner
(Spinner) findViewById(R.id.spnClients);
My Code
Cursor cursor_Names = SQLData.getClientNames();
startManagingCursor(cursor_Names);
String[] columns = new String[] { "C_Name" };
int[] to = new int[] { R.id.txt_Address };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_dropdown_item, cursor_Names, columns, to);
Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
spnClients.setAdapter(mAdapter);
The following code solved my problem. I was missing .setDropDownViewResource. After that i used simple_spinner_dropdown_item so i don't have to make my own layout.
Cursor cursor_Names = SQLData.getClientNames();
startManagingCursor(cursor_Names);
String[] columns = new String[] { "C_Name" };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor_Names, columns, to);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spnClients = (Spinner) findViewById(R.id.spnClients);
spnClients.setAdapter(mAdapter);
I don't see a View for your dropdown in your code. Something like:
mAdapter.setDropDownViewResource(R.layout.spinner_view_dropdown);
Of course you need to have a spinner_view_dropdown.xml file in your res/layout directory.
I have done it
empresasSpinner = (Spinner) findViewById(R.id.empresasSpinner);
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, empresasAll.toArray(new EntidadObject[0]));
empresasSpinner.setAdapter(spinnerArrayAdapter);
A simple DTO
public class EntidadObject {
private int id;
private String nombre;
//GETTES and SETTERS
}
The part DAO
public class EntidadDao {
//...
public List<EntidadObject> getEmpresas() {
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM empresas", null);
List<EntidadObject> entidadObjects = new ArrayList<EntidadObject>();
cursor.moveToFirst();
do {
EntidadObject entidadObject = new EntidadObject();
entidadObject.setId(cursor.getInt(0));
entidadObject.setNombre(cursor.getString(1));
entidadObjects.add(entidadObject);
} while (cursor.moveToNext());
return entidadObjects;
}
}
So then I can catch the ID of the select item with
EntidadObject eo = (EntidadObject)empresasSpinner.getSelectedItem();
eo.getId();

Categories

Resources