如果包含时间戳的子级是随机ID,如何在Firebase中按时间戳排序?

时间:2019-05-15 00:09:36

标签: java android firebase firebase-realtime-database

我有一个填充视图持有者recyclerview 并且我想按孩子订购它,如代码所示,它已与我的Firebase同步。

my firebase structure

mDatabase.orderByKey()。orderByChild(“ Timestamp”)。limitToLast(100); 它不起作用

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitorar_morador);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        String bairro = "test";
        String cidade = "test";
              mDatabase = FirebaseDatabase.getInstance().getReference().child(cidade).child(bairro).child("Relatorio");
        //Query chatQuery = mDatabase.orderByChild("last_time_stamp"). limitToLast(20);
        mDatabase.keepSynced(true);
        //mDatabase.orderByChild("Timestamp").limitToLast(100);

    //mDatabase.orderByKey().orderByChild("Timestamp").limitToLast(100);

        mBlogList=(RecyclerView)findViewById(R.id.myrecycleview);
        mBlogList.setHasFixedSize(true);
        mBlogList.setLayoutManager(manager);
        manager.setReverseLayout(false);
        mBlogList.scrollToPosition(0);
       // manager.setReverseLayout(true);

}
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);


    @Override
    protected void onStart() {
        super.onStart();

        final  FirebaseRecyclerAdapter<Blog,BlogViewHolder>firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>
                (Blog.class,R.layout.blog_row,BlogViewHolder.class,mDatabase) {
           // int n =0;

            @Override
            protected void populateViewHolder(BlogViewHolder viewHolder, Blog model,int position) {
                if (model.getNome() == null){


                }else{
                    viewHolder.setNome(model.getNome());
                }
                if (model.getMensagem() == null){


                }else{
                    viewHolder.setMensagem(model.getMensagem());
                }
                if (model.getRua() == null){


                }else{
                    viewHolder.setRua(model.getRua());
                }
                if (model.getNumero() == null){


                }else{
                    viewHolder.setNumero(model.getNumero());
                }

                if (model.getImage() == null){


                }else{
                    viewHolder.setImage(getApplicationContext(),model.getImage());
                }

                if(model.getLon() == null){
                    // String is empty or null
                }else {
                    viewHolder.setLon(Double.toString(model.getLon()));
                   // n = 1;
                }
                if(model.getLat() == null){
                    // String is empty or null
                }else {
                    viewHolder.setLat(Double.toString(model.getLat()));
                    //n++;
                }

                if(model.getTimestamp() == null){
                    // String is empty or null
                }else {
                    viewHolder.setTimestamp(model.getTimestamp());

                }

                if(model.getLat() == null || model.getLon() == null){
                    viewHolder.setgps("GPS NÂO LOCALIZADO");
                   // n = 0;
                }else {
                    viewHolder.setgps(getAddress(model.getLon(), model.getLat()));

                }


        //    n =0;
            }

               };

        readData();

        mBlogList.setAdapter(firebaseRecyclerAdapter);

      // mBlogList.scrollToPosition(firebaseRecyclerAdapter.getItemCount() - 1);



    }

    public static class BlogViewHolder extends RecyclerView.ViewHolder {
        View mView;

        public BlogViewHolder(View itemView) {
            super(itemView);
            mView = itemView;


        }

        public void setTitle(String title) {

            TextView post_title = (TextView) mView.findViewById(R.id.mensagem);
            post_title.setText(title);
        }

        public void setRua(String ruat) {

            TextView rua = (TextView) mView.findViewById(R.id.rua);
            rua.setText(ruat);
        }

        public void setNome(String nomet) {
            TextView nome = (TextView) mView.findViewById(R.id.nome);
            nome.setText(nomet);

        }

        public void setgps(String gpst) {
            TextView gps = (TextView) mView.findViewById(R.id.gps);
            gps.setText(gpst);

        }

        String Late;
        String Lone;

        public void setLon(String Lont) {
            Lone = Lont;

            TextView lon = (TextView) mView.findViewById(R.id.lon);
            if (TextUtils.isEmpty(Lont)) {
                // String is empty or null
            } else {
                lon.setText(Lont);
            }


        }

        public void setTimestamp(Long cal) {
            TextView data = (TextView) mView.findViewById(R.id.dataehora);
          //  Calendar cale = Calendar.getInstance();
           // cale.setTimeInMillis(cal);

            SimpleDateFormat fmt = new SimpleDateFormat("dd MM yyyy hh:mm aa", Locale.getDefault());
            String date = fmt.format(cal);
            data.setText(date);

        }



        public void setLat(String Latt){
        Late = Latt;
            TextView lat = (TextView)mView.findViewById(R.id.lat);
            if(TextUtils.isEmpty(Late)){
                // String is empty or null
            }else {
                lat.setText(Latt);
            }
        }



        public void setNumero(String numerot){
            TextView numero = (TextView)mView.findViewById(R.id.numero);
            numero.setText(numerot);

        }
   public void setMensagem(String mensagemt){
       TextView mensagem = (TextView)mView.findViewById(R.id.mensagem);
       mensagem.setText(mensagemt);

   }

   public void setImage(Context ctx, String image){

            ImageView post_Image=(ImageView)mView.findViewById((R.id.post_image)  );
            Picasso.with(ctx).load(image).into(post_Image);
   }


}
public String getAddress(Double Late,Double Lone) {
    Geocoder geocoder;
    List<Address> addresses;
    geocoder = new Geocoder(this, Locale.getDefault());

    try {
        addresses = geocoder.getFromLocation(Lone, Late, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
        String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
        String city = addresses.get(0).getLocality();
        String state = addresses.get(0).getAdminArea();
        String country = addresses.get(0).getCountryName();
        String postalCode = addresses.get(0).getPostalCode();
        String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
        return address;
    } catch (IOException e) {
        e.printStackTrace();

    }
    return "GPS NAO LOCALIZADO";
}




    private void readData(){
        mDatabase.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Query lastQuery = mDatabase.child("Relatorio").orderByChild("Timestamp").limitToLast(1);
                lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        String message = dataSnapshot.child("nome").getValue(String.class);
                        String title = String.format("O morador: %s", message);
                        builder.setContentTitle("Morador Solicitou Serviço");
                        builder.setContentText(title);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        //Handle possible errors.
                    }
                });
                mBlogList.scrollToPosition(0);
                builder.setSmallIcon(R.mipmap.ic_launcher);
                builder.setContentText("Por favor vigilante, verifique.");
                NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
              //  notificationManager.notify(1, builder.build());
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

}

我希望能够以正确的顺序将我的填充视图持有人订购为时间戳

0 个答案:

没有答案