0

Hello friends how are you i am creating wallpaper app using firebase now data which is retrieve from firebase must be in descending order so when ever add new wallpaper its must on on top here is my coding please check now help i dont know how sort this iss anyone expert is here who can help solving this little issue?

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 data fetch code start from here

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



}
jcda tv
  • 3
  • 1

1 Answers1

0

You can't query data from firebase in descending order. The only way to do what you want to do is to use limitToLast(int limit) function and then reverse the data client side.

Ashvin Sharma
  • 563
  • 1
  • 5
  • 24