gpt4 book ai didi

android - 如何从我的 doInBackground 任务中获取返回值?

转载 作者:行者123 更新时间:2023-11-29 14:35:37 25 4
gpt4 key购买 nike

我是 android studio 的新手,我正在尝试为我的网络操作执行 AsyncTask。

问题是从它获取返回变量,以便能够在 imageview 中设置图像。 imgDisplay.setImageBitmap(var)

public class ZoomActivity  extends Activity {


@SuppressLint("NewApi")



@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_zoom);

Intent intent = getIntent();
String url2 = intent.getStringExtra("image");


ImageView imgDisplay;
Button btnClose;


imgDisplay = (ImageView) findViewById(R.id.imgDisplay);
btnClose = (Button) findViewById(R.id.btnClose);


//Bitmap var = return of doInBackground??????????
imgDisplay.setImageBitmap(var);


btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ZoomActivity.this.finish();
}
});


}

private class MyTask extends AsyncTask<String, Integer, String> {

@Override
protected String doInBackground(String... Params) {
String myString = Params[0];
try {
URL url = new URL(URL???); //how to pass url2 var here?
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap; ??????????
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

}

有什么例子吗?

最佳答案

首先,声明这个异步任务类:

class MyTask extends AsyncTask<String,Void,Bitmap>{

@Override
protected Bitmap doInBackground(String... strings) {
String myString = Params[0];
try {
URL url = new URL(myString);
Bitmap myBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return null;
}

@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imgDisplay.setImageBitmap(bitmap);
}
}

您的 zoomActivity 更改为:

public class ZoomActivity  extends Activity {
ImageView imgDisplay;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_zoom);

Intent intent = getIntent();
String url2 = intent.getStringExtra("image");



Button btnClose;


imgDisplay = (ImageView) findViewById(R.id.imgDisplay);
btnClose = (Button) findViewById(R.id.btnClose);


//call asynctask
new MyTask().execute(url2);


btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ZoomActivity.this.finish();
}
});


}

希望这能行得通

关于android - 如何从我的 doInBackground 任务中获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42514461/

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