[英]'Person()' has private access in 'android.app.Person'
I am trying to insert a new country into the database without using the push() function, but the data override them in the database.我正在尝试在不使用 push() function 的情况下将新国家/地区插入数据库,但数据库中的数据会覆盖它们。 So I found to use Person class.所以我发现使用 Person class。
public class AddCountriesActivity extends AppCompatActivity {
EditText country;
Button insert;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_countries);
insert = findViewById(R.id.insert);
country = findViewById(R.id.country);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
uploadToFirebase();
}
});
}
protected void uploadToFirebase(){
String countrydb = country.getText().toString().trim();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference("Countries");
Person person = new Person();
person.setName(countrydb);
String s = "country";
root.child(s).setValue(person);
}
}
But the error occur that is given below:但是发生了下面给出的错误:
'Person()' has private access in 'android.app.Person' Cannot resolve method 'setName' in 'Person' “Person()”在“android.app.Person”中具有私有访问权限无法解析“Person”中的方法“setName”
Please guide me that where I am making a mistake.请指导我在哪里犯错。 Thank you!谢谢!
You're getting the following error:您收到以下错误:
'Person()' has private access in 'android.app.Person' 'Person()' 在 'android.app.Person' 中具有私有访问权限
Because there is no way you can create a new instance of the Person
class.因为您无法创建Person
class 的新实例。 Why?为什么? because the constructor of the class is private:因为 class 的构造函数是私有的:
private Person() {
throw new RuntimeException("Stub!");
}
So in order to write an object in the Realtime Database, the class should contain a public no-argument constructor.因此,为了在实时数据库中写入 object,class 应该包含一个公共的无参数构造函数。 That being said, to solve this issue, you have to create your own Person class.话虽如此,要解决此问题,您必须创建自己的 Person class。 At a minimum, it should look like this:至少,它应该如下所示:
class Person {
String name;
}
In which the constructor is provided by the JVM, or if you want to use encapsulation:其中构造函数由 JVM 提供,或者如果要使用封装:
class Person {
private String name;
public Person() {} //👈
Person(String name) {
this.name = name;
}
setName(String name) {
this.name = name;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.