我正在尝试从数据库中读取数据。。非常基本的阅读过程。。
红色显示的变量引用和getInstance((以及名为ModelPrediction的新类中的许多其他方法和变量。。
火球已经连接,对我来说一切都是正确的,但我不知道问题出在哪里,请帮忙。。
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) {
}
});
}
编辑:
为了更清楚地说明,引用对象中的错误为create type parameter 'reference'
和未知类:"reference"。。
以及getInstance((方法can't resolve symbol 'getInstance'
的错误下面所有与这两个错误有关的事情也是错误。。
哦,等等!答案很简单。您的代码是不对的,因为您不是在方法中执行代码,而是在原始类中执行代码。你应该总是尝试把你的代码放入一个方法中,这里有一个例子:
public class Hello {
public void foo(){
System.out.println("foo");
}
}
您的代码如下:
public class Hello {
System.out.println("foo");
}
我希望我能帮助你。您的代码应该重新格式化为:
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) {
}
});
}
}