vendredi 12 juin 2015

xamarin android ListView with image

Im tring to load data from database and display on a ListView. The list view contains 2 textview and 1 image view. Im using SQlite.net. Where is my databse:

Database

public class contacts
{
    [PrimaryKey, AutoIncrementAttribute, Column("id")]
    public int id {get; set;}
    public string name {get; set;}
    public string number { get; set; }
    public int COrder { get; set; }
    public byte[] photo{ get; set; }
}

And where is my function to fill the listview:

private void refreshListView()
    {           
        var db = new SQLiteConnection (MainActivity._DatabaseConnectString);

        MatrixCursor mMatrixCursor = new MatrixCursor (new String[]{ "_id", "name", "number", "photo" });

        SimpleCursorAdapter adap;

        adap = new SimpleCursorAdapter (
            this,
            Resource.Layout.lv_layout,
            null,
            new String[]{ "name", "number", "photo" },
            new int[]{ Resource.Id.tv_name, Resource.Id.tv_number, Resource.Id.iv_photo }, 0);

        IEnumerable<contacts> table = db.Query<contacts> ("select * from contacts order by COrder");
        foreach (var contact in table) {
            mMatrixCursor.AddRow (new Java.Lang.Object[] {contact.id,
                contact.name, contact.number, BitmapFactory.DecodeByteArray (contact.photo, 0, contact.photo.Length)
            });
        }

        lview.Adapter = adap;
        adap.SwapCursor (mMatrixCursor);
    }

The only problem is the image dont show and I have this error from the output:

[BitmapFactory] Unable to decode stream: java.io.FileNotFoundException: /android.graphics.Bitmap@42087da0: open failed: ENOENT (No such file or directory)
[System.out] resolveUri failed on bad bitmap uri: android.graphics.Bitmap@42087da0

I already done this application with java for android and I fix that problem with the this code but I dont know how to "translate" the code from java to c#.

Where is the java code below the adap:

adap.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int i) {
            if (view.getId() == R.id.iv_photo) {
                byte[] Blobdata = cursor.getBlob(i);

                Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeByteArray(
                        Blobdata, 0, Blobdata.length), 150, 150, false);

                ((ImageView) view).setImageBitmap(bitmap);
                return true;
            } else {
                return false;
            }
        }
    });

Somebody can help me "translate" this code to c#? or use another code. Thanks from the help and sorry my english.

Aucun commentaire:

Enregistrer un commentaire