2

我正在尝试构建一个要在其中显示一些图像的应用程序。

在真正开始之前,我已经遇到了一个问题:我无法让 imageview 从 URL 加载图像......

我知道这是本主题中关于 SO 的最常见问题之一,下面我有一些我从中摘录的代码:

https://stackoverflow.com/a/12173580

所以,这是我的整个 MainActivity:

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Bitmap bitmap = DownloadImage("http://4.bp.blogspot.com/-w7q2YocdYpY/UCeb6SCfGoI/AAAAAAAAAWY/nsXfzrGQjyA/s1600/Yahoo+Messenger.png");
        ImageView img = (ImageView) findViewById(R.id.imageView1);
        img.setImageBitmap(bitmap);
    }

    private InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection))
            throw new IOException("Not an HTTP connection");

        try {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        } catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }

    private Bitmap DownloadImage(String URL) {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return bitmap;
    }
    
 
}

我有:

 <uses-permission android:name="android.permission.INTERNET" />

我检查了链接,更改了几次,检查了我的互联网连接......我只有一个空白屏幕。一点反应都没有。

我想我错过了一些非常基本的东西,我需要任何其他许可吗?

你能看出什么不对吗?

编辑

使用毕加索库:

小代码:

 ImageView imgView =(ImageView)findViewById(R.id.imageView1);
    
        Picasso.with(this).load("http://i.imgur.com/DvpvklR.png").into(imgView);

大型 Logcat 错误,应用程序在启动时崩溃。

08-19 00:29:56.970: E/AndroidRuntime(4731): FATAL EXCEPTION: main
08-19 00:29:56.970: E/AndroidRuntime(4731): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampl.aaa/com.exampl.aaa.MainActivity}: java.lang.IllegalArgumentException: Target must not be null.
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2077)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.app.ActivityThread.access$600(ActivityThread.java:134)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.os.Looper.loop(Looper.java:154)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.app.ActivityThread.main(ActivityThread.java:4624)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at java.lang.reflect.Method.invokeNative(Native Method)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at java.lang.reflect.Method.invoke(Method.java:511)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at dalvik.system.NativeStart.main(Native Method)
08-19 00:29:56.970: E/AndroidRuntime(4731): Caused by: java.lang.IllegalArgumentException: Target must not be null.
08-19 00:29:56.970: E/AndroidRuntime(4731):     at com.squareup.picasso.RequestBuilder.into(RequestBuilder.java:317)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at com.exampl.aaa.MainActivity.onCreate(MainActivity.java:33)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.app.Activity.performCreate(Activity.java:4479)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
08-19 00:29:56.970: E/AndroidRuntime(4731):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2041)
08-19 00:29:56.970: E/AndroidRuntime(4731):     ... 11 more

什么目标不能为空?...请帮助:)

EDIT2 忘记之前的编辑。我没有 setContentView(R.layout.main);

-.- .... 另一方面,Tasomaniac 的回答效果很好:刚刚添加了毕加索罐子和:

 ImageView imgView =(ImageView)findViewById(R.id.imageView1);

Picasso.with(this).load("http://i.imgur.com/DvpvklR.png").into(imgView);

不需要 Asynctask 或复杂的废话。

谢谢你 !

4

4 回答 4

3

使用 Square Inc. 的 Picasso 库。它需要以下 1 行代码,仅此而已。

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

https://github.com/square/picasso/

于 2013-08-18T18:32:59.747 回答
1

我建议使用以下库,它负责图像加载/缓存等等,它只是让你的生活更轻松;-)

https://code.google.com/p/android-query/#Image_Loading

//fetch and set the image from internet, cache with file and memory 
aq.id(R.id.image1).image("http://www.vikispot.com/z/images/vikispot/android-w.png"); 

特征:

  • 简单的
  • 内存和文件缓存
  • 下采样
  • 可缩放(Web 视图)
  • 后备图像
  • 预加载
  • 动画
  • 动态纵横比
  • 避免重复的同时提取
  • 自定义回调
于 2013-08-18T18:56:04.710 回答
0

我也有这个权限,不确定是否有必要但值得一试:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

我不确定你的问题是什么,但这是我的工作代码。我将不得不检查这些库。

private Bitmap getBitmapFromURL(String str)
{
    Bitmap bmp = null;
    HttpURLConnection connection = null;

    try
    {
        URL url = new URL(str);
        connection = openConnectionWithTimeout(url);
        BitmapFactory.Options opt = new Options();
        // opt.inPurgeable=true;
        opt.inSampleSize = 6;
        bmp = BitmapFactory.decodeStream(connection.getInputStream(), null, opt);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (connection != null)
            connection.disconnect();
    }
    return bmp;
}

public static HttpURLConnection openConnectionWithTimeout(URL url) throws IOException
{
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setConnectTimeout(MAX_TIME);
    connection.setReadTimeout(MAX_TIME);
    return connection;
}
于 2013-08-18T18:38:53.443 回答
0

在不使用第三方库的情况下,您可以这样做:

private Bitmap getBitmap(String url) {
            try{
                HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
                con.setDoInput(true);
                con.connect();
                InputStream input = con.getInputStream();
                Bitmap bmp = BitmapFactory.decodeStream(input);
                input.close();
                return bmp;
            }catch(Exception e){
                Log.v("SHOW", e.getMessage());
                return null;
            }
        }
于 2013-08-18T18:39:34.343 回答