I'm new to firebase and I wanted to store a high score and retrieve it from Firebase Realtime database. The storage is working as intended , but I couldn't find a tutorial to retrieve the stored data. The official documentation is a bit confusing for me. Kindly help me out.
public class result extends AppCompatActivity {
TextView fscore,highs; Button pagain; String scor; int hs,scrcheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
fscore=(TextView)findViewById(R.id.finalscore);
highs=(TextView)findViewById(R.id.his);
pagain=(Button)findViewById(R.id.pagain);
scor=getIntent().getStringExtra("score");
fscore.setText(scor);
// need code here to retrieve the existing highscore value from firebase and assign it to highs textview.
//code to update highscore
scrcheck=Integer.parseInt(scor);
if(scrcheck>hs)
{
hs=scrcheck;
FirebaseDatabase.getInstance().getReference().child("highscore").setValue(hs);
}
highs.setText(Integer.toString(hs));
}
This is my Firebase database
.
Thanks in advance.
Based on the documentation on getting values:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("highscore").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("highscore: " + dataSnapshot.getValue(Long.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
Related
Button getBtn, sendBtn;
EditText edtTxt, getTxt;
FirebaseDatabase DB = FirebaseDatabase.getInstance();
DatabaseReference hisRef = DB.getReference("history");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_corp_history);
getBtn = findViewById(R.id.getbtn);
sendBtn = findViewById(R.id.sendbtn);
edtTxt = findViewById(R.id.edttxt);
getTxt = findViewById(R.id.gettxt);
}
public void sendDataToDB(View view) {
String s = edtTxt.getText().toString();
hisRef.setValue(s);
}
public void getDataFromDB(View view) {
hisRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String val = dataSnapshot.getValue(String.class);
getTxt.setText(val);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I am basically trying to create a history branch on my json tree and assign its value to the value that comes from the edit text field. After inserting the data I can see the sent data on my other edit text field but it doesn't appear on the real time database also when I refresh the app getBtn doesn't work. How can I fix this issue with firebase real-time database
I added the firebase from the tools section I don't know if it causes a problem.
In the latest update when connecting to Firebase from the Tools menu, SHA1 does not add this dairectly must be add manually.
Checking the rules in the database like this:
{
"rules": {
".read": true,
".write": true
}
}
So I have a set up where I want to get data from the Database on Firebase, I can get the URL back fine but I can't get data from it. When I try to debug it reads in query.addValueEventListener but after that it just goes straight to my list adapter. I don't know it's not getting the data. I have a similar set up on my node server which works perfectly fine, but won't work on Android for some reason
final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
Query query = database.child("exercises");
Log.i("Database query", database.child("exercises").toString());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot exerciseSnapshot: dataSnapshot.getChildren())
{
List<ExerciseList> exercises = new ArrayList<ExerciseList>();
ExerciseList exerciseList = exerciseSnapshot.getValue(ExerciseList.class);
Log.i("description/name", exerciseList.getDescription() + " " + exerciseList.getName());
exercises.add(exerciseList);
adapter = new ExerciseLoadListAdapter(mActivity, exercises);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mListView.setAdapter(adapter);
its go to adapter directly because addValueEventListener() is Asynchronous listeners , its run in background !
Try this code , it may be help you !
final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
//Query query = database.child("exercises");
//Log.i("Database query", database.child("exercises").toString());
database.child("exercises").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot exerciseSnapshot: dataSnapshot.getChildren())
{
List<ExerciseList> exercises = new ArrayList<ExerciseList>();
ExerciseList exerciseList = exerciseSnapshot.getValue(ExerciseList.class);
Log.i("description/name", exerciseList.getDescription() + " " + exerciseList.getName());
exercises.add(exerciseList);
}
adapter = new ExerciseLoadListAdapter(mActivity, exercises);
mListView.setAdapter(adapter)
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The Firebase do NOT get the data in the debug mode in real time. If you need some object from your firebase database you will need to get the object before. I face this problem a several times, thats why in some cases I use SQLite to store data from Firebase before i take any action. But, in a fragment you can not do that, you need the data in realtime. So you need to store the listener in a variable and use it after. Here in my Github page I have a fragment working fine.
ContatsFragment.java
[]'s
My app has two categories of users shop owner and buyers.
When shop owner adds a shop I use his UID and then pushkey to add a shop like this:
In the Image "83yV" and "FmNu" are the shop owners and they add 2 and 1 shop respectively.
Now for buyers, I want to show the whole list of shops in a Recycler View.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_shops_avtivity);
shopsDB = FirebaseDatabase.getInstance().getReference().child("shops");
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<Shop,ShopViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Shop, ShopViewHolder>(
Shop.class,
R.layout.shop_single_layout,
ShopViewHolder.class,
shopsDB)
}
The problem is when I point my Firebase Recycler Adapter to shopDB, it returns two empty cardView like this:
When I point it to specific child like
shopsDB = FirebaseDatabase.getInstance().getReference().child("shops").child("83yV24a3AmP15XubhPGApvlU7GE2");
It returns shops add by "83yV".
How can I get the shops added by other owners also? Preferably without altering current DB or creating one DB with all shops in it within on child.
To achieve this, you need to use getChildren() method twice, once to get all the users and second to get all the shops.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference shopsRef = rootRef.child("shops");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
for(DataSnapshot dSnapshot : ds.getChildren()) {
String name = dSnapshot.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
shopsRef.addListenerForSingleValueEvent(eventListener);
Using this code, you'll be able to display all shop names to the buyers.
Can I define a variable globally then assign it locally and again use it as another local method in Java? I tried to fetch data from FireBase database locally. Using it I want to perform some task in another local method but the problem is I could not manage to get the data to another method. Is there any way to do it?
double slatitude,slongitude,currbal;
DatabaseReference mDatabase= FirebaseDatabase.getInstance().getReference();
DatabaseReference mref,mlat,mlong,mstatus;
protected void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.travel);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String id = intent.getStringExtra(rfidreader.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
textView = (TextView) findViewById(R.id.message);
//textView.setText(id+" "+"signed in successfully");
mref=mDatabase.child(id).child("Balance");
mlat=mDatabase.child(id).child("Start").child("Lat");
mlong=mDatabase.child(id).child("Start").child("Long");
mstatus=mDatabase.child(id).child("Status");
getData(id);
}
public void getData(String input)
{
pssngrid = input;
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
currbal = dataSnapshot.child(pssngrid).child("Balance").getValue(Double.class);
status = dataSnapshot.child(pssngrid).child("Status").getValue(Integer.class);
mlatiude = dataSnapshot.child(pssngrid).child("Start").child("Lat").getValue(Double.class);
mlongittude = dataSnapshot.child(pssngrid).child("Start").child("Long").getValue(Double.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
protected void onStart() {
super.onStart();
if(currbal>=10)
{
gps = new GPSTracker(onTravel.this);
double slatitude = gps.getLatitude();
double slongitude = gps.getLongitude();
if(status==0)
{
mlat.setValue(slatitude);
mlong.setValue(slongitude);
mstatus.setValue(1);
textView.setText("Thank you,you are eligible for travelling....");
}
else if(status==1)
{
dis=HaverSineDistance(mlatitude,mlongitude,slatitude,slongitude);
fare=dis*5;
newbal=currbal-fare;
mref.setValue(newbal);
mstatus.setValue(0);
textView.setText("Distance Traveled:"+dis+"\n"+"Current Balance:"+currbal+"\n"+"Fare:"+fare+"\n"+"Net Balance:"+newbal);
}
}
else
{
textView.setText("Sorry,you are not eligible for travelling this time.Please recharge your card..");
}
There's a difference between what you're doing, and actually making things truly "global" variables.
Private instance variables are how you share variables across methods, however you might be misunderstanding the Activity lifecycle and that Firebase does not present data to your app in any guaranteed way according to it.
In other words, onStart will likely run first. Then onCreate and getData, and only after that, does the onDataChange event occur
Now you see the issue that currbal and status are never assigned until much later that you've given.
The correct way to get data to update like this is to make the UI updates from the Firebase callback. And you don't need the fields if you pass through your needed values as parameters
#Override
protected void onStart() {
super.onStart();
}
// separate this
private updateUI(String pssngrid, DataSnapshot dataSnapshot)
double currbal = dataSnapshot.child(pssngrid).child("Balance").getValue(Double.class);
int status = dataSnapshot.child(pssngrid).child("Status").getValue(Integer.class);
double mlatiude = dataSnapshot.child(pssngrid).child("Start").child("Lat").getValue(Double.class);
double mlongittude = dataSnapshot.child(pssngrid).child("Start").child("Long").getValue(Double.class);
if(currbal>=10) {
...
And
public void getData(final String input) {
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
updateUI(input, dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Also, remove all unnecessary DatabaseReference variables. You only need the one you're querying
You may want to additionally retrieve your Firebase data as a single Java object, rather than individually extracting the fields
I have an Arraylist checkOutBook containing keys. Its printing correctly to log message. However - i only want the books with matching the key of checkOutBook in the listview, But however im getting all books in database.
In the onPostResume method, Im checking the each key of the firebase realtime database with the checkOutBook Sting list, If only true, it should be added. But its getting true for each of the key in the database, however that is not present in the checkOutBook array. I dont know whats the issue here.
private ArrayList<String> checkOutBook;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
checkOutBook = new ArrayList<>();
Intent intent = getIntent();
checkOutBook =intent.getStringArrayListExtra("value");
Log.i("vvvv",checkOutBook.toString());
....
}
#Override
protected void onPostResume() {
super.onPostResume();
Log.i("yyy","onresume");
mAdapter.clear();
//to check if the university ID is already registered
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("GTA","HHH");
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(checkOutBook.contains(postSnapshot.getKey()));
{
Log.i("RRR","HHH");
BooksWithKey book = new BooksWithKey(postSnapshot.getKey(), postSnapshot.child("bookName").getValue().toString(), postSnapshot.child("author").getValue().toString(),
postSnapshot.child("copies").getValue().toString(), postSnapshot.child("publisher").getValue().toString(), postSnapshot.child("yearPublish").getValue().toString(), postSnapshot.child("callNumber").getValue().toString());
mAdapter.add(book);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w("TAG", "loadPost:onCancelled", databaseError.toException());
}
});
}
To solve this, combine this three lines of code:
private ArrayList<String> checkOutBook;
checkOutBook = new ArrayList<>();
checkOutBook =intent.getStringArrayListExtra("value");
in
ArrayList<String> checkOutBook = intent.getStringArrayListExtra("value");
Move this new line of code in your onDataChange() method right after this line: Log.i("GTA","HHH");.