Image from Url in ImageView

atorres86atorres86 Alberto TorresUSMember
edited May 2013 in Xamarin.Android

Hi i'm trying to display an image from an URL to an ImageView. but when i run the app i get a java error.

this is the code i'm using:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Net;
using Android.Graphics;
using Java.IO;
using Android.Graphics.Drawables;
using Android.Util;
using System.Net;
using System.IO;
using Com.Loopj.Android.Image; 


[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
namespace android1
{
     [Activity(Theme = "@android:style/Theme.NoTitleBar")]
    public class Inicio : Activity
    {
        private String path = "http://peytonhamil.com/suns.jpg";
        private ImageView imageView;
         protected override void OnCreate(Bundle bundle)
         {
             base.OnCreate(bundle);
             SetContentView(Resource.Layout.Main);
             int loader = Resource.Drawable.loading_moon;
             ImageView imagen = FindViewById<ImageView>(Resource.Id.image1);
             Android.Net.Uri url = Android.Net.Uri.Parse("http://xamarin.com/resources/design/home/devices.png");
             imagen.SetImageURI(url);

         }

    }
}

any help will be appreciated.

Best Answer

Answers

  • StevenTheEvenStevenTheEven Michael Andersson SEMember ✭✭✭

    I can't help you but i think you should at least provide the exact error you get if ppl should be able to help you.

  • atorres86atorres86 Alberto Torres USMember

    this is the error i get.

    Unhandled Exception:

    System.NullReferenceException: Object reference not set to an instance of an object

    and is in this line.

    imagen.SetImageURI(url);

  • JonathanPryorJonathanPryor Jonathan Pryor USXamarin Team Xamurai

    imagen is null, presumably because FindViewById<ImageView>(Resource.Id.image1) is returning null.

    What are the contents of Resources\Layout\Main.axml?

  • atorres86atorres86 Alberto Torres USMember
    edited May 2013

    this is the axml content

    <LinearLayout
        android:orientation="vertical"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout3">
        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/image1" />
    </LinearLayout>
    
  • atorres86atorres86 Alberto Torres USMember
    edited May 2013
    <LinearLayout
        android:orientation="vertical"
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/linearLayout3">
        <ImageView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/image1" />
    </LinearLayout>
    
  • atorres86atorres86 Alberto Torres USMember
       <LinearLayout
            android:orientation="vertical"
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayout3">
            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/image1" />
        </LinearLayout>
    
  • atorres86atorres86 Alberto Torres USMember

    ??

  • atorres86atorres86 Alberto Torres USMember

    sorry but i'm still having the same error... :s

  • ChrisHonselaarChrisHonselaar Chris Honselaar NLMember, Beta ✭✭✭

    You never confirmed if imagen is null. Is that the case? That would at least get us started in the right direction.

  • atorres86atorres86 Alberto Torres USMember

    this the Inicio.axml code:

     <LinearLayout
            android:orientation="vertical"
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayout3">
            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:id="@+id/imagenejemplo" />
        </LinearLayout>
    

    and this is the Inicio.cs Activity code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using Android.App;
    using Android.Content;
    using Android.OS;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Java.Net;
    using Android.Graphics;
    using Java.IO;
    using Android.Graphics.Drawables;
    using Android.Util;
    using System.Net;
    using System.IO;
    using Com.Loopj.Android.Image;

    [assembly: UsesPermission(Android.Manifest.Permission.Internet)]
    namespace android1
    {
    [Activity(Theme = "@android:style/Theme.NoTitleBar")]
    public class Inicio : Activity
    {
    ImageView imagen = null;
    protected override void OnCreate(Bundle bundle)
    {
    base.OnCreate(bundle);
    SetContentView(Resource.Layout.Main);
    imagen = FindViewById(Resource.Id.imagenejemplo);

            var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
             imagen.SetImageBitmap(imageBitmap);
         }
    
          private Bitmap GetImageBitmapFromUrl(string url)
         {
             Bitmap imageBitmap = null;
    
             using (var webClient = new WebClient())
             {
                 var imageBytes = webClient.DownloadData(url);
                 if (imageBytes != null && imageBytes.Length > 0)
                 {
                     imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
                 }
             }
    
             return imageBitmap;
         }
    }
    

    }

    if need anything else let me know

  • ChrisHonselaarChrisHonselaar Chris Honselaar NLMember, Beta ✭✭✭

    Works fine for me. The only thing I can think of is that your .axml file is missing an xml header element, and the xmlns:android="http://schemas.android.com/apk/res/android" attribute in the root element. In fact, you should be getting a build error?

  • atorres86atorres86 Alberto Torres USMember

    thanks Rmacias that was the problem, i did not pay attention to the setcontentview

  • tinku.efernstinku.eferns Tinku USMember
    edited March 2014

    Hi Ruben,

    I tried implementing the same but the image was not getting bound to Imageview.
    When I tried to debug, I found out these lines in console when
    imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length); was getting executed,
    [JpgDecPipe] JpgDecPipe::JpgDecPipe [JpgDecPipe] ::[setScalerType] set fScaleType 2->2, L:296!! [JpgDecPipe] ::[LOCK] lock, islock 0!! [JpgDecComp] JpgDecComp::JpgDecComp [JpgDecComp] lock!! [ImgScaler] ImgCdpPipe::ImgCdpPipe [mHalJpgDec] mHalJpgDec:: parser lock success,fg(1),SWS 0x25800, L:175!! [mHalJpgParser] enter Driver parse !!! [JpegDecDriver] ::[PARSE] nusupported format, Prog 1, fmt 1a4!!
    Here is my full code,

    `class NoteAdapter : ArrayAdapter
    {
    List item;
    Context context;

        public NoteAdapter(Context Context, int NoteListRowId, List<Story> Items) : base(Context, NoteListRowId, Items)
        {
            this.item = Items;
        }
    
        public override int Count 
        {
            get 
            {
                return item.Count;
            }
        }
    
        public override View GetView(int position, View convertView, ViewGroup parent)  
        {  
            View v = convertView;
            if (v == null) 
            {
                LayoutInflater inflater = (LayoutInflater)Context.GetSystemService (Context.LayoutInflaterService);
                v = inflater.Inflate (Resource.Layout.CustomView, parent, false);
            }
    
            v.FindViewById<TextView>(Resource.Id.Name).Text = item[position].Name;
            v.FindViewById<TextView>(Resource.Id.Message).Text = item[position].Message;
            v.FindViewById<TextView>(Resource.Id.TimeAgo).Text = item[position].TimeAfter;
    
            //UrlImageViewHelper.UrlImageViewHelper.SetUrlDrawable(v.FindViewById<ImageView>(Resource.Id.Picture),item[position].PictureUrl, Resource.Drawable.loading);
            var imageBitmap = GetImageBitmapFromUrl("https://fbexternal-a.akamaihd.net/app_full_proxy.php?app=2231777543&v=1&size=z&cksum=76e99f14f3ceda38069c431a48c2acdb&src=https%3A%2F%2Fpbs.twimg.com%2Fmedia%2FBjy6cH8IgAAAquM.jpg");
            v.FindViewById<ImageView> (Resource.Id.Picture).SetImageBitmap(imageBitmap);
            return v;
    
        }
        private Bitmap GetImageBitmapFromUrl(string url)
        {
            Bitmap imageBitmap = null;
            if(!(url=="null"))
            using (var webClient = new WebClient())
            {
                var imageBytes = webClient.DownloadData(url);
                if (imageBytes != null && imageBytes.Length > 0)
                {
                    imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
                }
            }
    
            return imageBitmap;
        }
    }`
    

    What might be causing this issue ??

    Thanks in advance

  • tinku.efernstinku.eferns Tinku USMember

    Here is my customlayout for ListView

    <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="8dp"> <LinearLayout android:id="@+id/Text" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="10dip"> <LinearLayout android:id="@+id/Text" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="10dip"> <TextView android:id="@+id/Name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FF7F3300" android:textSize="20dip" android:textStyle="italic" /> <TextView android:id="@+id/TimeAgo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#FF7F3300" android:textSize="20dip" android:textStyle="italic" android:layout_alignParentRight="true" /> </LinearLayout> <LinearLayout android:id="@+id/Text" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="10dip"> <TextView android:id="@+id/Message" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14dip" android:textColor="#FF267F00" android:paddingLeft="100dip" /> <ImageView android:id="@+id/Picture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:layout_alignParentRight="true" /> </LinearLayout> </LinearLayout> </RelativeLayout>

    And Main Layout

    <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@+id/List" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>

  • KeyzerSKeyzerS Tim Peters NOMember ✭✭

    Just wanted to say thanks for the Bitmap stuff. Helped me a lot!

  • MaulikShah.4827MaulikShah.4827 Maulik Shah USMember

    private Bitmap GetImageBitmapFromUrl(string url)
    {
    Bitmap imageBitmap = null;

            if (!(url == "nul"))
            using (var webClient = new webClient())
            {
                var imageBytes  = webClient.DownloadData(url);
                 if (imageBytes != null && imageBytes.Length > 0)
                {
                imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
                }
    
            }
            return imageBitmap;
    
        }
    

    webClient error type or namespace name 'webClient'
    any hev a solution

    thease using xamarin android using to visual studio 2013 community

  • rmaciasrmacias Ruben Macias USBeta, University ✭✭✭✭✭
    edited September 2015

    new webClient()

    You mis-typed "new webClient()". It should be new WebClient()

    Also, this thread is quite old, and was before async/await and full HttpClient support. I would recommend now using async/await and HttpClient. If you're doing this in a PCL, then you'll need to install the Microsoft Http Client Nuget Package.

    private async Task<Bitmap> GetImageBitmapFromUrlAsync(string url)
    {
         Bitmap imageBitmap = null;
    
         using (var httpClient = new HttpClient())
         {
              var imageBytes = await httpClient.GetByteArrayAsync(url);
              if (imageBytes != null && imageBytes.Length > 0)
              {
                   imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
              }
         }
    
         return imageBitmap;
    }
    
  • JSparrowJSparrow Bikash USMember

    which package is needed for the below method in xamrin.android ???

    GetImageBitmapFromUrl()

  • IgnacioCastilloIgnacioCastillo Ignacio Castillo USMember

    @JSparrow said:
    which package is needed for the below method in xamrin.android ???

    GetImageBitmapFromUrl()

    Great!!, thaks a lot c:

  • RxhnsRxhns Ronald Urbina USMember

    @rmacias said:
    It looks like you're loading "Main.axml" and not "Inicio.axml" from your activity. In your OnCreate() method, you need to load that view by calling SetContentView(Resource.Layout.Inicio). That would explain why imagen is returning null.

    void OnCreate(Bundle bundle) 
    { 
      base.OnCreate(bundle); 
      SetContentView(Resource.Layout.Inicio);  //Load correct view here
      imagen = FindViewById(Resource.Id.imagenejemplo);
    
      var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
      imagen.SetImageBitmap(imageBitmap);
    }
    

    This method lags my listview I'm now using this component and is more faster
    https://components.xamarin.com/gettingstarted/urlimageviewhelper

Sign In or Register to comment.