MSepehr
MSepehr

Reputation: 970

Use generic class as method input

I have a iterative code like below with is used in different place of my project:

            List<NewsItem> thisitem = Select.from(NewsItem.class).where(Condition.prop("_id").eq(item.get_id())).list();
            if (thisitem.size() > 0) {
                thisitem.get(0).delete();
                image_bookmark.setImageResource(R.drawable.ic_bookmark_normal);

            } else {
                item.save();
                image_bookmark.setImageResource(R.drawable.ic_bookmarkfill);
            }

I want to write a method witch contain above code ,but worked for every object of class witch extend SugarOrmItem class . i write the below but apparently it's not true:

public  static void  insert_bookmark(String prop,SugarOrmItem record ,ImageView imageView)
{
    List<SugarOrmItem> thisitem = Select.from(SugarOrmItem.class).where(Condition.prop(prop).eq(record.get_id())).list();
    if (thisitem.size() > 0) {
        thisitem.get(0).delete();
        imageView.setImageResource(R.drawable.ic_bookmark_normal);

    } else {

        imageView.setImageResource(R.drawable.ic_bookmarkfill);
    }
}

what should i do?

Edit:

this is my SugarItem class:

   import com.orm.SugarRecord;

public abstract class SugarOrmItem extends SugarRecord {
    public abstract  int  get_id();
}

Upvotes: 0

Views: 618

Answers (1)

Stephen C
Stephen C

Reputation: 718788

I think it needs to be this:

public static <T extends SugarOrmItem> void  insert_bookmark(
    String prop, T record, ImageView imageView, Class<T> clazz)
{
    List<T> thisitem = Select.from(clazz).
            where(Condition.prop(prop).eq(record.get_id())).list();
    if (thisitem.size() > 0) {
        thisitem.get(0).delete();
        imageView.setImageResource(R.drawable.ic_bookmark_normal);
    } else {
        imageView.setImageResource(R.drawable.ic_bookmarkfill);
    }
}

Upvotes: 2

Related Questions