3

I am trying to get random data from firebase, but I am unsure how. I want to get random data in the following two ways:

  1. when the app launches, it will pull any random quote from the list of 2000 quotes (maybe in the future the number can get upto 10000+ quotes).

  2. now if the user clicks the button (random button) I want a new random data to be shown every time the user clicks the button

The database is like this

I didn't implement a method for getting random data from Firebase, because I don't know how to do it.

I tried to implement some answers, but didn't know how. Here is the code I tried, but I wasn't sure how to use it.

 Random random = new Random();
        int position = random.nextInt(quotes_list.size());

HomeActivity

public class HomeActivity extends AppCompatActivity implements View.OnClickListener {
    TextView countTxt, quotesTxt;
    ImageView previousBtn, randomBtn, shareBtn, copyBtn, nextBtn;
    List<String> quotes_list;
    DatabaseReference databaseReference;
    Model model;
    int position = 0;
    private AdView mAdView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_activity);
        countTxt = findViewById(R.id.countText);
        quotesTxt = findViewById(R.id.quotesTextView);
        previousBtn = findViewById(R.id.backBtn);
        randomBtn = findViewById(R.id.randomBtn);
        shareBtn = findViewById(R.id.shareBtn);
        copyBtn = findViewById(R.id.copyBtn);
        nextBtn = findViewById(R.id.nextBtn);


        previousBtn.setOnClickListener(this);
        randomBtn.setOnClickListener(this);
        shareBtn.setOnClickListener(this);
        copyBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        Random random = new Random();
        int position = random.nextInt(quotes_list.size());


        databaseReference = FirebaseDatabase.getInstance().getReference("Quotes");
        model = new Model();
        quotes_list = new ArrayList<>();
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull @org.jetbrains.annotations.NotNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot1 : snapshot.getChildren()) {
                    model = dataSnapshot1.getValue(Model.class);
                    if (model != null) {
                        quotes_list.add(model.getTitle());

                    }
                }
                quotesTxt.setText(quotes_list.get(position));
                countTxt.setText(position + "/" + quotes_list.size());

            }

            @Override
            public void onCancelled(@NonNull @org.jetbrains.annotations.NotNull DatabaseError error) {
                Toast.makeText(HomeActivity.this, "Error", Toast.LENGTH_SHORT).show();

            }
        });

        // Ads

        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
            }
        });

        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.backBtn:
                back();
                break;
            case R.id.randomBtn:
                //this where i want to implement the random data when user click this button
                break;
            case R.id.copyBtn:
                copy();
                break;
            case R.id.shareBtn:
                share();
                break;
            case R.id.nextBtn:
                next();
                break;
        }

    }

    private void back() {
        if (position > 0) {
            position = (position - 1) % quotes_list.size();
            quotesTxt.setText(quotes_list.get(position));
            countTxt.setText(position + "/" + quotes_list.size());
        }
    }

    private void next() {
        position = (position + 1) % quotes_list.size();
        quotesTxt.setText(quotes_list.get(position));
        countTxt.setText(position + "/" + quotes_list.size());
    }

    private void copy() {
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("text", quotesTxt.getText());
        if (clipboardManager != null) {
            clipboardManager.setPrimaryClip(clipData);
        }
        Toast.makeText(getApplicationContext(), "Copied", Toast.LENGTH_SHORT).show();
    }

    private void share() {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, quotesTxt.getText());
        startActivity(Intent.createChooser(intent, "Share to"));
    }

}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    `it will pull any random quote from the list of 2000 quotes.` personally, this seems quite inconvenient or irrelevant, why not just load all 2000 or, for that matter, load X amount of quotes on to the user's device, then pick a random quote from the device ? if you're trying to build logic in to your data retrieval then perhaps building your own api would be a better choice, otherwise, leave the logic for the app – a_local_nobody May 30 '22 at 14:16
  • yes but the issue is i will make that 2000 list to 10000+ list of quotes after sometime so maybe its not good (im asking is it good ?), if there is no issue in 10000+ qutes to store in memory can you tell me how do i do that –  May 30 '22 at 14:19
  • well, you're not trying to create something that doesn't exist, lots of apps use [paging](https://developer.android.com/topic/libraries/architecture/paging/v3-overview) for getting pages of data, perhaps something like the [work manager](https://developer.android.com/topic/libraries/architecture/workmanager) where you can store this data locally using room as your database and use work manager to periodically check if there's new data to cache to the device, realistically, i don't think 10000+ smaller entries to a db would make much of a difference – a_local_nobody May 30 '22 at 14:21
  • paging is not what I want and i guess paging is a different thing , I just want to get a random quote stored in firebase every time the user clicks a button,I'm beginner –  May 30 '22 at 14:24
  • you will probably be able to get random data by assigning a number to a variable and then just going to that in firebase, ie : `"q(concatenated with my random number)"`. write the code for how you would get the content from q1 in your picture, then see if you can't just use q and a random variable for that – a_local_nobody May 30 '22 at 14:29
  • 1
    I dont get you nicely @Player91. Do you want 1 random quote or 10000 random quotes? – Sambhav Khandelwal May 30 '22 at 14:57
  • @Sambhav.K ok i explain i have 10000 quotes in firebase now what i want is when user clicks a button (lets name it randombtn) i want to get any one quote from that 10k list randomly , and this reapts as many times when the user clicks the randombtn –  May 30 '22 at 15:21
  • @Sambhav.K also when the app launch i want to get 1 random quote from that 10k list of quote –  May 30 '22 at 15:22
  • @Sambhav.K if u dont understand or having any confusion please ask –  May 30 '22 at 15:24
  • So, what is not working as intended? I can see that getting the random quote in the opening of the app works fine. Now, you can copy the same code in the click of the button – Sambhav Khandelwal May 30 '22 at 15:24
  • And `Here is the code I tried, but I wasn't sure how to use it.` doesn't make any sense. – Sambhav Khandelwal May 30 '22 at 15:25
  • i dont know where to put that code exactly –  May 30 '22 at 15:31

0 Answers0