如何使用 volley in android 将单个图像从服务器放入我的 imageview?

how to put single image from server into my imageview using volly in android?

我已经阅读了很多关于从服务器获取图像并将其放入 listview 的文章,但是对于 activity 我需要从服务中获取单个图像,它应该适合所有设备 perfectly.how 我可以这样做吗,因为我是 android 的新手,所以对此不太了解..请帮忙?如果能举出任何例子,那将非常有帮助。

这是我的 MainActivity.class:

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;

import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.android.volley.Request;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, FragmentOne.OnFragmentInteractionListener,
        FragmentTwo.OnFragmentInteractionListener

{
    ImageView im1, im2, im3;
    ImageLoader mImageLoader;
    ImageView mImageView;
    // The URL for the image that is being loaded.
    private static final String IMAGE_URL =
            "http://developer.android.com/images/training/system-ui.png";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        im1 = (NetworkImageView) findViewById(R.id.ms1);


        ImageRequest imageRequest = new ImageRequest(IMAGE_URL, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(final Bitmap response) {
                im1.setImageBitmap(response);
            }
        }, 0, 0, ImageView.ScaleType.CENTER_INSIDE, null, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        requestQueue.add(imageRequest);

        if (savedInstanceState == null) {
            Fragment fragment = null;
            Class fragmentClass = null;
            fragmentClass = FragmentOne.class;
            try {
                fragment = (Fragment) fragmentClass.newInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }

            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        }
        im1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(MainActivity.this, Login.class));
            }
        });
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:
                // User chose the "Settings" item, show the app settings UI...


            case R.id.action_cart:


                Intent ibs = new Intent(MainActivity.this,AddToCart.class);
                ibs.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(ibs);
                finish();
                break;
            // User chose the "Favorite" action, mark the current item
            // as a favorite...


            default:
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
        return true;
    }
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        Fragment fragment = null;
        Class fragmentClass = null;
        if (id == R.id.br_menu) {
            Intent i = new Intent(MainActivity.this,Login.class);
            startActivity(i);

        } else if (id == R.id.tr_ordr) {
            fragmentClass = FragmentTwo.class;
        } else if (id == R.id.pl_ordr) {
            fragmentClass = FragmentOne.class;
        } else if (id == R.id.profl) {
            fragmentClass = FragmentTwo.class;
        } else if (id == R.id.addr) {
            fragmentClass = FragmentOne.class;
        } else if (id == R.id.crds) {
            fragmentClass = FragmentTwo.class;
        }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //FragmentManager fragmentManager = getSupportFragmentManager();
       //fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }




}

对于 m1,我需要设置图像视图...

使用 ImageRequestVolleyURL 下载图像并在您的 ImageView.

上使用它
    im1 = (ImageView) findViewById(R.id.imageView_id); //add proper ImageView id not NetworkimageView id


    ImageRequest imageRequest = new ImageRequest(IMAGE_URL, new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(final Bitmap response) {
            im1.setImageBitmap(response);
        }
    }, 0, 0, ImageView.ScaleType.CENTER_INSIDE, null, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
        }
    });

    RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
    requestQueue.add(imageRequest);

始终使用一些第 3 方库来加载 Glide、fresco、picasso 等图像。

为什么?
1. 防止我的​​收藏夹在加载许多图像时出现内存不足错误,例如列表视图。
2. 快速获取图片
3.为了将来使用它。这些图像存储在缓存中,您可以在将来使用它们而无需再次实际下载它们。这有助于节省流量并减少用户的等待时间。

检查volley networkimageview并使用LruCache。您可以找到所有内容 here。只需使用 LruCache。它非常简单和强大。我已经在很多项目中使用了。

实施步骤

  1. 创建class LruBitmapCache 并下载下面的文件然后复制代码

    https://drive.google.com/file/d/0B8oLTPOweId6cnFBamhFd3pva2c/view?usp=sharing

  2. 创建一个名为 AppController 的应用程序 class 并从下面的文件中复制代码

    https://drive.google.com/file/d/0B8oLTPOweId6T1VEdlVTeWwxUTQ/view?usp=sharing

  3. 在 xml 中包括此视图以代替 imageview

    <com.android.volley.toolbox.NetworkImageView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/thumbnail"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="8dp">
    
  4. 在activity

    NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.thumbnail);
    
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();
    
    thumbNail.setImageUrl(url, imageLoader);