通过 URL 下载图片并在点击按钮时显示在屏幕上

Download image through URL and show it on the Screen when clicked on the button

我正在尝试在单击按钮时在模拟器上显示图像。它是如何工作的,我提供了一个 URL 图像,所以当单击按钮时,相应的图像应该显示在模拟器上,但我在这里没有得到任何图像。

Java代码

package com.example.download;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

    ImageView imageView;

    public void downLoad(View view)
    {

        ImgDownloader task = new ImgDownloader();
        Bitmap myImage;
        try {
            myImage=task.execute("https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png").get();
            imageView.setImageBitmap(myImage);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.i("Button","Pressed");
    }

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

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

    }
    public static class ImgDownloader extends AsyncTask<String, Void, Bitmap>
    {
        @Override
        protected Bitmap doInBackground(String... urls) {
            try {
                URL url= new URL(urls[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                InputStream inputStream = connection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
                return myBitmap;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}

布局

2020-09-09 07:52:03.931 13065-13129/com.example.download W/System.err: java.net.UnknownHostException: Unable to resolve host "upload.wikimedia.org": No address associated with hostname
2020-09-09 07:52:03.932 13065-13129/com.example.download W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:156)
2020-09-09 07:52:03.934 13065-13129/com.example.download W/System.err:     at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
2020-09-09 07:52:03.934 13065-13129/com.example.download W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:1152)
2020-09-09 07:52:03.935 13065-13129/com.example.download W/System.err:     at com.android.okhttp.Dns.lookup(Dns.java:41)
2020-09-09 07:52:03.936 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
2020-09-09 07:52:03.936 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
2020-09-09 07:52:03.938 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
2020-09-09 07:52:03.938 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:176)
2020-09-09 07:52:03.938 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
2020-09-09 07:52:03.939 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
2020-09-09 07:52:03.940 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
2020-09-09 07:52:03.940 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
2020-09-09 07:52:03.941 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
2020-09-09 07:52:03.942 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
2020-09-09 07:52:03.942 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:90)
2020-09-09 07:52:03.943 13065-13129/com.example.download W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:30)
2020-09-09 07:52:03.943 13065-13129/com.example.download W/System.err:     at com.example.download.MainActivity$ImgDownloader.doInBackground(MainActivity.java:55)
2020-09-09 07:52:03.944 13065-13129/com.example.download W/System.err:     at com.example.download.MainActivity$ImgDownloader.doInBackground(MainActivity.java:48)
2020-09-09 07:52:03.946 13065-13129/com.example.download W/System.err:     at android.os.AsyncTask.call(AsyncTask.java:394)
2020-09-09 07:52:03.947 13065-13129/com.example.download W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
2020-09-09 07:52:03.947 13065-13129/com.example.download W/System.err:     at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:305)
2020-09-09 07:52:03.948 13065-13129/com.example.download W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
2020-09-09 07:52:03.949 13065-13129/com.example.download W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
2020-09-09 07:52:03.950 13065-13129/com.example.download W/System.err:     at java.lang.Thread.run(Thread.java:923)
2020-09-09 07:52:03.951 13065-13129/com.example.download W/System.err: Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
2020-09-09 07:52:03.953 13065-13129/com.example.download W/System.err:     at libcore.io.Linux.android_getaddrinfo(Native Method)
2020-09-09 07:52:03.954 13065-13129/com.example.download W/System.err:     at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:73)
2020-09-09 07:52:03.954 13065-13129/com.example.download W/System.err:     at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:202)
2020-09-09 07:52:03.954 13065-13129/com.example.download W/System.err:     at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:73)
2020-09-09 07:52:03.955 13065-13129/com.example.download W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:135)
2020-09-09 07:52:03.956 13065-13129/com.example.download W/System.err:  ... 23 more
2020-09-09 07:52:03.958 13065-13065/com.example.download I/Button: Pressed
2020-09-09 07:52:03.964 13065-13065/com.example.download I/Choreographer: Skipped 1207 frames!  The application may be doing too much work on its main thread.
2020-09-09 07:52:03.988 13065-13117/com.example.download I/OpenGLRenderer: Davey! duration=20137ms; Flags=0, IntendedVsync=18050067477460, Vsync=18070184143322, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=18070186401860, AnimationStart=18070186512760, PerformTraversalsStart=18070187352960, DrawStart=18070187859860, SyncQueued=18070190416860, SyncStart=18070194709860, IssueDrawCommandsStart=18070195078060, SwapBuffers=18070198414760, FrameCompleted=18070209020960, DequeueBufferDuration=1898300, QueueBufferDuration=3621000, GpuCompleted=0, 

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.download">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true"
        android:networkSecurityConfig="@xml/network_security_config">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">secure.example.com</domain>
    </domain-config>
</network-security-config>

XML 文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="match_parent"
            android:layout_height="759dp"
            android:layout_below="@+id/button"
            android:layout_marginTop="-4dp"
            android:layout_marginBottom="5dp" />

        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="downLoad"
            android:text="Button" />
    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

EAI_NODATA (No address associated with hostname)

通常意味着您没有网络访问权限。所以请检查您的 wifi 或网络连接

您的网络似乎不可用。根据this,尝试重新连接wifi连接或重启你的模拟器。