Load image from URL

ぃ、小莉子 提交于 2019-12-08 04:44:53

问题


I've searched and tried a couple different methods. I am coming up short on both. This is my current method:

package com.dop.mobilevforum;

import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.VideoView;

public class Vforum extends Activity
{
    private String imgPath = "http://mysite.com/mv/vfdemo1/slides/slide1.jpg";

    private ImageView slideHolder;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.vforum);

        slideHolder = (ImageView) findViewById(R.id.slideHolder);

        Drawable drawable = LoadImageFromWebOperations(imgPath);
        slideHolder.setImageDrawable(drawable);
    }

    private Drawable LoadImageFromWebOperations(String url)
    {
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        } 
        catch (Exception e)
        {
            Log.w("LoadImageFromWebOperations",e.toString());
            return null;
        }
    }
}

the LoadImageFromWebOperations method is returning a bitmap, so I know that part is working. It is the slideHolder.setImageDrawable(drawable); that I think it failing. This is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/mobile_vforum_bg">
    <ImageView 
        android:id="@+id/slideHolder"
        android:layout_width="320px" 
        android:layout_height="240px">
    </ImageView>
</FrameLayout>

any ideas? I just get a black screen, no errors.


回答1:


Your best bet is using a WebView, but if you really want to do it this way don't use setImageDrawable. You should use setImageBitmap. If your LoadImageFromWebOperations returns a Bitmap then you shouldn't change anything, but the function you are using and it should work smoothly.




回答2:


Your code work, my dear friend your url don't work http://mysite.com/mv/vfdemo1/slides/slide1.jpg.

You can use this it works 100%, but your code also works

URL url = new URL("http://variable3.com/files/images/email-sig.jpg");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
slideHolder.setImageBitmap(bmp);


来源:https://stackoverflow.com/questions/6022908/load-image-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!