How to organize data from a listview?

Asked

Viewed 882 times

2

I have a list view of times where it says the name of the line, the stop , time and state.

If someone can explain me how the organization works in android I would just need to know how to organanizar in ascending and ascending order for for example the field of the line name.

The goal is for example what I saw in English stackoverflow:

Unsorted:

Record  Color   Clothes
0       blue    shoes
1       yellow  pants
2       red     boots
3       black   coat

Sorted by Color:

Record  Color   Clothes
3       black   coat
0       blue    shoes
2       red     boots
1       yellow  pants

Sorted by Clothes:

  Record  Color   Clothes
    2       red     boots
    3       black   coat
    1       yellow  pants
    0       blue    shoes

Only that for a listview with the "Arraylist" only that with the two ascending and descending order. The English post:

link

My code from my list :

 try {
            jsonArray = new JSONArray(myJSON);


            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject cursor = jsonArray.getJSONObject(i);

                String title = cursor.getString(TAG_TITLE);

                horarioHora.add(cursor.getString(TAG_TITLE));
                String estado = cursor.getString(TAG_DATESTART);
                horarioLinha.add(cursor.getString("linhaNome"));
                horarioParagem.add(cursor.getString("paragemRua"));
                HashMap<String, String> horario = new HashMap<>();
                horario.put(TAG_TITLE, title);
                horario.put(TAG_DATESTART, estado);

                horarioList.add(horario);
            }

            ListAdapter adapter = new SimpleAdapter(this, horarioList, R.layout.list_item,
                    new String[]{TAG_TITLE, TAG_DATESTART},
                    new int[]{R.id.title, R.id.estado});
            listaHorarios.setAdapter(adapter);
            dialog.dismiss();
            Url = "http://dagobah.grifin.pt/tiagocoelho/utilizadorAndroid.php";
            funcao = "utilizador";

            get_data();
            listaHorarios.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                            HorariosActivity.this);
                    alertDialogBuilder
                            .setMessage("Quer adicionar o horário aos favoritos?")
                            .setCancelable(false)
                            .setPositiveButton("Adicionar",


                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                            int id) {
                                            try {
                                                horarioitem = jsonArray.getJSONObject(position).toString();
                                                Sthoras = horarioHora.get(position);
                                                Stlinhas = horarioLinha.get(position);
                                                Stparagens = horarioParagem.get(position);
                                                tvlinhas.setText(Sthoras);

                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }

                                            Url = "http://dagobah.grifin.pt/tiagocoelho/confirmaAddFavAndroid.php?Sthoras="+Sthoras+"&Stlinhas="+Stlinhas+"&Stparagens="+Stparagens+"&utilizadorId="+UtilizadorId2;
                                            Url=Url.replace(" ", "%20");
                                            funcao = "verificar";
                                            get_data();


                                        }
                                    });
                    alertDialogBuilder.setNegativeButton("Cancelar",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });
                    AlertDialog alert = alertDialogBuilder.create();
                    alert.show();

                }
            }); //end setOnItemClickListener
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

I hope you can help me because really by what I’ve researched I’m not able to understand the android organization.

For my program the organization cannot be made via php or sql even needs to be made by Android.

  • You want to sort the array horarioList? Why are you wearing one Hasmap? Instead you cannot use a class whose properties are the Keys of Hasmap?

2 answers

1

Listview organizes the items in the order you put them in, if your data is cluttered, most likely it is because of the JSON object because according to the documentation http://www.json.org/

Json Object is an unordered set of name/value pairs.

This way, libraries are free to reorder it as you like, and in the case of Android, it does (don’t ask me why).

I’ve had problems with this ordering as well, and the way I found to fix was to organize the list before inserting it into the list, taking the Key from Json and inserting it into position "0", then into position "1" and so on.

Some libraries like GSON maintain order, is a much easier solution than handling Key a Key (depending on the amount of Keys)

-1

Here is a listview template with intensity different from yours:

var
TForm1: TForm;
ColIndex: Integer = 0;
OrdAsc : boolean = true;

//No evento OnColumnClick do ListView
  if ColIndex = Column.Index then
  begin
    // Se a coluna clicada eh a mesma que ja esta,
    // troca a ordem
    OrdAscCol := not(OrdAscCol);
    lvMicros.AlphaSort;
  end else
  begin
    // Sendo a coluna diferente da clicada anteriormente
    OrdAscCol := true;
    ColIndex:= Column.Index;
    lvMicros.AlphaSort;
  end;


//No evento OnCompare do ListView

  // Para reorganizar o ListView de acordo com a coluna clicada
  If ColIndex = 0 Then
  begin
    // Organização pelo caption do item de acordo com a ordem ascendente ou não
    if OrdAscCol then
      Compare:= CompareText(Item1.Caption, Item2.Caption)
    else
      Compare:= CompareText(Item2.Caption, Item1.Caption);
  end else
  begin
    // Organização pelos subitems, tb de acordo com a ordem ascendente ou não
    if OrdAscCol then
      Compare:= CompareText(Item1.SubItems[ColIndex-1],
                            Item2.SubItems[ColIndex-1])
    else
      Compare:= CompareText(Item2.SubItems[ColIndex-1],
                            Item1.SubItems[ColIndex-1]);

  end;
  • 1

    AP asked the question in Java. Answer in Java. Imagine you ask a question in Delphi and I answer it in PHP. It wouldn’t do you much good.

Browser other questions tagged

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