gpt4 book ai didi

java - 类之间丢失数据

转载 作者:太空宇宙 更新时间:2023-11-04 14:35:54 25 4
gpt4 key购买 nike

我有基本的下载器类我也在那里下载和解码位图。但如果我尝试从此类中解码,我会得到我的位图= null。

public void add_item(String _txt, String _url) {
try {
Downloader dw = new Downloader(_url, context);
InputStream s = dw.execute().get();
Bitmap b = BitmapFactory.decodeStream(s); // <<<<<< bitmap is null
bmp.add(b);
} catch (ExecutionException e) { Toast.makeText(this.context, "Ошибка загрузки картинки", Toast.LENGTH_SHORT).show(); }
catch (InterruptedException e) { Toast.makeText(this.context, "Ошибка загрузки картинки", Toast.LENGTH_SHORT).show(); }
}

下载器.java

package com.example.john.weather;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.Toast;

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

public class Downloader extends AsyncTask<Void, Void, InputStream> {

String url;
Context mContext;

public Downloader(String _url, Context _context){
this.url = _url;
this.mContext = _context;
}

@Override
protected InputStream doInBackground(Void... params) {
InputStream s;
try{
s = download(this.url);
//Bitmap b = BitmapFactory.decodeStream(s); // <<<<<< Bitmap is good
return s;
}
catch (MalformedURLException e) {
Toast.makeText(mContext, "Ошибка загрузки "+url, Toast.LENGTH_SHORT).show();
return null; }
catch (IOException e){
Toast.makeText(mContext, "Ошибка загрузки "+url, Toast.LENGTH_SHORT).show();
return null;
}
}

private InputStream download(String url) throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
InputStream input = connection.getInputStream();

return input;
}

}

我有基本的下载器类我也在那里下载和解码位图。但如果我尝试从此类中解码,我会得到我的位图= null。

最佳答案

问题很可能出在 download() 方法中的 Downloader 类中。您需要先加载流的内容,然后再将执行转移到另一个线程(在本例中是主线程)

关于java - 类之间丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25583596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com