簡體   English   中英

如何使用 ImageView 將現有 sqlite 數據庫中的數據填充到 ListView

[英]How to populate data from existing sqlite database to ListView with ImageView

我正在尋找一種方法來將現有 sqlite 數據庫中的數據顯示到 ListView 中,該數據庫是我之前使用“DB Browser”創建的。 在數據庫中有一個徽標/圖像 (Blob) 列,我想將其輸入到 ListView 中。 我怎樣才能做到這一點?

我從網上得到了下面的代碼,但不幸的是這種方法不能顯示圖像,只能在一行中顯示兩行。

這是我的 main_activity 更改為 Home_Act..

    public class Home_Act extends AppCompatActivity {

        static final String DBNAME = "testing.db";
        static final String DBASSETPATH = "databases/" + DBNAME;
        static final String CHANNELTABLE = "Channel_Info";
        static final String KEY_NO = "No";
        static final String KEY_NAME = "Name";
        static final String KEY_CATEGORY = "Category";
        static final String KEY_LOGO = "Logo";

        ListView channelList;
        SQLiteDatabase mDB;
        SimpleCursorAdapter mSCA;
        Cursor mCsr;

        @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.act_home);

    channelList = this.findViewById(R.id.channelList);
    mDB = openDB();



    if (mDB != null) {
        mCsr = mDB.query(CHANNELTABLE,
                new String[]{KEY_NO + " AS _id",
                        KEY_NAME, KEY_CATEGORY, KEY_LOGO
                },
                null,null,null,null,null);
        mSCA = new SimpleCursorAdapter(this,R.layout.mylist,mCsr,
                new String[]{KEY_NAME, KEY_CATEGORY, KEY_LOGO},
                new int[]{R.id.item, R.id.textView1, R.id.icon},0);

        mSCA.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
            // Binds the Cursor column defined by the specified index to the specified view
            public boolean setViewValue(View view, Cursor cursor, int columnIndex){
                if(view.getId() == R.id.icon){
                    //...
                    String channelName = cursor.getString(3);
                    Home_Act.this.getResources();
                    int resID = getResources().getIdentifier(channelName, "drawable", getPackageName());

                    //Option 1
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
                        ((ImageView)view).setImageDrawable(getResources().getDrawable(resID, getApplicationContext().getTheme()));
                    } else {
                        ((ImageView)view).setImageDrawable(getResources().getDrawable(resID));
                    }

                    //Option 2
                    //((ImageView)view).setImageDrawable(getResources().getDrawable(resID));

                    return true; //true because the data was bound to the view
                }
                return false;

            }
        });

        channelList.setAdapter(mSCA);
    } else {
        Toast.makeText(this,"Unable to open Database.",Toast.LENGTH_LONG);
    }

    channelList.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // TODO Auto-generated method stub
            String Slecteditem = itemname[+position];
            channelName = Slecteditem;
            OpenDialog();
            //Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();

        }
    });
}

private SQLiteDatabase openDB() {
    String dbpath = this.getDatabasePath(DBNAME).getPath();
    if (this.getDatabasePath(DBNAME).exists()) {
        Log.d("OPENDB","Opening already existing Database");
        return SQLiteDatabase.openDatabase(dbpath,null,SQLiteDatabase.OPEN_READWRITE);
    }
    InputStream is;
    byte[] buffer;
    FileOutputStream db;
    try {
        is =  this.getAssets().open(DBASSETPATH);
        buffer = new byte[is.available()];
        is.read(buffer);
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
        Log.d("OPENDB","Unable to locate or buffer input from assets " + DBASSETPATH);
        return null;
    }
    // Just in case the databases directory doesn't exist create it.
    File dbmkdir = (this.getDatabasePath(DBNAME)).getParentFile();
    dbmkdir.mkdirs();
    try {
        db = new FileOutputStream(this.getDatabasePath(DBNAME).getPath());
    } catch (Exception e) {
        e.printStackTrace();
        Log.d("OPENDB","Unable to create outputstream for DB at path " + dbpath);
        try {
            is.close();
        } catch (Exception e2) {
        }
        return null;
    }
    try {
        db.write(buffer);
        db.flush();
        db.close();
        is.close();
    } catch (Exception e) {
        Log.d("OPENDB","Failed to copy asset to DB");
        e.printStackTrace();
        return null;
    }
    return SQLiteDatabase.openDatabase(dbpath,null,SQLiteDatabase.OPEN_READWRITE);
}

上面的代碼僅在 1 行中顯示 2 行,我想在左側包含圖像。

這是上面的代碼,圖像沒有顯示,也沒有錯誤。

在此處輸入圖像描述

這就是我想要的。

在此處輸入圖像描述

編輯:

現在它正在按我的意願工作。 第一,您必須擁有自己的布局,其中包括 2 個 TextView 和 1 個 ImageView。 用.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="100dp"
        android:layout_height="60dp"
        android:padding="5dp" />

    <LinearLayout android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp"
            android:padding="2dp"
            android:textColor="#33CC33" />
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView"
            android:layout_marginLeft="10dp"/>
    </LinearLayout>
</LinearLayout>

第二,按照上面的代碼。

SimpleCursorAdapter不支持圖像to 在你的代碼中

new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, mCsr,
                    new String[]{KEY_NAME, KEY_CATEGORY, KEY_LOGO},
                    new int[]{android.R.id.text1, android.R.id.text2}, 0);

您將 3 列傳遞給 2 個文本視圖,這些文本視圖毫無例外地顯示在 UI 中。 如果要顯示圖像 + 文本視圖,則需要創建自己的自定義適配器。

或者嘗試如下設置:

mSCA.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
   /** Binds the Cursor column defined by the specified index to the specified view */
   public boolean setViewValue(View view, Cursor cursor, int columnIndex){
       if(view.getId() == R.id.your_image_view_id){
           String yourImageNameFromDb = cursor.getString(2);
           int resID = getResources().getIdentifier(yourImageNameFromDb , "drawable", getPackageName());

          ((ImageView)view).setImageDrawable(getResources().getDrawable(resID));
           return true; //true because the data was bound to the view
       }
       return false;
   }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM