我想通过传递网址加载多个图片。与本教程不同http://www.learn2crack.com/2014/06/android-load-image-from-internet.html 其中只下载一个图像并使用img.setImageBitmap(image)查看;我的问题是如何将url发送到一个方法来加载该URL的图像,该方法返回一个图像,然后我在imageview中显示它。然后我将一些其他网址传递给它并获得响应的图像,并将其显示在其他图像视图中。
答案 0 :(得分:2)
好的,假设您出于某种原因希望逐个按顺序获取图像,而不是并行获取图像,假设您在列表,数组等中有URL,请修改教程示例,以便onPostExecute调用活动中的方法,在回调接口或类本身中定义,并且对于每次迭代,从列表中选择一个元素,并在前一个完成后启动新的LoadImage作业。
示例(未经测试)代码:
public class MainActivity extends Activity {
Button load_img;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
private List<String> mURLs = new LinkedList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
load_img = (Button)findViewById(R.id.load);
img = (ImageView)findViewById(R.id.img);
load_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mURLs.add("http://www.learn2crack.com/wp-content/uploads/2014/04/node-cover-720x340.png");
mURLs.add("some-other-URL");
loadNext();
}
});
private void loadNext() {
String url = mURLs.remove();
if (url != null) {
new LoadImage().execute(url);
}
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
loadNext();
}
}
}
在这个例子中,我将图像重复地设置在同一个ImageView上,这显然没有意义。您显然必须通过将imageview作为参数发送到任务来跟踪哪个图像进入哪个图像视图,或者将图像视图(或它们的R.id.xxx ID并相应地调用findById)保存在数组中同样,或者保留一个柜台,或......有一百万种方法可以解决这个问题。
另一种方法是将数组发送到AsyncTask并使doInBackground简单地使用for循环或类似循环遍历数组。
但请注意,更好的方法可能是实际并行化任务,以确保充分利用可用的网络带宽来并行获取图像。
答案 1 :(得分:0)
您可以使用Android Volley Library下载图像。
将volley.jar库添加到您的项目中
Image Request using Volley https://developer.android.com/training/volley/request.html#request-image
如果要在gridView / ListView中显示图像。
使用
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/networkImageView"
android:layout_width="150dp"
android:layout_height="170dp"
android:layout_centerHorizontal="true" />
在grid_item.xml或list_item.xml
中在ListAdapter的getView中
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the NetworkImageView that will display the image.
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
// Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader();
// Set the URL of the image that should be loaded into this view, and
// specify the ImageLoader that will be used to make the request.
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);
}
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
答案 2 :(得分:0)
private void GetMultipleImages() {
HttpGet httpGet = null;
try {
httpGet = new HttpGet(new URI("URL"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
RestTask task = new RestTask(getActivity(), ACTION_FOR_INTENT_CALLBACK);
task.execute(httpGet);
}
private class RestTask extends AsyncTask<HttpUriRequest, Void, String>
{
private static final String TAG = "AARestTask";
public static final String HTTP_RESPONSE = "httpResponse";
private Context mContext;
Activity context;
private HttpClient mClient;
private String mAction;
public RestTask(Context context, String action)
{
mContext = context;
mAction = action;
mClient = new DefaultHttpClient();
}
public RestTask(FragmentActivity activity, String action, HttpClient client)
{
mContext = context;
mAction = action;
mClient = client;
}
@Override
protected String doInBackground(HttpUriRequest... params)
{
try
{
HttpUriRequest request = params[0];
HttpResponse serverResponse = mClient.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
return handler.handleResponse(serverResponse);
}
catch (Exception e)
{
// TODO handle this properly
e.printStackTrace();
return "";
}
}
@Override
protected void onPostExecute(String result)
{
Log.e(TAG, "RESULT = " + result);
/*Intent intent = new Intent(mAction);
intent.putExtra(HTTP_RESPONSE, result);
mContext.sendBroadcast(intent);*/
JSONObject jObject;
try {
jObject = new JSONObject(result);
JSONArray jSearchData = jObject.getJSONArray("data");
for (int i = 0; i < jSearchData.length(); i++) {
JSONObject objJson = jSearchData.getJSONObject(i);
String data = objJson.getString("id");
String imagesData = objJson.getString("images");
JSONArray jsonImages = new JSONArray("[" + imagesData + "]");
JSONObject imageObject = jsonImages.getJSONObject(0);
String images = imageObject.getString("thumbnail");
JSONArray imageArray = new JSONArray("[" + images + "]");
JSONObject urlObject = imageArray.getJSONObject(0);
String url = urlObject.getString("url");
urlArrayList.add(url);
}
imageAdapter = new InstaImageAdapter(getActivity(),urlArrayList);
Log.e("imageAdapter ==>",""+imageAdapter);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(),4);
rvInstagramImage = (RecyclerView)getActivity().findViewById(R.id.rv_insta_img);
rvInstagramImage.setLayoutManager(layoutManager);
rvInstagramImage.setItemAnimator(new DefaultItemAnimator());
rvInstagramImage.addItemDecoration(new ItemOffsetDecoration(getActivity(), R.dimen.item_offset));
rvInstagramImage.setAdapter(imageAdapter);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}