Android code to fetch Image from server and display it in Imageview

后端 未结 4 1521
逝去的感伤
逝去的感伤 2020-12-22 08:11

Hi I know how to fetch an string from jsonobject, but my question is how to fetch an image from Rest api and display it. The image is stored as profile_image in jsonobject

4条回答
  •  天命终不由人
    2020-12-22 08:32

    This can be done using Picasso

    for that add dependancy in build.gradle file of your project

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.0.1'
        compile 'com.android.support:design:23.0.1'
        compile 'com.squareup.picasso:picasso:2.4.0'
    }
    

    and add code in your method as below

    if(object.has("profile_image")) {
        // imageView should be declared in layout xml file with id `imageView`
        ImageView imageView = (ImageView) context.findViewById(R.id.imageView);
        com.squareup.picasso.Picasso.with(context).
            load(object.get("profile_image")).
            placeholder(R.mipmap.ic_launcher).
            into(imageView);
    }
    

    and done.

    NOTE : object.get("profile_image") should return full path of image.

    for e.g. http://www.example.com/images/image1.jpg

    then only it will work.

提交回复
热议问题