How to view images in Listview from Firebase?

Asked

Viewed 1,142 times

1

Well I am receiving numerous information from firebase, and displaying them, however I would like to receive also images, without last storege, I already saved some urls in the database and when I pulled the url it would mount the image directly in the app. How can I do that ???

My Adapter

public class NoticiaAdapter extends ArrayAdapter<Noticias> {
private ArrayList<Noticias> noticias;
private Context context;
public NoticiaAdapter(Context c, ArrayList<Noticias> objects) {
    super(c, 0, objects);
    this.noticias = objects;
    this.context = c;

}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    //Criamos o objeto do tipo view
    View v = null;
    //Vemos se esta vazio
    if(noticias != null){

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        //Recupera o XML da lista
        v = inflater.inflate(R.layout.lista_noticias,parent, false);
        TextView tituloNoticia = (TextView) v.findViewById(R.id.txt_lista_noticias);
        TextView dataNoticia = (TextView) v.findViewById(R.id.txt_lista_data);
        Noticias noticia = noticias.get(position);
        tituloNoticia.setText(noticia.getTitulo());
        dataNoticia.setText(noticia.getData());
    }
    return  v;
 }
}

Model class

public class Noticias {
private String titulo;
private String noticia;
private String data;
private String imagem;

public Noticias() {
}

public String getTitulo() {
    return titulo;
}

public void setTitulo(String titulo) {
    this.titulo = titulo;
}

public String getNoticia() {
    return noticia;
}

public void setNoticia(String noticia) {
    this.noticia = noticia;
}

public String getData() {
    return data;
}

public void setData(String data) {
    this.data = data;
}

public String getImagem() {
    return imagem;
}

public void setImagem(String imagem) {
    this.imagem = imagem;
 }
}

The Fragment that receives the data

public class fragmentNoticias extends Fragment {
private ListView listView;
private ArrayAdapter adapter;
private ArrayList<Noticias> noticias;
private DatabaseReference databaseReference;
private FirebaseAuth autenticacao;
private ValueEventListener valueEventListener;

public fragmentNoticias() {
    // Required empty public constructor
}

@Override
public void onStart() {
    super.onStart();
    /*Chamamos o metodo do event listener aqui para otimizarmos os dados
     quando o fragment for gerado*/
    databaseReference.addValueEventListener(valueEventListener);
}

@Override
public void onStop() {
    super.onStop();
    //Da mesma maneira removemos a chamada do Firebase quando o fragmente for eliminado
    databaseReference.removeEventListener(valueEventListener);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_noticias, container, false);
    //Intanciando o Array de noticias
    noticias = new ArrayList<>();
    //Instanciando o listView recuperado do layout
    listView = (ListView) view.findViewById(R.id.lv_noticias);
    //Instanciando o Adapter
    /*adapter = new ArrayAdapter(
     // O getActivity recupera para o fragment o parametro Activity da classe pai (MainActivity)
            getActivity(),
            android.R.layout.simple_list_item_1,
            noticias
    );*/
    adapter = new NoticiaAdapter(getActivity(), noticias);

    //Setando o adpter no ListView
    listView.setAdapter(adapter);
    //Chamando o autentication
    autenticacao = FirebaseConfig.getAutenticacao();
    //Chamando a referencia do firebase para poder ter acesso ao BD
    databaseReference = FirebaseConfig.getFirebase().child("Noticias").child("TabelaNoticias");
    /*Aqui nos chamamos a função onde iremos listar os dados, colocamos ela dentro de uma
    de uma variavel pra poder otimizar o uso e só chamar essa função quando o fragmente for criado
    e eliminala quando o fragmente for eliminado*/
    valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //O clear vai limpar a lista para não chamar os dados mais de uma vez
            noticias.clear();
            //Aqui temos o for onde o laço vai pegar todas as noticias
            for(DataSnapshot dados: dataSnapshot.getChildren()) {
                /*Chamamos a classe modelo Noticias pra poder gravarmos os dados vindos do firebase
                em um obj */
                Noticias noticia = dados.getValue(Noticias.class);
                //pegamos só o titulo da noticia
                noticias.add(noticia);
            }
            //Passamos os dados do fireBase para o adapter poder popular o Listview
            adapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    };

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new Intent(getActivity(), NoticiaActivity.class);

            Noticias noti = noticias.get(position);

            i.putExtra("noticia",noti.getNoticia());
            i.putExtra("titulo",noti.getTitulo());
            i.putExtra("data",noti.getData());

            startActivity(i);
        }
    });

    return view;
 }

}

inserir a descrição da imagem aqui

  • You can already see the url inside the app?

  • yes, I can pull the url in text format

1 answer

4


You have more than one possibility to perform this procedure. I will show you 2 ways using framework and a "in race". Follow below:

1. Picasso

The Picasso is a framework which allows the loading of images without complications. See how it should be done:

Gradle:

compile 'com.squareup.picasso:picasso:2.5.2'

How to use:

Ai in your code just do this way below, passing as method parameter into() your ImageView. Behold:

ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

2. Glide

Glide has the same image loading purpose, focusing on caching and smoothness with respect to scroll.

Gradle:

repositories {
  mavenCentral() 
}

dependencies {
  compile 'com.github.bumptech.glide:glide:3.7.0'
  compile 'com.android.support:support-v4:19.1.0'
}

How to use:

Also very similar to Picasso, in the code just do this way below, also passing as method parameter into() your ImageView. Behold:

ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Obs.: Check the latest release on framework

In case you didn’t want to use any of these framework, you can do "in race" using the InputStream through a AsyncTask. It is important to read a little about the advantages of using one of these framework for the purpose, as it may facilitate in the issue of image processing, for example cache and Crop of images. See how it should look:

// Aqui mostra a imagem no ImageView
new DownloadImageTask((ImageView) findViewById(R.id.imageView))
            .execute("http://i.imgur.com/DvpvklR.png");

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

Source: How to load an Imageview by URL in Android?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.