How to display images in the ListView from Firebase?

1

Well I'm getting lots of information from the firebase, and displaying them, but I would like to receive images as well, without overcoming the 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 this ???

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;
 }

}

    
asked by anonymous 25.06.2017 / 20:09

1 answer

4

You have more than one possibility to perform this procedure. I'll show you 2 shapes using framework and a "in breed". Follow below:

1. Picasso

Picasso is a framework that allows you to upload images without complications. Here's how it should be done:

Gradle :

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

How to use :

In your code, just do this below, passing as a parameter of the method into() its ImageView . See:

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, with a focus on cache and smoothness over 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 a parameter of the method into() its ImageView . See:

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

Note: Check the most current version of the release on the framework

If you did not want to use any of these framework , you can do "in breed" using InputStream through AsyncTask . It is important to read a little about the advantages of using one of these framework for the purpose, as it may make it easier to handle the image, for example cache and crop of images. Here's 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 ?

    
25.06.2017 / 20:56