Android - How to create a comparison so that items from LISTVIEW are displayed or not according to the date?

Asked

Viewed 187 times

1

I’m creating an app that will show open pharmacies on a certain date:
Tela inicial

I created a listview with 10 lines (pharmacies)...
And according to the day of the month certain units will be displayed... or not.
I’m taking the current date of the device, storing and displaying using :

// MOSTRA A DATA ATUAL
        dataatual = (TextView) findViewById(R.id.dataatual);
        long date = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy");
        String dateString = sdf.format(date);
        dataatual.setText(dateString);
        // FIM DATA ATUAL

However, I don’t know how to create a comparison, either with if/Else, or switch (I don’t know which one best applies) to "filter" which line of the listview should be displayed according to the date.

Entire code:

public class TELA001 extends AppCompatActivity {

static class Data
{
    public static void main (String[] args) throws java.lang.Exception
    {
        SimpleDateFormat formataData = new SimpleDateFormat("dd-MM-yyyy");
        Date data = new Date();
        String dataFormatada = formataData.format(data);
        System.out.println("Data formatada " + dataFormatada );
    }
}


// INICIA LISTVIEW

private ListView listLocais;
private TextView dataatual;

private String[] itens = {
        "Farmácia Santa Luzia", "Droga Raia", "Drogaria Droga Leste",
        "Drogaria Camila", "Drogaria Votufarma", "Farmácia Central", "Farmácia Brasil",
        "Drogarias FarMelhor", "Drogaria Bom Clima", "Drogaria São Paulo"
};

// TERMINA LISTVIEW


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tela001);

    listLocais = findViewById(R.id.lst);

    //CRIAR ADAPTADOR
    ArrayAdapter<String> adaptador =
            new ArrayAdapter<String>(getApplicationContext(),
                    android.R.layout.simple_list_item_1,
                    android.R.id.text1, itens);


    //ADICIONA O ADAPTADOR PARA A LISTA
    listLocais.setAdapter(adaptador);

    //ADICIONA UM CLIQUE NA LISTA
    listLocais.setOnItemClickListener

            (new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView,
                                        View view, int i, long l) {


                    String valorSelecionado =
                            listLocais.getItemAtPosition(i).toString();

                    Intent intent = new Intent(getApplicationContext(),MainActivity.class);


                    if (valorSelecionado == "Farmácia Santa Luzia")
                    {
                        intent.putExtra("link","https://g.page/farmaciasantaluziavotuporanga?share");
                    }

                    else if (valorSelecionado == "Droga Raia")
                    {
                        intent.putExtra("link","https://goo.gl/maps/TfvtnJ2NVjn7NN4D6");
                    }

                    else if (valorSelecionado == "Drogaria Droga Leste")
                    {
                        intent.putExtra("link","https://goo.gl/maps/ux5DTEpTrEyTnp6F6");
                    }

                    else if (valorSelecionado == "Drogaria Camila")
                    {
                        intent.putExtra("link","https://goo.gl/maps/Ku8hTFX35c18HgHU7");
                    }

                    else if (valorSelecionado == "Drogaria Votufarma")
                    {
                        intent.putExtra("link","https://goo.gl/maps/bYmsYo81vZsnRU236");
                    }

                    else if (valorSelecionado == "Farmácia Central")
                    {
                        intent.putExtra("link","https://goo.gl/maps/ekddKUMgcP7j6QVGA");
                    }

                    else if (valorSelecionado == "Farmácia Brasil")
                    {
                        intent.putExtra("link","https://goo.gl/maps/z4EHdCqbyUgtyeAcA");
                    }

                    else if (valorSelecionado == "Drogarias FarMelhor")
                    {
                        intent.putExtra("link","https://goo.gl/maps/tgsUWsh15wxYv6PPA");
                    }

                    else if (valorSelecionado == "Drogaria Bom Clima")
                    {
                        intent.putExtra("link","https://goo.gl/maps/exbBuZ74LtPVCDGm8");
                    }

                    else if (valorSelecionado == "Drogaria São Paulo")
                    {
                        intent.putExtra("link","https://goo.gl/maps/HNmM2aGZysVoocBN7");
                    }

                    startActivity(intent);

                }
            });


        // MOSTRA A DATA ATUAL
        dataatual = (TextView) findViewById(R.id.dataatual);
        long date = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy");
        String dateString = sdf.format(date);
        dataatual.setText(dateString);
        // FIM DATA ATUAL


        // CRIAR COMPARAÇÃO PARA LISTAR DETERMINADAS FARMÁCIAS PELA DATA

}

How to create a situation for only 3 days?

EDIT: There are problems with capturing and displaying items.
to class Farmacia needed to stay inside the TELA001, because, when leaving it on file, it was not found by Adapter:

public class TELA001 extends AppCompatActivity implements FarmaciaAdapter.OnFarmaciaItemClickListenerlistener {

private RecyclerView listLocais;
private TextView dataatual;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tela001);

    listLocais = findViewById(R.id.rv_farmacias);
    dataatual  = findViewById(R.id.dataatual);

    List<Farmacia> farmacias = new ArrayList<>();

    // CRIAR NOVO OBJETO PARA CADA FARMACIA
    Farmacia exemplo = new Farmacia();
    exemplo.setNome("Farmácia Santa Luzia");
    exemplo.setUrl("https://g.page/farmaciasantaluziavotuporanga?share");

    Farmacia exemplo1 = new Farmacia();
    exemplo1.setNome("GOOGLE");
    exemplo1.setUrl("https://google.com");



    // DIA (INTEIRO)
    exemplo.setDia(24); // Dia exemplo

    // ADICIONAR TODOS OBJETOS NA LISTA
    farmacias.add(exemplo);
    farmacias.add(exemplo1);

    // CRIAR NOVO ADAPTER
    FarmaciaAdapter adapter = new FarmaciaAdapter();
    adapter.setOnFarmaciaItemClickListener(this); // CAPTURA O CLIQUE DO ITEM

    listLocais.setLayoutManager(new LinearLayoutManager(this));
    listLocais.setAdapter(adapter);

    // FILTRA A LISTA DAS FARMACIAS
    Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
    Date hoje = calendar.getTime();
    int dia   = calendar.get(Calendar.DAY_OF_MONTH);

    List<Farmacia> novaLista = new ArrayList<>();

    // FILTRA FARMACIAS APENAS DO DIA SELECIONADO
    for (Farmacia obj : farmacias) {
    if (obj.getDia() == dia) novaLista.add(obj);
    }

    adapter.setData(novaLista);
    adapter.notifyDataSetChanged();

    SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy");
    String dateString = sdf.format(hoje);
    dataatual.setText(dateString);
}

    @Override
    public void onFarmaciaItemClick(@NonNull Farmacia item) {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        intent.putExtra("link", item.getUrl());
        startActivity(intent);
    }


class Farmacia {
    private String nome;
    private String url;
    private int dia;
    private int data;

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getNome() {
        return nome;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrl() {
        return url;
    }

    public void setDia(int dia) {
        this.data = data;
    }

    public int getDia() {
        return dia;
    }
}

}

EDIT CONT: It was necessary to create the method for the Itemclicklistener:

public class FarmaciaAdapter extends RecyclerView.Adapter<FarmaciaAdapter.FarmaciaViewHolder> {


    private List<TELA001.Farmacia> data;
    private OnFarmaciaItemClickListener mListener;

    public void setOnFarmaciaItemClickListener(OnFarmaciaItemClickListener listener) {
        mListener = listener;
    }

    public void setData(List<TELA001.Farmacia> data) {
        this.data = data;
    }

    @NonNull
    @Override
    public FarmaciaViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new FarmaciaViewHolder(LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_farmacia, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull FarmaciaViewHolder holder, int i) {
        holder.tvFarmaciaNome.setText(data.get(i).getNome());
    }

    @Override
    public int getItemCount() {
        return data == null ? 0 : data.size();
    }

public void setOnFarmaciaItemClickListener(TELA001 tela001) {
    Log.d(TAG, "Elemento " + getItemCount() + " clicado."); //FUNCIONANDO
}


public interface OnFarmaciaItemClickListenerlistener {
    void onFarmaciaItemClick(@NonNull TELA001.Farmacia item);
}



    class FarmaciaViewHolder extends RecyclerView.ViewHolder {
        public TextView tvFarmaciaNome;

        FarmaciaViewHolder(@NonNull View view) {
            super(view);
            tvFarmaciaNome = view.findViewById(R.id.tv_farmacia_nome);

            view.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    TELA001.Farmacia item = data.get(getAdapterPosition());

                    mListener.onFarmaciaItemClick(item);
                }
            });
        }
    }

    public interface OnFarmaciaItemClickListener {
        void onFarmaciaItemClick(@NonNull TELA001.Farmacia item);
    }
}

Itens não listados

  • You need to display all pharmacies filtered by the current day, right?

  • 1

    Wouldn’t it be the case to create a table in a db sqlite or any other of your choice and store this data in a way that can be changed in order to register a new pharmacy? Dai would also be easier to filter the data using a query sql by date, by name, by whatever you want.

  • @Exact Ivansilva

  • @Armandomarquessobrinho Yes, it would be easier and more professional working with bank even, but as the app has student goals and the deadline is super tight, did not want to change the whole structure to include bank afraid of worsening the situation...

  • There were typos in my code. They were all fixed. I noticed that you threw all the code inside the Activity, soon it will be very confusing. I advise to separate things: create the class Farmacia.java and FarmaciaAdapter.java apart from.

2 answers

0

An idea that can give a north:

Use a FOR to compare dates, and if the comparison is true, display the content of the list line. the auxiliary variable for (I mostly use "i") should be used to check the list line.

found contents regarding the link: https://www.guj.com.br/t/como-comparar-datas/85294/10

data1.compareTo(date2)

remembering that I don’t know the language used for mobile development but logic can help. Credit Felipe if you can help.

0

To use this solution, you will need to use a Adapter customized one more RecyclerView.

Backup your current code before making these changes.

1 - Replace your ListView by a RecyclerView

<android.support.v7.widget.RecyclerView
      android:id="@+id/rv_farmacias"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

2 - Create a layout customized for each item in the RecyclerView

Right click in layout/ New / Layout Resource file

3 - Choice LinearLayout, save him as item_farmacia.xml add the following xml

    <TextView android:id="@+id/tv_farmacia_nome"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

4 - Create a new class and name it as FarmaciaAdapter and add the following code

public class FarmaciaAdapter extends RecyclerView.Adapter<FarmaciaAdapter.FarmaciaViewHolder> {
    private List<Farmacia> data;
    private OnFarmaciaItemClickListener mListener;

    public void setOnFarmaciaItemClickListener(OnFarmaciaItemClickListener listener) {
        mListener = listener;
    }

    public void setData(ArrayList<Farmacia> data) {
        this.data = data;
    }

    @NonNull
    @Override
    public BottomMenuViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new FarmaciaViewHolder(LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.item_farmacia, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull FarmaciaViewHolder holder, int i) {
        holder.tvFarmaciaNome.setText(data.get(i).getNome());
    }

    @Override
    public int getItemCount() {
        return data == null ? 0 : data.size();
    }

   class FarmaciaViewHolder extends RecyclerView.ViewHolder {
        public TextView tvFarmaciaNome;

        FarmaciaViewHolder(@NonNull View view) {
            super(view);
            tvFarmaciaNome = view.findViewById(R.id.tv_farmacia_nome);

            view.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Farmacia item = data.get(getAdapterPosition());

                    mListener.onFarmaciaItemClick(item);
                }
            });
        }
    }

    public interface OnFarmaciaItemClickListener {
        void onFarmaciaItemClick(@NonNull Farmacia item);
    }
}

5 - Create another class that serves as a model for the pharmacy

public class Farmacia {
    private String nome;
    private String url;
    private int dia;

   public void setNome(String nome) {
      this.nome = nome;
   }

    public String getNome() {
      return nome;
   }

   public void setUrl(String url) {
      this.url = url;
   }

    public String getUrl() {
      return url;
   }

   public void setDia(int dia) {
      this.data = data;
   }

    public int getDia() {
      return dia;
   }
}

All this work is so that we can work with objects in the list and not simple Strings.

6 - Now in your Activity, do the following

public class TELA001 extends AppCompatActivity implements FarmaciaAdapter.OnFarmaciaItemClickListenerlistener {

     private RecyclerView listLocais;
     private TextView dataatual;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_tela001);

         listLocais = findViewById(R.id.rv_farmacias);
         dataatual  = findViewById(R.id.dataatual);

         List<Farmacia> farmacias = new ArrayList<>;

         // Crie um novo objeto para cada nova farmácia
         Farmacia exemplo = new Farmacia();
                  exemplo.setNome("Farmácia Santa Luzia");
                  exemplo.setUrl("https://g.page/farmaciasantaluziavotuporanga?share");
                  // O dia deverá ser um inteiro
                  exemplo.setDia(10); // Dia 10

         // Adicione todos os objetos nessa lista
         farmacias.add(exemplo);             

        // Vamos agora criar seu novo adapter
        FarmaciaAdapter adapter = new FarmaciaAdapter();
                        adapter.setOnFarmaciaItemClickListener(this); // Isso irá capturar o clique do item

        listLocais.setLayoutManager(new LinearLayoutManager(this));
        listLocais.setAdapter(adapter);

        // Com todas as farmácias adicionadas a lista filtre  
         Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
         Date hoje = calendar.getTime();
         int dia   = calendar.get(Calendar.DAY_OF_MONTH);

         List<Farmacia> novaLista = new ArrayList<>();

         // Isso filtrará adicionando na nova lista apenas farmácias daquele dia
         // específica
         for (Farmacia obj : farmacias) {
             if (obj.getDia() == dia) novaLista.add(obj);
         }

        adapter.setData(novaLista);
        adapter.notifyDataSetChanged();

        SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy");
        String dateString = sdf.format(hoje);
        dataatual.setText(dateString);
     }

     @Override
     public void onFarmaciaItemClick(@NonNull Farmacia item) {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
               intent.putExtra("link", item.getUrl());
        startActivity(intent);
     }
}

I haven’t tested this code, so I don’t know if it works in practice. Anything is asking. Hug!

  • In part 4 you used lambda expression, hadn’t used it in Androidstudio yet... I tried following this tutorial (https://developer.android.com/guide/platform/j8-jack.html?hl=pt-BR#Configuration) but several conflicts, what to do ?

  • I removed the expression lambda, I believe it will now work.

  • Review your code to make sure it’s the same as mine.

  • With the withdrawal of the expression - flowed, however I am not able to display the pharmacies, the absence of some error code complicates more

  • Maybe no pharmacy is going through the check if (obj.getDia() == dia) novaLista.add(obj);. Give it a whack with Log.i() and see what’s happening

Browser other questions tagged

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