无法从网址下载图片

时间:2020-09-04 13:45:17

标签: android android-studio bitmap

我尝试使用android studio中的位图从URL下载图像到图像视图。但是出现未知错误,我无法下载图像。

这是我的代码:

    public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    Button button;

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

        imageView = findViewById(R.id.imageView);
        button = findViewById(R.id.button);
    }

    public void downloadImage(View view) {
        imageDownloader task = new imageDownloader();

        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();
        }
    }

    public class imageDownloader extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... urls) {
            try {

                URL url = new URL(urls[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();
                InputStream in = urlConnection.getInputStream();
                Bitmap myBitmap = BitmapFactory.decodeStream(in);
                return myBitmap;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}

当我尝试在模拟器中下载图像时,什么都没有显示,这是我的日志:

enter image description here

2 个答案:

答案 0 :(得分:0)

为什么不使用滑行?

https://github.com/bumptech/glide

#read the text file into python: 
jobads= pd.read_csv("jobads.txt", header=None)
print(jobadsads)

#create dataframe 
df=pd.DataFrame(jobads, index=None, columns=None)
type(df)
print(df)
#name column to target it for split 
df = df.rename(columns={0:"Job"})
print(df)

#split it into two columns. Problem: I only get the first row.
print(pd.DataFrame(dr.Job.str.split(';',1).tolist(),
                   columns=['ID','AD']))

答案 1 :(得分:0)

最好使用滑行或毕加索 但是如果要使用这个模型 检查一下: 在onPost方法上设置图像背景 初始化图像视图onPre方法 运行任务前检查网络 并为您的活动添加政策