如何按降序检索Firebase数据

时间:2019-10-21 04:51:46

标签: java android firebase firebase-realtime-database

朋友您好,我现在如何使用Firebase创建墙纸应用程序,从Firebase检索的数据必须按降序排列,所以当添加新墙纸时,其必须放在最上面,这是我的编码,请现在检查,我不知道如何排序这是这里能帮助解决这个小问题的专家吗?

package saying.qoute.best.bestquotesaying;

import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ProgressBar;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import net.danlew.android.joda.JodaTimeAndroid;

import org.joda.time.DateTime;
import org.joda.time.Days;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WallpapersActivity extends AppCompatActivity {
Toolbar toolbar;

    List<Wallpaper> wallpaperList;
    RecyclerView recyclerView;
    WallpapersAdapter adapter;
    List<Wallpaper>favList;
    DatabaseReference dbWallpapers, dbFavs;
    ProgressBar progressBar;
    private AdView mAdView;
    private  int count=0;
    private static SharedPreferences sharedPreferences;
    @Override


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallpapers);

        Intent intent = getIntent();
        final String category = intent.getStringExtra("category");
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle(category);
        setSupportActionBar(toolbar);
        JodaTimeAndroid.init(this);
        AdView adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
        mAdView = findViewById(R.id.adView);

        sharedPreferences=getSharedPreferences("TimeStamp",MODE_PRIVATE);
        final String getcickdate=sharedPreferences.getString("currentdate",null);
        count=sharedPreferences.getInt("count",0);

        if(getcickdate!=null){
            Date date=new Date();
            SimpleDateFormat format=new SimpleDateFormat("dd-MM-yyyy");
            String currnetdate=format.format(date);
            Date date1 = null;
            Date date2 = null;
            try {
                date1 = format.parse(getcickdate);
                date2 = format.parse(currnetdate);
                DateTime dt1 = new DateTime(date1);
                DateTime dt2 = new DateTime(date2);


                if(count==1){
                    if (Days.daysBetween(dt1, dt2).getDays() >= 1) {
                        AdRequest adRequest = new AdRequest.Builder().build();
                        mAdView.loadAd(adRequest);
                    }
                }

                else if(count==2){
                    if(Days.daysBetween(dt1, dt2).getDays() >=4) {
                        AdRequest adRequest = new AdRequest.Builder().build();
                        mAdView.loadAd(adRequest);
                    }

                }
                else if(count==3){
                    if(Days.daysBetween(dt1, dt2).getDays()>=6) {
                        AdRequest adRequest = new AdRequest.Builder().build();
                        mAdView.loadAd(adRequest);

                    }
                }


                else if(count==4){
                    if(Days.daysBetween(dt1, dt2).getDays()>=8) {
                        AdRequest adRequest = new AdRequest.Builder().build();
                        mAdView.loadAd(adRequest);
                    }


                }
                else if(count>=5){
                    if(Days.daysBetween(dt1, dt2).getDays() >=10) {
                        AdRequest adRequest = new AdRequest.Builder().build();
                        mAdView.loadAd(adRequest);
                    }




                }



            }

            catch (Exception e) {

                e.printStackTrace();
            }
        }
        else {
            AdRequest adRequest = new AdRequest.Builder().build();
            mAdView.loadAd(adRequest);
        }




        mAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                // Code to be executed when an ad finishes loading.
                mAdView.setVisibility(View.VISIBLE);

            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
                // Code to be executed when an ad request fails.
            }

            @Override
            public void onAdOpened() {
                // Code to be executed when an ad opens an overlay that
                // covers the screen.
            }

            @Override
            public void onAdClicked() {

            }

            @Override
            public void onAdLeftApplication() {
                count++;
                Date date=new Date();
                SimpleDateFormat format=new SimpleDateFormat("dd-MM-yyyy");
                String currnetdate=format.format(date);
                sharedPreferences=getSharedPreferences("TimeStamp",MODE_PRIVATE);
                SharedPreferences.Editor editor=sharedPreferences.edit();
                editor.putString("currentdate",currnetdate);
                editor.putInt("count",count);
                editor.commit();
                // Toast.makeText(ALLVERSE.this, "i am clicked", Toast.LENGTH_LONG).show();

            }

            @Override
            public void onAdClosed() {
                // Code to be executed when the user is about to return
                // to the app after tapping on an ad.

                //Toast.makeText(ALLVERSE.this, "ad closed", Toast.LENGTH_LONG).show();
            }
        });

// firebase数据获取代码从此处开始

        favList = new ArrayList<>();
        wallpaperList = new ArrayList<>();
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new WallpapersAdapter(this, wallpaperList);

        recyclerView.setAdapter(adapter);

        progressBar = findViewById(R.id.progressbar);
        dbWallpapers = FirebaseDatabase.getInstance().getReference("images")
                .child(category);


        if (FirebaseAuth.getInstance().getCurrentUser() != null) {
            dbFavs = FirebaseDatabase.getInstance().getReference("users")
                    .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
                    .child("favourites")
                    .child(category);
            fetchFavWallpapers(category);
        } else {
            fetchWallpapers(category);
        }

    }

    private void fetchFavWallpapers(final String category) {
        progressBar.setVisibility(View.VISIBLE);
        dbFavs.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                progressBar.setVisibility(View.GONE);
                if (dataSnapshot.exists()) {
                    for (DataSnapshot wallpaperSnapshot : dataSnapshot.getChildren()) {

                        String id = wallpaperSnapshot.getKey();
                        String title = wallpaperSnapshot.child("title").getValue(String.class);
                        String desc = wallpaperSnapshot.child("desc").getValue(String.class);
                        String url = wallpaperSnapshot.child("url").getValue(String.class);
                        Wallpaper w = new Wallpaper(id, title, desc, url, category);
                        favList.add(w);
                    }
                }
                fetchWallpapers(category);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void fetchWallpapers(final String category) {
        progressBar.setVisibility(View.VISIBLE);
        dbWallpapers.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                progressBar.setVisibility(View.GONE);
                if (dataSnapshot.exists()) {
                    for (DataSnapshot wallpaperSnapshot : dataSnapshot.getChildren()) {

                        String id = wallpaperSnapshot.getKey();
                        String title = wallpaperSnapshot.child("title").getValue(String.class);
                        String desc = wallpaperSnapshot.child("desc").getValue(String.class);
                        String url = wallpaperSnapshot.child("url").getValue(String.class);

                        Wallpaper w = new Wallpaper(id, title, desc, url, category);

                        if (isFavourite(w)) {
                            w.isFavourite=true;

                        }

                        wallpaperList.add(w);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private boolean isFavourite(Wallpaper w) {
        for (Wallpaper f: favList) {
            if (f.id.equals(w.id)) {
                return true;
            }
        }
        return false;
    }



}

1 个答案:

答案 0 :(得分:0)

您无法按降序从Firebase查询数据。做您想做的唯一方法是使用limitToLast(int limit)函数,然后反转数据客户端。