I'm a little bit stuck on viewbinders in android
here's my code:
public void displayAllAlerts() {
Cursor mCursor = mDbAdapter.fetchAllAlerts();
//Bind Columns
String[] columns = new String[] {
DbAdapter.KEY_ID,
DbAdapter.KEY_PLACE,
DbAdapter.KEY_LONG,
DbAdapter.KEY_LAT,
DbAdapter.KEY_STATUS
};
int[] to = new int[] {
R.id.txtId,
R.id.txtPlace,
R.id.txtLong,
R.id.txtLat,
R.id.tglBtnAlert
};
mSimpleCursorAdapter = new SimpleCursorAdapter(
this,
R.layout.layout_lvrow,
mCursor,
columns,
to,
0);
ListView lvAlerts = (ListView) findViewById(R.id.lvAlerts);
lvAlerts.setAdapter(mSimpleCursorAdapter);
}
The problem is that 'DbAdapter.key_status' is formatted as an int in my database, but someway I have to change it to a boolean, beacuase it's my status for my togglebutton.
I know i have to use .setViewBinder, but i have no idea were to start.
I tried the following from some tutorials but it does not work:
mSimplecursorAdapter.setViewBinder(new ViewBinder() {
public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {
if (aColumnIndex == 5) {
String strBool = aCursor.getString(aColumnIndex);
ToggleButton tb = (Togglebutton) aView;
if (strBool=="0") {
tb.setChecked = false;
}else{
tb.setChecked = true;
}
return true;
}
return false;
}
thanks in advance
(also tried already to use developer site of android but it's giving me a real headache)
The code does not work because you must use String.equals() or TextUtils.equals() to compare strings.
To handle boolean columns on SQLite, I usually handle this data as INTEGER with values 1 or 0:
public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {
if (aColumnIndex == 5) {
boolean checked = aCursor.getInt(aColumnIndex) == 1;
ToggleButton tb = (Togglebutton) aView;
tb.setChecked(checked);
return true;
}
return false;
}
Related
I'm using multiple selection on the listview in my app which is being populated by db (SimpleCursorAdapter). There's some weird behavior with the listview selection.
If there are more than 7 items in the database, if I select the 1st item in the listview, the 8th item also gets selected even when I'm not selecting the 8th item and vice-versa. If I select the 9th item, the 2nd row gets selected.
What's happening here?
Code:
String[] projection = { ..table_columns..};
String[] from = { table_columns..};
Cursor cursor = contentResolver.query(SomeContentProvider.CONTENT_URI, projection, null, null,
null);
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.color,
R.id.name,
R.id.desc,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.layout_main,
cursor,
from,
to,
0);
dataAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int column) {
int nNameIndex = cursor.getColumnIndexOrThrow(EventsTable.COLUMN_NAME);
if( column == nNameIndex ){
TextView nname = (TextView) view;
String name = cursor.getString(cursor.getColumnIndex(EventsTable.COLUMN_NAME));
String formatted_name = "NAME: " +name;
nname.setText(formatted_name);
return true;
}
return false;
}
});
listView.setAdapter(dataAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> av, View v, int pos, long id) {
if (!listView.isItemChecked(pos)){
listView.setItemChecked(pos, true);
v.setBackground(getResources().getDrawable(R.drawable.listview_bg_selected));
v.setSelected(true);
} else {
listView.setItemChecked(pos, false);
v.setBackground(getResources().getDrawable(R.drawable.listview_bg));
v.setSelected(false);
}
if (listView.getCheckedItemCount() > 0) {
if (mMode == null) {
mMode = startActionMode(new ActionModeCallback());
} else {
mMode.setTitle(listView.getCheckedItemCount() + " " + "Selected");
}
} else {
if (mMode != null) {
mMode.finish();
}
}
return true;
}
});
I suspect it's because in your bindView of your adapter you are not checking if the item is checked, and then changing the background appropriately.
You experiencing your views being recycled.
So when you scroll, and say item one goes out of view and was selected, the view for item 1 is reused for item 8.
SO add something like this to your view binder
int post = cursor.getPosition();
if (!listView.isItemChecked(pos)){
v.setBackground(getResources().getDrawable(R.drawable.listview_bg_selected));
} else {
v.setBackground(getResources().getDrawable(R.drawable.listview_bg));
}
Here is my first question on StackOverFlow, I usually always find an answer by myself but I am really stuck on a weird problem that I will explain here:
I implemented a ListView in a fragment activity, this listview contains a list of categories related to the current record that I get from the SQLLite database.
All is working fine, I created a SimpleCursorAdapter to retrieve the data from the DB and I display the categories correctly in the ListView.
The problem is related to the pre-fill of the checkboxes (it is a multiselection list), depending on how I try to pre-check the checkboxes, I get 2 cases:
First, the checkboxes are well pre-checked, but I cannot toggle the checkboxes anymore by clicking them. Second the click toggle well the checkboxes, but they are not pre-checked anymore...
Here is the part of the code where I have the problem:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.rate_fragment, container,false);
dbCategories = "";
displayCategories = resources.getText(R.string.no_categories).toString();
/** INITIALIZATION */
mViewSwitcher = (ViewSwitcher)v.findViewById(R.id.profileSwitcher);
/** Edition view */
rateGroup = (RadioGroup)v.findViewById(R.id.rate_group);
rateOne = (RadioButton)v.findViewById(R.id.one_button);
rateOne.setTag(1);
rateTwo = (RadioButton)v.findViewById(R.id.two_button);
rateTwo.setTag(2);
rateThree = (RadioButton)v.findViewById(R.id.three_button);
rateThree.setTag(3);
rateFour = (RadioButton)v.findViewById(R.id.four_button);
rateFour.setTag(4);
rateFive = (RadioButton)v.findViewById(R.id.five_button);
rateFive.setTag(5);
descET = (EditText)v.findViewById(R.id.editdescription);
descTextSize = descET.getTextSize();
descET.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
categoriesTV_edit = (TextView)v.findViewById(R.id.edit_categories);
categoriesBT = (Button) v.findViewById(R.id.select_categories);
categoriesBT.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
View categoriesListTitle = getActivity().getLayoutInflater().inflate(R.layout.category_list_title, null);
AlertDialog.Builder alt_bld = new AlertDialog.Builder(v.getContext()).setCustomTitle(categoriesListTitle);
categories = db.getAllCategoriesByRate(currentRate);
categoriesList = new ListView(getActivity());
categoriesList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
categoriesList.setClickable(true);
String[] fromColumns = new String[] {
DatabaseHandler.CATEGORY_NAME
};
int[] toViews = new int[]{
R.id.cat_checked
};
//mAdapter = new SimpleCursorAdapter(getActivity(), android.R.layout.simple_list_item_multiple_choice, categories, fromColumns, toViews, 0);
mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.category_item, categories, fromColumns, toViews, 0);
mAdapter.setViewBinder(new ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == 1) {
CheckedTextView categRow = (CheckedTextView) view;
String catName = cursor.getString(1);
mAdapter.setViewText((TextView) view, catName);
int catChecked = cursor.getInt(2);
//boolean checkedCat = catChecked==1;
//categoriesList.setItemChecked(cursor.getPosition(),checkedCat);
categRow.setChecked(catChecked==1);
int catID = cursor.getInt(0);
categRow.setTag(catID);
return true;
}
else {
return false;
}
}
});
categoriesList.setAdapter(mAdapter);
alt_bld.setView(categoriesList);
To have one case or another, all depends on these 2 lines:
//boolean checkedCat = catChecked==1;
//categoriesList.setItemChecked(cursor.getPosition(),checkedCat);
If they are commented, the checkboxes are not pre-checked, but the toggle on the clicks is working. But if I comment these lines out, the toggle is not working anymore but the categories are prechecked.
What I also don't understand is that this line is not working:
categRow.setChecked(catChecked==1);
But this one is working well (I succeed to retrieve the tag):
categRow.setTag(catID);
So I hope someone will succeed to explain to me what I do wrong, I guess there is something I misunderstood here...
NOTE: I get 3 columns from the cursor "categories", first one is the ID of the category, second one is the name, and third one is the status: checked or not (1 or 0).
Thanks in advance for your time.
Finally I ended up creating my own custom adapter, this way I could at least understand more easily what was happening.
I had to create actually several multiselect lists, some populated with data from the database, others from the shared preferences.
For this one displaying data from the DB, I created the following adapter (I commented out the lines about the icons because I did not set them up yet):
public class CategoriesLVAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;
private List<Category> categoriesList;
// Constructor
public CategoriesLVAdapter(Context c, List<Category> categories_list){
mContext = c;
mInflater = LayoutInflater.from(c);
categoriesList = categories_list;
}
public List<Category> getCategoriesList(){
return categoriesList;
}
#Override
public int getCount() {
return categoriesList.size();
}
#Override
public Object getItem(int position) {
return categoriesList.get(position);
}
#Override
public long getItemId(int position) {
return categoriesList.get(position).getID();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.categories_list_row, null);
//convertView.setLayoutParams(new ListView.LayoutParams(200, 90));
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.categories_list_row_tv);
//holder.icon = (ImageView) convertView.findViewById(R.id.categories_list_row_iv);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.icon.setImageResource(categoriesList.get(position).getDrawableID());
//holder.icon.setAdjustViewBounds(true);
//holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.title.setText(categoriesList.get(position).getName());
return convertView;
}
static class ViewHolder {
TextView title;
//ImageView icon;
}
}
In my activity, I use this adapter when the AlertDialog is called to populate the ListView, then I pre-select the categories using the last ones saved in the shared preferences:
private void categoriesFilter(){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setTitle(resources.getText(R.string.select_categories).toString());
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.categories_list,(ViewGroup) findViewById(R.id.categories_layout_root));
categoriesLV = (ListView) layout.findViewById(R.id.categories_list);
alt_bld.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String selectedCategoriesString = getSelectedValues(categoriesLV);
//Update the shared preferences
prefs.edit().putString(RateDayApplication.PREF_KEY_CATEGORIES, selectedCategoriesString).commit();
updateFilterDisplay(resources.getText(R.string.cat_title).toString(), selectedCategoriesString, searchedCategoriesTV, "Category");
}
});
alt_bld.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
String selectedCategoriesString = prefs.getString(RateDayApplication.PREF_KEY_CATEGORIES, new String());
categoriesLV.setAdapter(new CategoriesLVAdapter(this, categoriesList));
String[] selectedCategoriesArray = selectedCategoriesString.split(",");
int categoriesLVLength = categoriesLV.getCount();
for(int i = 0; i < categoriesLVLength; i++){
int categoryID = ((Category) categoriesLV.getItemAtPosition(i)).getID();
if(Arrays.asList(selectedCategoriesArray).contains(String.valueOf(categoryID))){
categoriesLV.setItemChecked(i, true);
}
}
alt_bld.setView(layout);
AlertDialog alert = alt_bld.create();
alert.show();
}
Finally here is the function I call from my database handler to get the list of catagories:
// Getting All Categories By ID desc
public List<Category> getCategoriesList() {
String selectQuery = "SELECT " + CATEGORY_ID + ", " + CATEGORY_NAME + " FROM " + CATEGORY_TABLE + " ORDER BY " + CATEGORY_ID + " ASC";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
List<Category> categoriesList = new ArrayList<Category>();//String[] categoriesList = {};
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Category category = new Category(cursor.getInt(0), cursor.getString(1), false);
categoriesList.add(category);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return categoriesList;
}
I think my problem before was coming from the fact that the function "setItemChecked" is a little misleading because it does not mean necessarily that anything is checked.
When you use the function "setItemChecked", the item in the list view becomes selected, with or without a checkbox (my rows only contain text views).
The rows selected in my list appear in a different color, and that's enough in my opinion for a simple multi selection list.
The layouts I used are quite simple, "categories_list" contains a ListView in a LinearLayout and "categories_list_row" contains a TextView in a LinearLayout.
Hope it may guide someone!
I retrieve from database my swimming performance. I would like to change background color of one field according to his value. For example if i swimm 4 laps I want color background. I try this code that set background correctly but text disappears.
String[] columns = new String[] { "swimm_pos", "swimm_date","swimm_lap", "swimm_stroke", "swimm_time", "swimm_media", "swimm_efficiency", "swimm_note" };
int[] to = new int[] { R.id.row_counter, R.id.swimm_date, R.id.swimm_lap, R.id.swimm_stroke, R.id.swimm_time, R.id.swimm_medialap, R.id.swimm_efficiency, R.id.swimm_note};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.contacto_list_item,
cursor,
columns,
to);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getId() == R.id.swimm_lap)
{
int color = cursor.getInt(columnIndex);
String s = String.valueOf(color);
if (s.equals("4")) {
TextView tv = (TextView)view;
tv.setBackgroundColor(0xFF558866);}
return true;
}
return false;}
});
And is also possible, when lap is equals to 4 set background color of another field, for example in my code: R.id.swimm_pos?
thank you.
Returning true from ViewBinder implies that you are also binding the data to the View.
But in your case you are not setting the text of R.id.swimm_lap.
So add setText before return statement
tv.setText(s);
return true;
Edit:
For the second question suppose you want to change background of R.id.row_counter depending upon swim lap then add
else if (view.getId() == R.id.row_counter){
int color = cursor.getString(cursor.getColumnIndex("swimm_lap"));
if (s.equals("4")) {
view.setBackgroundColor(0xFF558866);
}
}
Solved, here the right code:
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getId() == R.id.row_counter)
{
int color = cursor.getInt(cursor.getColumnIndex("swimm_lap"));
String s = String.valueOf(color);
if (s.equals("4")) {
TextView tv = (TextView)view;
tv.setBackgroundColor(0xFF558866);
}
return true;
}
return false;}
});
this.setListAdapter(adapter);
datasource.close();
}
I have an android.R.layout.simple_list_item_multiple_choice with checkboxes an want so initiate some of them.
How can I do that?
I have the following code:
private void fillList() {
Cursor NotesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(NotesCursor);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_BODY, NotesDbAdapter.KEY_CHECKED };
int[] to = new int[] {
android.R.id.text1,
android.R.id.text2,
//How set checked or not checked?
};
SimpleCursorAdapter notes = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, NotesCursor,
from, to);
setListAdapter(notes);
}
Put the resource id of your checkbox in your row layout into the to array, corresponding to the NotesDbAdapter.KEY_CHECKED cursor in from array.
Implement a SimpleCursorAdapter.ViewBinder.
Have the ViewBinder.setViewValue() method check for when its called for the NotesDbAdapter.KEY_CHECKED column.
When it is not the KEY_CHECKED column, have it return false the the adapter will do what it normally does.
When it is the KEY_CHECKED column, have it set the CheckBox view (cast required) to checked or not as you wish and then return trueso that adapter won't attempt to bind it itself. The cursor and corresponding column id is available to access query data to determine whether to check the checkbox or not.
Set your ViewBinder in your SimpleCursorAdapter via setViewBinder()
Here's one of my ViewBinder implementations. Its not for checboxes, rather its for doing some fancy formatting of a text view, but it should give you some idea for the approach:
private final SimpleCursorAdapter.ViewBinder mViewBinder =
new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(
final View view,
final Cursor cursor,
final int columnIndex) {
final int latitudeColumnIndex =
cursor.getColumnIndexOrThrow(
LocationDbAdapter.KEY_LATITUDE);
final int addressStreet1ColumnIndex =
cursor.getColumnIndexOrThrow(
LocationDbAdapter.KEY_ADDRESS_STREET1);
if (columnIndex == latitudeColumnIndex) {
final String text = formatCoordinates(cursor);
((TextView) view).setText(text);
return true;
} else if (columnIndex == addressStreet1ColumnIndex) {
final String text = formatAddress(cursor);
((TextView) view).setText(text);
return true;
}
return false;
}
};
I have database table with the columns {Name, Time (UTC format) , Latitude, Longitude}
I display the table using a ListActivity with a SimpleCursorAdapter.
I would like that the column Time show the time in a human readable format (13-07-2010 10:40) rather than in UTC format (18190109089).
How can I specify that the values from column Time need some filtering/adaptation?
POSSIBLE SOLUTION (with a problem):
SimpleCursorAdapter offers the method:
setCursorToStringConverter(SimpleCursorAdapter.CursorToStringConverter cursorToStringConverter);
to specify how a class that is able to convert a Cursor to CharSequence (convertToString(Cursor cursor).
Anyway I don't know in which format should be the return CharSequence paramater!
The simplest way to format a cursor value is to use SimpleCursorAdapter.setViewBinder(..):
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list, cursor,
new String[] { Definition.Item.TITLE, Definition.Item.CREATE_DATE }, new int[] { R.id.title, R.id.createDate});
adapter.setViewBinder(new ViewBinder() {
public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex) {
if (aColumnIndex == 2) {
String createDate = aCursor.getString(aColumnIndex);
TextView textView = (TextView) aView;
textView.setText("Create date: " + MyFormatterHelper.formatDate(getApplicationContext(), createDate));
return true;
}
return false;
}
});
i also had the same problem after long struggle finally i found answer :) ( see below )
use setViewText (TextView v, String text)
for example
SimpleCursorAdapter shows = new SimpleCursorAdapter(this, R.layout.somelayout, accountCursor, from, to)
{
#Override
public void setViewText(TextView v, String text) {
super.setViewText(v, convText(v, text));
}
};
private String convText(TextView v, String text)
{
switch (v.getId())
{
case R.id.date:
String formatedText = text;
//do format
return formatedText;
}
return text;
}
You can use setViewBinder(), or subclass SimpleCursorAdapter and override bindView().
You can use SQLite syntax on that column to format the date.
Something like this will do it
SELECT strftime('%d-%m-%Y %H:%M',1092941466,'unixepoch');
SELECT strftime('%d-%m-%Y %H:%M',timecol,'unixepoch');
Going thru this old post, noticed I have done something similar that might help:
public class FormatCursorAdapter extends SimpleCursorAdapter {
protected int[] mFormats;
public static final int FORMAT_TEXT=0;
public static final int FORMAT_CURRENCY=1;
public static final int FORMAT_DATE=2;
public FormatCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int[] formats, int flags) {
super(context, layout, c, from, to, flags);
mFormats = formats;
ViewBinder viewBinder = new ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
int formatType = mFormats[columnIndex-1];
switch (formatType) {
case FORMAT_CURRENCY:
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMaximumFractionDigits(2);
((TextView)view).setText(nf.format(cursor.getDouble(columnIndex)));
return true;
case FORMAT_DATE:
DateFormat df = SimpleDateFormat.getDateTimeInstance();
((TextView)view).setText(df.format(new Date(cursor.getLong(columnIndex))));
return true;
}
return false;
}
};
setViewBinder(viewBinder);
}
}
Usage:
// For the cursor adapter, specify which columns go into which views with which format
String[] fromColumns = {
Table.COLUMN_TITLE,
Table.COLUMN_AMOUNT,
Table.COLUMN_DATE};
int[] toViews = {
R.id.tvTitle,
R.id.tvAmount,
R.id.tvDate};
int[] formatViews = {
FormatCursorAdapter.FORMAT_TEXT,
FormatCursorAdapter.FORMAT_CURRENCY,
FormatCursorAdapter.FORMAT_DATE};
mAdapter=new FormatCursorAdapter(getContext(),R.layout.item_operation,cursor,
fromOpsColumns,toOpsViews,formatViews,0);
mListView.setAdapter(mOpsAdapter);
Hope this helps anyone out there !