以编程方式创建ImageView并从URL加载其内容

时间:2013-06-02 13:04:27

标签: android imageview

我有一个简单的LinearLayout,上面有Button,我想在按下按钮时创建一个图像并从URL加载其内容。

我创建了AsyncTask来执行此操作,但是当我按下按钮时程序崩溃。

这是我的代码:

package com.example.image;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

    Button testButton;
    LinearLayout layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        testButton = (Button) findViewById(R.id.button1);
        layout = (LinearLayout) findViewById(R.id.LinearLayout1);

        testButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                new GetData().execute();
            }

        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    class GetData extends AsyncTask<String, Void, String> {

        Bitmap bitmap;
        ImageView image = new ImageView(MainActivity.this);

        @Override
        protected void onPreExecute() {
        };

        @Override
        protected String doInBackground(String... params) {
            try {
                URL url = new URL("http://www.android.com/images/logo.png");
                Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            image.setImageBitmap(bitmap);
            layout.addView(image);
        }
    }

}

这里是logcat:

06-02 12:58:57.880: E/Trace(1572): error opening trace file: No such file or directory (2)
06-02 12:58:58.580: D/gralloc_goldfish(1572): Emulator without GPU emulation detected.
06-02 12:59:02.331: W/dalvikvm(1572): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
06-02 12:59:02.401: E/AndroidRuntime(1572): FATAL EXCEPTION: AsyncTask #1
06-02 12:59:02.401: E/AndroidRuntime(1572): java.lang.RuntimeException: An error occured while executing doInBackground()
06-02 12:59:02.401: E/AndroidRuntime(1572):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.lang.Thread.run(Thread.java:856)
06-02 12:59:02.401: E/AndroidRuntime(1572): Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at com.example.image.MainActivity$GetData.doInBackground(MainActivity.java:63)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at com.example.image.MainActivity$GetData.doInBackground(MainActivity.java:1)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
06-02 12:59:02.401: E/AndroidRuntime(1572):     ... 5 more
06-02 12:59:02.401: E/AndroidRuntime(1572): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.io.Posix.getaddrinfo(Native Method)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
06-02 12:59:02.401: E/AndroidRuntime(1572):     at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
06-02 12:59:02.401: E/AndroidRuntime(1572):     ... 22 more
06-02 12:59:02.401: E/AndroidRuntime(1572): Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
06-02 12:59:02.401: E/AndroidRuntime(1572):     ... 25 more

3 个答案:

答案 0 :(得分:2)

在日志中:

  

SecurityException:Permission denied(缺少INTERNET权限?)

表示您忘记添加INTERNET权限AndroidManifest。将其添加为:

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

答案 1 :(得分:0)

尝试在Android清单中添加权限。

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

答案 2 :(得分:0)

删除位图

你为那个

创建了全局变量
     Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());

只写这个

     bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());