Hot questions for Using Glide in android context

Top 10 Java Open Source / Glide / android context

Question:

I want to get Application context to use with glide in non-activity class. But it's always returning null. This is the code I'm using - how might I solve this?

I created Contextor for get application context to use in non-activity model.

public class Contextor {

    private static Contextor instance;

    public static Contextor getInstance() {
        if (instance == null)
            instance = new Contextor();
        return instance;
    }

    private Context mContext;

    private Contextor() {}

    public void init(Context context) {
        mContext = context;
    }

    public Context getContext() {
        return mContext;
    }
}

In myRecyclerViewAdapter.

public class RecyclerViewNewfeedAdapter extends RecyclerView.Adapter<RecyclerViewNewfeedAdapter.PostViewHolder> {

private List<Post> mPostList;
private Context mContext;

class PostViewHolder extends RecyclerView.ViewHolder {
    TextView username;
    TextView text;
    CircleImageView profileImage;

    PostViewHolder(View view) {
        super(view);
        username = (TextView) view.findViewById(R.id.tvPostUsername);
        text = (TextView) view.findViewById(R.id.tvPostText);
    }
}

public RecyclerViewNewfeedAdapter(List<Post> mPostList) {
    this.mPostList = mPostList;
}

@Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.post_row, parent, false);

    initInstances();

    return new PostViewHolder(itemView);
}

private void initInstances(){
    mContext = Contextor.getInstance().getContext();
}

@Override
public void onBindViewHolder(final PostViewHolder holder, int position) {
    final Post post = mPostList.get(position);

    FirebaseRef.mUserInfoRef.child(post.getOwnerPost()).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            holder.username.setText(dataSnapshot.child("username").getValue(String.class));
            Glide.with(mContext).load(dataSnapshot.child("profileImage").getValue(String.class)).placeholder(R.drawable.ic_default_profile_image).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.profileImage);
            holder.text.setText(post.getTextPost());
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
@Override
public int getItemCount() {
    return mPostList.size();
}

Answer:

Why this context always returned null?

because you never call init(Context context) on Contextor.getInstance(). Btw, it seems a little of overkill to have this object when you can easily assign parent.getContext() to mContext

Question:

Boa noite, Segui um tutorial que implementa o RecycleView; Porém pelo código não consegui definir o Glide.with(???)

Alguém pode me orientar como posso fazer?

Segue código:

    public class adp_rv_pcp_promocoes extends RecyclerView.Adapter<adp_rv_pcp_promocoes.ViewHolderPromocoes> {

//**meu
public String id_Sel, usua_Sel, raza_Sel, cnpj_Sel, nome_Sel, emai_Sel, esta_Sel, cida_Sel;
public String fant_Sel;
public String data_Sel, premium_Sel, data_contrato_Sel, ende_Sel, bair_Sel, cep_Sel, cate1_Sel, cate2_Sel;
public String cate3_Sel, info_Sel, latitude_Sel, longitude_Sel, promo_Sel, vlr_desc_Sel, txt_desc_Sel;
public String val_desc_Sel, site_Sel, urlLogo_Sel, urlFoto_Sel, words_Sel;
public String url_ver = "";
//**meu

private List<cls_promocoes> dados;

public adp_rv_pcp_promocoes(List<cls_promocoes> dados){
    this.dados = dados;
}


@Override
public adp_rv_pcp_promocoes.ViewHolderPromocoes onCreateViewHolder(ViewGroup parent, int viewType) {

    LayoutInflater layoutInflater = LayoutInflater.from( parent.getContext() );

    View view = layoutInflater.inflate( R.layout.lyt_pcp_promocoes, parent, false );

    ViewHolderPromocoes holderPromocoes = new ViewHolderPromocoes(view, parent.getContext());

    return holderPromocoes;
}

@Override
public void onBindViewHolder(adp_rv_pcp_promocoes.ViewHolderPromocoes holder, int position) {

    if(dados != null && dados.size() > 0){//PREVINE DE PASSAR SEM TER DADOS
        //PARA POPULAR DEVE SER AQUI
    }

    //UTILIZANDO A CLASSE PARA RECUPERAR OS DADOS
    cls_promocoes promocao = dados.get( position );
    // posso usar direto ou passar pela classe
    // direto-> dados.get( position ).getCnpj()
    // pela classe-> promocao.getCnpj()

    for (int i = 0; i < arrayList_empr.size(); i++) {
        if (arrayList_empr.get(i).getCnpj().equals( promocao.getCnpj() )) {
            urlLogo_Sel =  arrayList_empr.get( i ).getUrlLogo().toString();
        }
    }


    holder.cnpj = promocao.getCnpj();


    /*
    Glide.with(this.context)
            .load(endereco + "img/empresas/logos/" + cnpj_Sel + ".png")
            .diskCacheStrategy( DiskCacheStrategy.ALL)
            .thumbnail(0.1f)
            .placeholder (R.drawable.icon_foto_carregando)
            .error (R.drawable.icon_foto_sem)
            .into(holder.image);
    */

    holder.tv_prod_codi.setText("Cód.:" + promocao.getCodi().toUpperCase());
    if(promocao.getPromoInfo().length() > 3){
        holder.tv_prod_promo.setText(promocao.getPromoInfo());
    }
    if(promocao.getNome().length() > 0){holder.tv_prod_nome.setText(promocao.getNome().toUpperCase()); holder.tv_prod_nome.setVisibility( View.VISIBLE );} else {holder.tv_prod_nome.setVisibility( View.GONE );}
    if(promocao.getDesc().length() > 0){holder.tv_prod_desc.setText(promocao.getDesc()); holder.tv_prod_desc.setVisibility( View.VISIBLE );} else {holder.tv_prod_desc.setVisibility( View.GONE );}
    if(promocao.getFabr().length() > 0){holder.tv_prod_fabr.setText("Ind.: " + promocao.getFabr()); holder.tv_prod_fabr.setVisibility( View.VISIBLE );} else {holder.tv_prod_fabr.setVisibility( View.GONE );}
    if(promocao.getCore().length() > 0){holder.tv_prod_core.setText("Cor: " + promocao.getCore()); holder.tv_prod_core.setVisibility( View.VISIBLE );} else {holder.tv_prod_core.setVisibility( View.GONE );}
    //if(promocao.getQuan().length() > 0){holder.tv_prod_quan.setText("Qnt: " + promocao.getQuan()); holder.tv_prod_quan.setVisibility( View.VISIBLE );} else {holder.tv_prod_quan.setVisibility( View.GONE );}


    if(promocao.getPrec().length() > 0){
        String vlr = promocao.getPrec().toString();
        Double n_valor = Double.parseDouble(vlr);
        NumberFormat nf = NumberFormat.getCurrencyInstance();
        String formatado = nf.format (n_valor);

        holder.tv_prod_prec.setText(formatado);
    } else {
        holder.tv_prod_prec.setVisibility( View.GONE );
    }

    holder.urlFoto = promocao.getUrlFoto();

    /*
    Glide.with(context)
            .load(endereco + "img/empresas/produtos/" + holder.cnpj + "/" + promocao.getCodi() + ".png")
            .diskCacheStrategy( DiskCacheStrategy.ALL)
            .thumbnail(0.1f)
            .placeholder (R.drawable.icon_foto_carregando)
            .error (R.drawable.icon_foto_sem)
            .into(holder.iv_prod_foto);
    */


}

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

public class ViewHolderPromocoes extends RecyclerView.ViewHolder{

    public ImageView iv_prod_foto;
    public TextView tv_prod_codi, tv_prod_nome, tv_prod_desc, tv_prod_prec, tv_prod_fabr, tv_prod_core, tv_prod_quan, tv_prod_promo;
    public ProgressBar progressBar;
    public String urlFoto, cnpj;
    public LinearLayout ll_logo1;
    public RoundedImageView image;

    public ViewHolderPromocoes(View itemView, final Context context) {
        super( itemView );

        image = RoundedImageView.class.cast(itemView.findViewById(R.id.image_item));
        iv_prod_foto = (ImageView) itemView.findViewById(R.id.iv_prod_foto);
        tv_prod_codi = (TextView) itemView.findViewById(R.id.tv_prod_codi);
        tv_prod_nome = (TextView) itemView.findViewById(R.id.tv_prod_nome);
        tv_prod_desc = (TextView) itemView.findViewById(R.id.tv_prod_desc);
        tv_prod_prec = (TextView) itemView.findViewById(R.id.tv_prod_prec);
        tv_prod_fabr = (TextView) itemView.findViewById(R.id.tv_prod_fabr);
        tv_prod_core = (TextView) itemView.findViewById(R.id.tv_prod_core);
        tv_prod_quan = (TextView) itemView.findViewById(R.id.tv_prod_quan);
        tv_prod_promo = (TextView) itemView.findViewById(R.id.tv_prod_promo);
        progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);


        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //System.out.println("************** CNPJ 55555 ***********> " + viewHolder.cnpj);
                for (int i = 0; i < arrayList_empr_sel.size(); i++) {
                    if (arrayList_empr_sel.get(i).getCnpj().equals( cnpj )) {
                        //System.out.println("************** CNPJ 88888888888 ***********> " + arrayList_empr_sel.get( i ).getId().toString());
                        Intent intent = new Intent(context, ebook.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("id_Sel", arrayList_empr_sel.get( i ).getId().toString());
                        bundle.putString("usua_Sel", arrayList_empr_sel.get( i ).getUsua().toString());
                        bundle.putString("raza_Sel", arrayList_empr_sel.get( i ).getRaza().toString());
                        bundle.putString("fant_Sel", arrayList_empr_sel.get( i ).getFant().toString());
                        bundle.putString("cnpj_Sel", arrayList_empr_sel.get( i ).getCnpj().toString());
                        bundle.putString("nome_Sel", arrayList_empr_sel.get( i ).getNome().toString());
                        bundle.putString("emai_Sel", arrayList_empr_sel.get( i ).getEmai().toString());
                        bundle.putString("esta_Sel", arrayList_empr_sel.get( i ).getEsta().toString());
                        bundle.putString("cida_Sel", arrayList_empr_sel.get( i ).getCida().toString());
                        bundle.putString("data_Sel", arrayList_empr_sel.get( i ).getData().toString());
                        bundle.putString("premium_Sel", arrayList_empr_sel.get( i ).getPremium().toString());
                        bundle.putString("data_contrato_Sel", arrayList_empr_sel.get( i ).getData_contrato().toString());
                        bundle.putString("ende_Sel", arrayList_empr_sel.get( i ).getEnde().toString());
                        bundle.putString("bair_Sel", arrayList_empr_sel.get( i ).getBair().toString());
                        bundle.putString("cep_Sel", arrayList_empr_sel.get( i ).getCep().toString());
                        bundle.putString("cate1_Sel", arrayList_empr_sel.get( i ).getCate1().toString());
                        bundle.putString("cate2_Sel", arrayList_empr_sel.get( i ).getCate2().toString());
                        bundle.putString("cate3_Sel", arrayList_empr_sel.get( i ).getCate3().toString());
                        bundle.putString("info_Sel", arrayList_empr_sel.get( i ).getInfo().toString());
                        bundle.putString("latitude_Sel", arrayList_empr_sel.get( i ).getLatitude().toString());
                        bundle.putString("longitude_Sel", arrayList_empr_sel.get( i ).getLongitude().toString());
                        bundle.putString("promo_Sel", arrayList_empr_sel.get( i ).getPromo().toString());
                        bundle.putString("vlr_desc_Sel", arrayList_empr_sel.get( i ).getVlr_desc().toString());
                        bundle.putString("txt_desc_Sel", arrayList_empr_sel.get( i ).getTxt_desc().toString());
                        bundle.putString("val_desc_Sel", arrayList_empr_sel.get( i ).getVal_desc().toString());
                        bundle.putString("site_Sel", arrayList_empr_sel.get( i ).getSite().toString());
                        bundle.putString("urlLogo_Sel", arrayList_empr_sel.get( i ).getUrlLogo().toString());
                        bundle.putString("urlFoto_Sel", arrayList_empr_sel.get( i ).getUrlFoto().toString());
                        bundle.putString("words_Sel", arrayList_empr_sel.get( i ).getWords().toString());
                        intent.putExtras(bundle);
                        context.startActivity(intent);
                    }
                }
            }
        });

        iv_prod_foto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent abre = new Intent(context, ebook_ampliar.class);
                abre.putExtra("urlPhoto", urlFoto);
                context.startActivity(abre);
                //((AppCompatActivity)context).startActivityForResult(abre, 1); //usado para ter o retorno
                //O onActivityResult fica na activity que usa este adapter
            }
        });
    }

}

}

Fiz conforme um tutorial que implementa o RecycleView; Porém pelo código não consegui definir o Glide.with(???)

Alguém pode me orientar como posso fazer?

Agradeço a ajuda!!!


Answer:

Should look like this:

Glide.with(holder.image.getContext())
            .load(endereco + "img/empresas/logos/" + cnpj_Sel + ".png")
            .diskCacheStrategy( DiskCacheStrategy.ALL)
            .thumbnail(0.1f)
            .placeholder (R.drawable.icon_foto_carregando)
            .error (R.drawable.icon_foto_sem)
            .into(holder.image);