使用齐射在片段上显示图像

时间:2017-10-18 09:57:16

标签: java android fragment android-volley

我想下载,缓存和显示images on Fragment using volley但没有任何反应我只有加载消息(“正在加载数据”,“请稍候......”)但没有图像。我得到Volley的正确答复。我已经以正确的格式解析了JSON in arraylist

public class PhotoFragment extends Fragment {

public PhotoFragment(){
}

//Creating a List of superheroes
private List<SuperHeroes> listSuperHeroes;

//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_photo, container, false);

    //Initializing Views
    recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);

    //Initializing our superheroes list
    listSuperHeroes = new ArrayList<>();

    //Calling method to get data
    getData();
    //Finally initializing our adapter
    adapter = new CardAdapter(listSuperHeroes, getActivity());

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);

    return view;
}

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

}

//This method will get data from the web api
private void getData(){
    //Showing a progress dialog
    final ProgressDialog loading = ProgressDialog.show(getActivity(),"Loading Data", "Please wait...",false,false);

    //Creating a json array request
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Dismissing progress dialog
                    loading.dismiss();

                    //calling method to parse json array
                    parseData(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    //Creating request queue
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

    //Adding request to the queue
    requestQueue.add(jsonArrayRequest);
}

//This method will parse json data
private void parseData(JSONArray array){
    for(int i = 0; i<array.length(); i++) {
        SuperHeroes superHero = new SuperHeroes();
        JSONObject json = null;
        try {
            json = array.getJSONObject(i);
            superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
            superHero.setName(json.getString(Config.TAG_NAME));
            superHero.setRank(json.getInt(Config.TAG_RANK));
            superHero.setRealName(json.getString(Config.TAG_REAL_NAME));
            superHero.setCreatedBy(json.getString(Config.TAG_CREATED_BY));
            superHero.setFirstAppearance(json.getString(Config.TAG_FIRST_APPEARANCE));

            ArrayList<String> powers = new ArrayList<String>();

            JSONArray jsonArray = json.getJSONArray(Config.TAG_POWERS);

            for(int j = 0; j<jsonArray.length(); j++){
                powers.add(((String) jsonArray.get(j))+"\n");
            }
            superHero.setPowers(powers);


        } catch (JSONException e) {
            e.printStackTrace();
        }
        listSuperHeroes.add(superHero);
    }


}


 }

CardAdapter

    public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

        private ImageLoader imageLoader;
        private Context context;

        //List of superHeroes
        List<SuperHeroes> superHeroes;

        public CardAdapter(List<SuperHeroes> superHeroes, Context context){
            super();
            //Getting all the superheroes
            this.superHeroes = superHeroes;
            this.context = context;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.superheroes_list, parent, false);
            ViewHolder viewHolder = new ViewHolder(v);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {

            SuperHeroes superHero =  superHeroes.get(position);

            imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
            imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));

            holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
            holder.textViewName.setText(superHero.getName());
            holder.textViewRank.setText(String.valueOf(superHero.getRank()));
            holder.textViewRealName.setText(superHero.getRealName());
            holder.textViewCreatedBy.setText(superHero.getCreatedBy());
            holder.textViewFirstAppearance.setText(superHero.getFirstAppearance());

            String powers = "";

            for(int i = 0; i<superHero.getPowers().size(); i++){
                powers+= superHero.getPowers().get(i);
            }

            holder.textViewPowers.setText(powers);
        }

        @Override
        public int getItemCount() {
            return superHeroes.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder{
            public NetworkImageView imageView;
            public TextView textViewName;
            public TextView textViewRank;
            public TextView textViewRealName;
            public TextView textViewCreatedBy;
            public TextView textViewFirstAppearance;
            public TextView  textViewPowers;

            public ViewHolder(View itemView) {
                super(itemView);
                imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
                textViewName = (TextView) itemView.findViewById(R.id.textViewName);
                textViewRank= (TextView) itemView.findViewById(R.id.textViewRank);
                textViewRealName= (TextView) itemView.findViewById(R.id.textViewRealName);
                textViewCreatedBy= (TextView) itemView.findViewById(R.id.textViewCreatedBy);
                textViewFirstAppearance= (TextView) itemView.findViewById(R.id.textViewFirstAppearance);
                textViewPowers= (TextView) itemView.findViewById(R.id.textViewPowers);
            }
        }
    }

4 个答案:

答案 0 :(得分:0)

在代码中使用Glide。

1.add compile

dependencies {
    ...
    compile 'com.github.bumptech.glide:glide:3.7.0'
}

2.在代码中使用。

Glide.with(context).load(url).placeholder(R.mipmap.ic_placehoder).error(R.mipmap.ic_placehoder).into(imageView);

答案 1 :(得分:0)

您可以使用Glide库

在此片段中加载图像
public void LoadImagefrg(final Context cx, final ImageView imageView, int demoImage, String url){
    if (!((Activity) cx).isFinishing()) {
        Glide.with(cx).load(url).asBitmap().centerCrop().placeholder(demoImage).signature(new StringSignature(String.valueOf(System.currentTimeMillis()))).into(new BitmapImageViewTarget(imageView) {
            @Override
            protected void setResource(Bitmap resource) {
               //For round image
                RoundedBitmapDrawable circularBitmapDrawable =
                        RoundedBitmapDrawableFactory.create(cx.getResources(), resource);
                circularBitmapDrawable.setCircular(true);
               //round image code ends here
                imageView.setImageDrawable(circularBitmapDrawable);
            }
        });
    }
}

答案 2 :(得分:0)

试试这个

  • 仅限Volley
  • 您必须创建LruBitmapCache class
public class LruBitmapCache extends LruCache<String, Bitmap> implements
        ImageLoader.ImageCache {
        public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        return cacheSize;
    }

    public LruBitmapCache() {
        this(getDefaultLruCacheSize());
    }

    public LruBitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}
  • 然后您创建了application class
  • instance of LruCache class
public class AppController extends Application {
 private ImageLoader mImageLoader;
@Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        constants = new Constants(this);
        initialize();
       // Foreground.init(this);
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
                .name(Realm.DEFAULT_REALM_NAME)
                .schemaVersion(0)
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm.setDefaultConfiguration(realmConfiguration);
    }
 public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }
}
  • LruBitmapCache
  • 中使用fragment in OnResume课程
 @Override
        protected void onResume() {
            super.onResume();
      setImage(Base_url_of_IMAGE,Pass_your_pic_where_you_have_to_set_it);
        }

    public static void setImage(String str_url, final ImageView iv_profile) 
   {
    if (str_url != null && str_url.length() > 0) {
        ImageLoader imageLoader = 
     AppController.getInstance().getImageLoader();
        imageLoader.get(str_url, new ImageLoader.ImageListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("jkd", "Image Load Error: " + error.getMessage());                    
            iv_profile.setImageResource(R.drawable.no_image);
            }

            @Override
            public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {
                    Log.e("jkd", "" + response);
                    iv_profile.setImageBitmap(response.getBitmap());
                }
            }
        });
    } else {
          iv_profile.setImageResource(R.drawable.no_image);
    }
}

乐意帮助您

答案 3 :(得分:0)

使用毕加索图书馆http://square.github.io/picasso/ 我很容易使用它,在https://github.com/developerThami/PiccassoImage/

上查看我的代码