BindView after cursor update - android

I'm trying to update a view displayed by a CursorAdapter just after its data modification.
Each row contains an image. When I touch this image, the database is update and I want to modify the image regarding this data update.
Except a requery on the cursor i didn't find a solution...My database is really big and a requery is too heavy. Do you have a better solution ?

Yes, sometimes requery is not the best solutions. What I usually do is creating helping methods in the database adapter to retrieve pieces of code. This is an excerpt of one of my adapters:
#Override
public void bindView(View view, final Context context, Cursor cursor) {
String name = cursor.getString(cursor.getColumnIndex("name"));
long id = cursor.getLong(cursor.getColumnIndex("_id"));
((TextView)view.findViewById(R.id.name)).setText(name);
Button btnFavorite = (Button) view.findViewById(R.id.item_add_favorite);
btnFavorite.setTag(id);
btnFavorite.setOnClickListener(mFavoriteCliked);
}
What I do is basically set a click listener to the image... and make sure it takes care of change its state properly:
private OnClickListener mFavoriteCliked = new OnClickListener() {
#Override
public void onClick(View v) {
// change the image of the v object
}
};

Related

CursorLoader + CursorAdapter + Regular DB updates = Gridview Flicker

I have a custom image gallery app that stores the image data in a database. The gallery is a GridView backed by CursorAdapter.
When first requesting an image decode ContentResolver.update updates the height, width, and orientation in a background thread. Since many images are visible at a time the database updates are happening rapidly as a user scrolls which causes the backing CursorLoader to refresh the GridView rapidly which manifests itself as a rapid flicker.
Is it not possible to use CursorLoader and CursorAdapter if the underlying source can rapidly change, or am I missing something here?
When there's a change to monitored data (selection, projection) within a database the LoaderManager simply supplies a new cursor. As such, as far as the CursorAdapter is concerned it will have an entirely new datasource (swapCursor) on every update to the database:
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor)
{
mGalleryAdapter.swapCursor(cursor);
}
Therefore the ideal CursorAdapter attached to a dynamic LoaderManager will need to micro-manage view updates to ensure that it does not bother updating views that are exactly the same. To do so (since my views are fairly complicated) I created a helper object to handle translations and comparisons between cursor and views (removed most views for the sake of brevity).
public static class GalleryItem
{
private String name;
private int rotation;
public static GalleryItem fromCursor(Context c, Cursor cursor)
{
GalleryItem item = new GalleryItem();
item.rotation = ImageUtils.getRotation(cursor.getInt(Meta.ORIENTATION_COLUMN));
item.name = cursor.getString(Meta.NAME_COLUMN);
return item;
}
public static GalleryItem fromViewHolder(ViewHolder vh)
{
GalleryItem item = new GalleryItem();
item.rotation = (int)vh.mImageView.getRotation();
item.name = (String) vh.mFileName.getText();
return item;
}
#Override
public boolean equals(Object o)
{
GalleryItem compare = (GalleryItem) o;
boolean sameRotation = rotation == compare.rotation;
boolean sameName = name == null ? compare.name == null : name.equals(compare.name);
return sameName && sameRotation;
}
}
Then use this to check if you need to update anything in the view:
#Override
public void onBindViewHolder(ViewHolder vh, final int position, Cursor cursor)
{
GalleryItem galleryItem = GalleryItem.fromCursor(mContext, cursor);
GalleryItem former = GalleryItem.fromViewHolder(vh);
// If nothing has changed avoid refreshing.
// The reason for this is that loaderManagers replace cursors meaning every change
// will refresh the entire data source causing flickering
if (former.equals(galleryItem))
return;
...
So long story short, with a dynamic LoaderManager you'll have to implement a way to skip recreating completely unchanged views.

Change Specific TextView Color in Listview

i Have Two Database
first one Contain All The Items, and the ListView Display it
and the second db contain the the Favorite item , [selected from the first database]
what i want is that when the listview display all the items
check if the item is already exist in Favoritelist then make that textview background RED for this item
i have this code that work fine
public static void ChangeMyFavoritesBG(){
for (int i = 0; i < Items.size(); i++) {
if(db.verification(Items.get(i).toString())){
try {
TextView favtextview = (TextView) listview.getChildAt(i-listview.getFirstVisiblePosition()).findViewById(R.id.item_name);
favtextview.setBackgroundResource(R.drawable.redcolor);
}catch (NullPointerException e) {
}}}}
db.verification check if item exist in favorites database
if true . then it should change the background of this item to red
this code work fine but only if i put it in button click
i need to make the code work automatically
but if i made it start automatically when the activity is loaded i get NullPointer Error
i guess because the function ChangeMyFavoritesBG(); work before the listview display items
any idea guys? and sorry for my bad english
Do this control inside the getView(int position, View convertView, ViewGroup parent) method of the Adapter used by the listView.
If your favorite is not currently visible in the ListView then getChildAt() will return null.
You are looping over all items in the list view and my guess is that it holds more items than can fit on the screen. When your favorite item is one of them then this fragment of your code
listview.getChildAt(i-listview.getFirstVisiblePosition())
will return null. And that will cause the NullPointerException when you call findViewById(R.id.item_name) on it.
Just add a check for null on the result of getChildAt(). If it is null then do nothing, if it is non-null then call the second part. This will protect against the exception when your favorite item is not on the screen, and will allow it to be colored red when your favorite is visible on the screen.
update
My apologies, I read to quickly and misunderstood your problem to be about the NullPointerException but you say that your code works fine when you call it from a button click handler but not when you call it automatically at start-up.
You are right, the ListView does not yet have any items loaded when you are still in onCreate(). You can add a delay before running you code. The following works for me:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
// initialize the ListView with data for the list items. (I'm using a string array in this
// example. You are loading it from a database table, but that is the same in principle.)
ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.item_list, R.id.item_name, Items);
ListView listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(adapter);
// ask the system to wait before setting the background color of the favorite item so that
// the ListView has time to load the items.
final int DELAY_IN_MILLISECONDS = 100;
listview.postDelayed(new Runnable() {
#Override
public void run() {
ChangeMyFavoritesBG();
}
}, DELAY_IN_MILLISECONDS);
}
As you can see in the above example, after initializing the ListView, you ask the system to wait 100 milliseconds before calling ChangeMyFavoritesBG(). Hopefully that is enough time to load the items from the database into the ListView. If it is not enough time then you can, of course, use a longer delay.
The alternative
The above should work, but to be honest I would not write it this way. The above code is very brittle because it depends on the timing of how long it takes to load the items. I recommend that you put your background coloring into a customized adapter.
Because you want the items displayed in a customized way -- you want them to have a red background when it is the favorite one -- you should use a customized adapter. Override the bindView() function to make the background red when it is the favorite one or give it a normal background when it is not the favorite.
I don't know how you currently get the items from the database into your ListView, but inheriting from SimpleCursorAdaptor would work pretty well.
public class FavoritesItemAdapter extends SimpleCursorAdapter {
public FavoritesItemAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
// read the name from the database
int nameColumnIndex = cursor.getColumnIndexOrThrow("name");
String name = cursor.getString(nameColumnIndex);
// write the name to the TextView
TextView nameText = (TextView) view.findViewById(R.id.item_name);
nameText.setText(name);
// set the background to normal or to red, depending on if it is the favorite one or not
boolean isFavorite = db_verification(name);
if (isFavorite) {
nameText.setBackgroundResource(R.drawable.redcolor);
} else {
nameText.setBackgroundResource(android.R.color.transparent);
}
}
public boolean db_verification(String name) {
// this is a stub. You must use your own code here
return name.equals("the favorite one");
}
}
You can then throw away ChangeMyFavoritesBG() and initialize your ListView with the adapter in onCreate() like this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Cursor cursor = readItemsFromDatabase();
String[] from = new String[] { "name_column" }; // mapping from database column name ...
int[] to = new int[] { R.id.item_name }; // ... to View ID in the item's layout.
FavoritesItemAdapter adapter = new FavoritesItemAdapter(this, R.layout.item_list, cursor, from, to, 0);
ListView listview = (ListView) findViewById(R.id.listview);
listview.setAdapter(adapter);
}
Good luck!

ContentProvider - returning multiple Cursors or custom Object

I have a working implementation of a ContentProvider loading data via CursorLoader into a listview (with custom CursorAdapter). It's a list of events. Every item has a title, place, etc. but also a set of offers which should be displayed in a LinearLayout inside every list row.
The problem is that a Cursor row can only contain flat data, not a set of other items.
My only idea is to make a joined query on database like this:
SELECT * FROM events, offers WHERE events.id=offers.event_id;
But then I'll have as much rows as there are offers (and the list should display events, so it's not good) and the list would be overpopulated. Maybe there is a possibility to tell CursorAdapter to only populate list rows with unique events.id but somehow retrieve the offers data as well?
The best solution would be to put a Cursor or custom Object containing offers inside the events Cursor. But afaik it's not possible.
I was facing the same problem. In fact, I think a lot of people are.
The whole mechanism of URI - to Relational DB through contentprovider, and everything that was built around it (like the various change listeners, file and stream handling) - this is all very impressive and useful, but for very simple data models.
Once your application needs a more elaborate data model, like - a hierarchy of tables, object relational semantics - this model breaks.
I've found a bunch of ORM tools for Android, but they seem too 'bleeding edge' to me (plus, for the life of me, I couldn't figure out if they have data change notification support).
ORM is very common today, I really hope the Android folks agree and add ORM capabilities to the platform.
This is what I ended up doing:
A cursor of cursors, with a a leading index cursor that helps choose the correct internal curosr.
It's kind of a temp solution, I just needed to move on with my code and get back to this later. Hope this helps.
Of course if you use a listview, you probably need to also create a custom adapter to inflate the correct views, and do the binding.
public class MultiCursor implements Cursor {
private final String TAG = this.getClass().getSimpleName();
ArrayList<Cursor> m_cursors = new ArrayList<Cursor>();
Map<Long, CursorRowPair> m_idToCursorRow = Collections.synchronizedMap(new HashMap<Long, CursorRowPair>());
Set<Long> m_idSet = new HashSet<Long>();
Cursor m_idCursor;
/**
* #precondition: _id column must exist on every type of cursor, and has to have index of 0 (be the first)
* #param idCursor
*/
public MultiCursor(Cursor idCursor) {
m_idCursor = idCursor;// this cursor binds the order (1,2,3) to ids
// go over all the ids in id cursor and add to m_idSet
initIdSet();
// m_cursors.add(idCursor);
// m_position = -1;
}
private void initIdSet() {
m_idSet.clear();
long id;
m_idCursor.moveToPosition(-1);
while (m_idCursor.moveToNext()) {
id = m_idCursor.getLong(m_idCursor.getColumnIndex(ContentDescriptor.ShowViewItem.Cols.ID));
m_idSet.add(id);
}
m_idCursor.moveToFirst();
}
public void addCursor(Cursor cursor) {
// when something changes in the child cursor, notify parent on change, to notify subscribers
// cursor.registerContentObserver(new SelfContentObserver(this)); // calls my onchange, which calls the ui
m_cursors.add(cursor);
updateIdToCursorMap(cursor);
}
private class CursorRowPair {
public final Cursor cursor;
public final int row;
public CursorRowPair(Cursor cursor, int row) {
this.cursor = cursor;
this.row = row;
}
}
private void updateIdToCursorMap(Cursor cursor) {
// get object_type
// for each row in cursor, take id, row number
// add id, <cursor,rowNum> to map
long id;
int row = 0;
cursor.moveToPosition(-1);
while (cursor.moveToNext()) {
id = cursor.getLong(cursor.getColumnIndex(ContentDescriptor.ShowViewItem.Cols.ID));
if (m_idSet.contains(id)) m_idToCursorRow.put(id, new CursorRowPair(cursor, row));
row++;
}
cursor.moveToFirst();
}
private Cursor getInternalCursor() {
if (getPosition() < 0 || getCount()==0) return m_idCursor; // todo throw a proper exception
// get the id of the current row
long id = m_idCursor.getLong(m_idCursor.getColumnIndex(ContentDescriptor.BaseCols.ID));
CursorRowPair cursorRowPair = m_idToCursorRow.get(id);
if (null == cursorRowPair) return null;
Cursor cursor = cursorRowPair.cursor;
int row = cursorRowPair.row;
cursor.moveToPosition(row);
return cursor;
}
// //////////////////////////////////////////////
#Override
public void close() {
Log.d(TAG, "close");
for (Cursor cursor : m_cursors) {
cursor.close();
}
m_idCursor.close();
}
#Override
public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) {
Log.d(TAG, "copyStringToBuffer");
getInternalCursor().copyStringToBuffer(columnIndex, buffer);
}
etc etc etc.
In you're adapter query the offers cursor for all records and make it a class variable. Then in your getView use the event id to iterate through the offer cursor and add the necessary textviews to your row layout when it find an appropriate match. It's not elegant, but it should work.
Unfortunately one CursorLoader can only load one Cursor. So the solution was to write a custom AsyncTaskLoader which returned two Cursors.

how does cursor know which item is clicked in listview?

I have a activity displaying call logs in a ListView. The adapter used here to populate listview extends CursorAdapter. Listview is set to onItemClickListener(..). My Question is whenever an item is clicked how does cursor get the data? how does cursor know which position is clicked and need to get data from clicked position only? I have provided a code snippnet.
public class CallLog extends Activity
{
ListView mListView;
Cursor cursor;
//other variables
public void OnCreate()
{
setContentView(R.layout.calllog);
//SQLiteDatabaseInstance db
cursor = db.query(...parameters to get all call logs...);
mListView.setOnItemClickListener(this);
}
public void OnItemClick( // all arguments... )
{
//there is a column name 'NAME' in call log table in database
String name = cursor.getString(cursor.getColumnIndex(Database.NAME))
//here name is obtained of the clicked item.
}
Cursor is a result set. how does the cursor know which item is clicked? What can be the methods implicitly called by cursor that gives it position of clicked item?
If there are any links of similar question then pls provide.
I hope I am able to make you understand the question. Thank you
Try this:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//move cursor to clicked row
cursor.moveToPosition(position);
}
Specifically it is NOT the Cursor that knows who clicked on what. This is actually handled by the Adapter. The adapter is used to group elements together and allow abstraction as such that they can be handled in a uniform way.
Any form of list, always has an adapter, and this is exactly why the adapter works so well. If you look at a Custom Listview with a Custom Adapter, you'll see exactly how this is done.
Example:
http://android.vexedlogic.com/2011/04/02/android-lists-listactivity-and-listview-ii-%E2%80%93-custom-adapter-and-list-item-view/
You should use cursor.moveToposition(position) inside function to get to the position of that clicked item. After that you apply this and when you will click on any item, the cursor will be set on that item and then you can use that particular item for your operation.
mListView..setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,
View view, int position, long id) {
// here position gives the which item is clicked..
}
});
Additionally check this link for ListView ListView and ListActivity
It may help you..

checkbox in List being checked unexpectedly

I have list of checkboxes in list binded by Custom simpleCursorAdapter.
In my custom simpleCursorAdapter, I've overridden newView and bindView with my modifications.
I've managed somehow to do multichoice.
The wierd thing is, after I delete any item from my list, the first item's checkbox is being checked all of a sudden. How does that happen? How can I solve it?
My SimpleCursorAdapter class:
public class MyListCursorAdapter extends SimpleCursorAdapter
{
private Context context;
private int layout;
public MyCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to)
{
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
Cursor c = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
CheckBox chkBoxBtn = (CheckBox) v.findViewById (R.id.deleteTwittChkBox);
if (chkBoxBtn != null)
{
chkBoxBtn.setChecked(false);
}
return v;
}
#Override
public void bindView(View v, Context context, Cursor c)
{
--binding view to my textsview in my items
//now it's the importat part:
CheckBox chkBoxBtn = (CheckBox) v.findViewById(R.id.deleteTwittChkBox);
if (chkBoxBtn != null)
{
chkBoxBtn.setId(Integer.valueOf(c.getString(c
.getColumnIndex(MyUsers.User._ID))));
chkBoxBtn.setOnClickListener(new OnItemClickListener(chkBoxBtn, v));
chkBoxBtn.setChecked(false);
}
}
//i couldnt find another way of doing this, but this is how i set listeners to my checkboxses
static ArrayList<String> checkedItemsList = new ArrayList<String>();
private class OnItemClickListener implements OnClickListener
{
private int mPosition;
private CheckBox chkBox;
OnItemClickListener(CheckBox mChkBox, View v)
{
chkBox = mChkBox;
chkBox.setChecked(false);
}
#Override
public void onClick(View v)
{
if (chkBox.isChecked())
{
checkedItemsList.add(String.valueOf(chkBox.getId()));
}
else
{
checkedItemsList.remove(String.valueOf(chkBox.getId()));
}
}
}
}
Here is the code part from the ListActivity class which describes the button that deletes the checked box items:
OnClickListener btListener = new OnClickListener()
{
public void onClick(View view)
{
// long[] items = listView.getCheckItemIds();
int x = 0;
Uri myUri = Uri
.parse("content://com.idan.datastorageprovider/users");
String where = "_id" + "=?";
//here i am tatking all checkboxes which ive added from the adapter class
ArrayList<String> checkedItemsList = MySimpleCursorAdapter.checkedItemsList;
for (String itemID : checkedItemsList)
{
getContentResolver()
.delete(myUri, where, new String[] { itemID});
checkedItemsList.remove(itemID);
}
}
};
I doubt that SimpleCursorAdapter is the right class to extend here.
Is the "checked" state connected to the data XML in any way? No? So you need your own custom adapter!
Basically all adapters have to implement a way to generate a view from a given element (more precisely an element position!). This will be called at any time where the list wants to display an element. Now, the trick it uses is to re-use formerly created list view elements that cannot be seen on screen any more! Thus: when you scroll your list down and an element disappears at the top, EXACTLY this view object will be re-used for the next appearing item.
So, when this method is called with a given "old" view that should be re-used, all contained elements will have to be set according the elements data. If a checkbox is part of this game, you will have to have a storage for the checked state! It is not sufficient to have a checkbox as there will be less checkbox objects as there are list elements!
SimpleCursorAdapters are there to - yeah - represent SIMPLE things. An XML describing data (images and text, as the documentation states). Because of this simplicity all you have to do here is provide a method to create NEW element view objects - you are not intercepting the re-use process AT ALL! It basically only knows how to put the data into an existing view object - but it is lacking the knowledge of how to handle checked/unchecked boxes!
Your solution: write your own BaseAdapter extension and do what has to be done: implement "getView" (and some other methods like getItem, getItemId and getCount). It's not hard at all!
This API Demo uses a BaseAdapter and the mExpanded state here is basically identical to your checkbox states!
Good luck!
You might need to call notifyDataSetChanged when you modify the data.
The problem is probably that you're calling setChecked from within the onItemClickListener. One hacky way around this is to do the following before and after you call setChecked from within your listener:
chkBox.setClickable(false);
chkBox.setChecked(false);
checkBox.setClickable(true);
This will prevent your onItemClickListener from getting called when you manually call setChecked.

Categories

Resources