java Android - 将 ImageView 设置为 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17120230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:03:24  来源:igfitidea点击:

Android - Set ImageView to URL

javaandroidurlbitmapimageview

提问by user222786

I am trying to set an Imageview to a URL.

我正在尝试将 Imageview 设置为 URL。

Below is my code

下面是我的代码

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.getpic);
    ImageView i = (ImageView)findViewById(R.id.ivget);

    URL url;
    try {

        url = new URL("http://0-media-cdn.foolz.us/ffuuka/board/sp/thumb/1359/41/1359419073599s.jpg");
        Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
        i.setImageBitmap(image);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

But whenever I try to open/run the app it crashes, why isnt it working?

但是每当我尝试打开/运行应用程序时它就会崩溃,为什么它不起作用?

06-15 00:37:20.977: E/AndroidRuntime(8579): FATAL EXCEPTION: main
06-15 00:37:20.977: E/AndroidRuntime(8579): java.lang.RuntimeException: Unable to  instantiate activity  ComponentInfo{com.OptimusApps.stayhealthy/com.OptimusApps.stayhealthy.Practice2}:  java.lang.NullPointerException
06-15 00:37:20.977: E/AndroidRuntime(8579):     at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1993)
 06-15 00:37:20.977: E/AndroidRuntime(8579):    at  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at android.app.ActivityThread.access0(ActivityThread.java:132)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at android.os.Looper.loop(Looper.java:137)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at android.app.ActivityThread.main(ActivityThread.java:4575)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at java.lang.reflect.Method.invokeNative(Native Method)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at  java.lang.reflect.Method.invoke(Method.java:511)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at dalvik.system.NativeStart.main(Native Method)
06-15 00:37:20.977: E/AndroidRuntime(8579): Caused by: java.lang.NullPointerException
06-15 00:37:20.977: E/AndroidRuntime(8579):     at android.app.Activity.findViewById(Activity.java:1794)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at com.OptimusApps.stayhealthy.Practice2.<init>(Practice2.java:17)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at java.lang.Class.newInstanceImpl(Native Method)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at java.lang.Class.newInstance(Class.java:1319)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
06-15 00:37:20.977: E/AndroidRuntime(8579):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1984)
06-15 00:37:20.977: E/AndroidRuntime(8579):     ... 11 more

above is the logcat, I am not sure where the error is in it specificaly though..............................................................................................................................................................

上面是 logcat,但我不确定错误具体在哪里...................................... ………………………………………………………………………………………………………………………………………………………… ………………………………………………………………………………………………………………………………………………………… ……………………………………………………………………………………………………………………………………

回答by Raghunandan

You should not do network related operation on the main ui thread.

你不应该在主 ui 线程上做网络相关的操作。

You can findViewById of the current view hierachy set to the activity. check if you have imageview in ivget.xml. Also use a asynctask as below and make a http get request to get the image.

您可以找到设置为活动的当前视图层次结构的ViewById。检查 ivget.xml 中是否有 imageview。还使用如下异步任务并发出 http get 请求以获取图像。

activity_main.xml

活动_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="173dp"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

MainActivity.java

主活动.java

    public class AndroidCustomGalleryActivity extends Activity { 
ImageView iv;
Bitmap image ;
ProgressDialog pd;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    iv = (ImageView) findViewById(R.id.imageView1);
    pd = new ProgressDialog(this);
    pd.setMessage("Loading..");
    new TheTask().execute();    
}
class TheTask extends AsyncTask<Void,Void,Void>
{

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        pd.show();
    }


    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
        try
        {
        //URL url = new URL( "http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png");


        image = downloadBitmap("http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        pd.dismiss();
        if(image!=null)
        {
            iv.setImageBitmap(image);
        }

    }   
}
 private Bitmap downloadBitmap(String url) {
     // initilize the default HTTP client object
     final DefaultHttpClient client = new DefaultHttpClient();

     //forming a HttoGet request 
     final HttpGet getRequest = new HttpGet(url);
     try {

         HttpResponse response = client.execute(getRequest);

         //check 200 OK for success
         final int statusCode = response.getStatusLine().getStatusCode();

         if (statusCode != HttpStatus.SC_OK) {
             Log.w("ImageDownloader", "Error " + statusCode + 
                     " while retrieving bitmap from " + url);
             return null;

         }

         final HttpEntity entity = response.getEntity();
         if (entity != null) {
             InputStream inputStream = null;
             try {
                 // getting contents from the stream 
                 inputStream = entity.getContent();

                 // decoding stream data back into image Bitmap that android understands
                 image = BitmapFactory.decodeStream(inputStream);


             } finally {
                 if (inputStream != null) {
                     inputStream.close();
                 }
                 entity.consumeContent();
             }
         }
     } catch (Exception e) {
         // You Could provide a more explicit error message for IOException
         getRequest.abort();
         Log.e("ImageDownloader", "Something went wrong while" +
                 " retrieving bitmap from " + url + e.toString());
     } 

     return image;
 }
}

enter image description here

在此处输入图片说明

回答by Paresh Mayani

android.app.Activity.findViewById(Activity.java:1794)

=> It says you haven't initialized your ImageView i.e. "i" in your code.

=> 它说你没有在你的代码中初始化你的 ImageView 即“i”。

ImageView i = (ImageView) findViewById(R.id.myImageViewInXML);

回答by Tanmay Ranjan

Use Glide

使用滑行

Implementation 'com.github.bumptech.glide:glide:4.2.0'

执行 'com.github.bumptech.glide:glide:4.2.0'

Or

或者

in java

在 Java 中

Glide.with(getApplicationContext())
                .load(image)
                .into(imageView);