Reputation: 108
I'm trying to read data from database.. very basic reading process ..
The variable reference and getInstance() shown in red and many other methods and variables in the new class called ModelPrediction..
The firebase is connected and everything for me is correct but I don't know what is the problem, please help ..
package com.example.iwork;
import androidx.annotation.NonNull;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class ModelPrediction {
//Writ This is in the top
DatabaseReference reference;
//For connecting realtime with Android
reference = FirebaseDatabase.getInstance().getReference();
//Here make sure the child name is same as FB (capital or not)
reference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//To recive and display the data you need to have a class in andrid studio with String variables
User userType = dataSnapshot.getValue(User.class);
String UserType = userType.role;
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Edit :
For more clarification, the error in the reference object is create type parameter 'reference'
and Unknown class: 'reference'..
and the error for getInstance() method can't resolve symbol 'getInstance'
and all the things below and related to these two errors are also error..
Upvotes: 0
Views: 94
Reputation: 519
Oh, wait! The answer is simple. Your code is not right, because you are executing code not in a method but in a raw class. You should always try to put your code into a method, here is an example:
public class Hello {
public void foo(){
System.out.println("foo");
}
}
Your code looks like this:
public class Hello {
System.out.println("foo");
}
I hope i could help you. Your code should be reformatted into this:
package com.example.iwork;
import androidx.annotation.NonNull;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class ModelPrediction {
DatabaseReference reference;
public void doSomething() {
reference = FirebaseDatabase.getInstance().getReference();
reference.child("Users").addListenerForSingleValueEvent(new
ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User userType = dataSnapshot.getValue(User.class);
String UserType = userType.role;
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
Upvotes: 2