从SQLite数据库在ListView中显示图像

时间:2011-06-27 16:51:28

标签: android sqlite android-listview android-imageview

此刻我有点卡住了。我知道有类似的问题,但我找不到任何有帮助的东西。

我正在尝试从我的Android应用程序内部的数据库中获取和图像显示在ListView中。我有一个141行的数据库,每行标记为1,2或3.我需要一个不同的png图像(保存在我的res / drawable文件夹中)来显示取决于1,2或3.这是我的当前查询。任何的建议都受欢迎。我意识到可能有更好的方式来显示我需要的信息。

   public void whosnext(View view) {
    // || is the concatenation operation in SQLite
    cursor = db.rawQuery("SELECT * FROM eventsv1 WHERE start_time > (DATETIME('now')) AND title LIKE ? ORDER BY date ASC, time DESC", 
                    new String[]{"%" + searchText.getText().toString() + "%"});
    adapter = new SimpleCursorAdapter(
            this, 
            R.layout.artist_list_item, 
            cursor, 
            new String[] {"title", "time", "date", "title3", "style"}, 
            new int[] {R.id.title, R.id.time, R.id.date, R.id.title3, R.id.style});
    setListAdapter(adapter);
}

2 个答案:

答案 0 :(得分:1)

我会写一个自定义的CursorAdapter

public class WhosNextAdapter extends CursorAdapter
{
    public WhosNextAdapter(Context context, Cursor cursor, boolean autoRequery) {
        super(context, cursor, autoRequery);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        //This is were you would check your cursor for style (I think that is 1,2,3 your column)
        int style = cursor.getInt(cursor.getColumnIndex("style"));

        ImageView img = (ImageView) view.findViewById(R.id.yourImageViewId);

        switch (style) {
            case 1:
                img.setImageResource(R.drawable.yourImageForStyle1);

            break;
            case 2:
                img.setImageResource(R.drawable.yourImageForStyle2);

            break;

//etc.
        }
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        //Inflate layout R.layout.artist_list_item

        //Call bindView passing inflated layout, context, and cursor

        //return layout
    }
}

答案 1 :(得分:0)

您肯定需要扩展SimpleCursorAdapter,如果您的项目布局足够简单,您唯一需要做的就是覆盖setViewImage()方法,只需从数据库中转换提供的值并调用{ setImageResource()对象上的{1}}方法。那么您就不必多次替换附加的代码。

ImageView
相关问题