0

I get a random number but it changes every time I press the button.Can I save them without saving them in the database? or is there a method of retrieving data from the firebase only once? Because I get data by random number.

For example:

int number = rand.nextInt(10);

output:

number = 7

run the application again:

number = 5

I use number to retrieve data from database:

ref = FirebaseDatabase.getInstance().getReference().child(number);

ValueEventListener listeners = new ValueEventListener() {
    @Override public void onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI
        User abc = dataSnapshot.getValue(User.class);

    }

    @Override public void onCancelled(DatabaseError databaseError) {
        // Getting Post failed, log a message

        // ...
    }
};
ref.addValueEventListener(listeners);

Is there a method to run this method only once?

Padmal
  • 458
  • 5
  • 15
murattssss
  • 45
  • 7

3 Answers3

0

You can use SharedPreferences to store a boolean flag that you generated the value. Then you would check for the flag in your generate method.

Looks something like this

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("MyFlag", true);
editor.commit();

and get it like this

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean flag= sharedPref.getBoolean("MyFlag", false); // default value is false

For more, you can look into the android developer guide

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

You can add it into arraylist. After that you can save whole arraylist into SharedPreferences.

Refer this link

sohel.eco
  • 337
  • 2
  • 12
0

Whenever you generate a new random number, save it in the SharedPreferences.

Try this.

        SharedPreferences sharedPref = getActivity().getPreferences("myPreference",Context.MODE_PRIVATE);
        int number = sharedPref.getInt("number",rand.nextInt(10));
        SharedPreferences.Editor ed = sharedPref.edit();
        editor.putInt("number", number);
        editor.apply();

What it will do is, when you open your application for the first time, it will look into the Shared Preferences if there is any saved number. If not, it will generate the new random number and save it in Shared Preference. Next time you open it, you will receive the number from SP.

justkvl
  • 1
  • 2